xamarin.forms listview 4列获得列点击

xamarin.forms listview 4列获得列点击,listview,xamarin.forms,multiple-columns,Listview,Xamarin.forms,Multiple Columns,我有一个普通的XAML页面,其中包含一个具有4列的ListView。 首先,我创建一个定义我的列的网格,例如: <Grid x:Name="gFirst" BackgroundColor="#4682B4"> <Grid.ColumnDefinitions> <ColumnDefinition Width="10"/> <ColumnDefin

我有一个普通的XAML页面,其中包含一个具有4列的ListView。 首先,我创建一个定义我的列的网格,例如:

<Grid x:Name="gFirst" BackgroundColor="#4682B4">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="10"/>
                    <ColumnDefinition Width="6*"/>
                    <ColumnDefinition Width="2*"/>
                    <ColumnDefinition Width="2*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="60"/>
                </Grid.RowDefinitions>
                <StackLayout x:Name="slImage" Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="0" Grid.Row="0" IsVisible="False">
                    <Label Text="" FontFamily="Trebuchet MS" FontSize="16" TextColor="White"/>
                </StackLayout>
                <StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="1" Grid.Row="0">
                    <Label Text="Mieter / Strasse" FontFamily="Trebuchet MS" FontSize="16" Margin="20,0,0,0" TextColor="White"/>
                </StackLayout>
                <StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="2" Grid.Row="0">
                    <Label Text="Vertragsbeginn" FontFamily="Trebuchet MS" FontSize="16" TextColor="White"/>
                </StackLayout>
                <StackLayout x:Name="sl3" Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="3" Grid.Row="0" IsVisible="False">
                    <Label Text="Vertragsende" FontFamily="Trebuchet MS" FontSize="16" TextColor="White"/>
                </StackLayout>
            </Grid>

然后我有一个列表视图:

<ListView x:Name="lv" RowHeight="70">  
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell Appearing="ViewCell_Appearing">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="{Binding ColumnWidthImg}" />
                                    <ColumnDefinition Width="{Binding ColumnWidth}" />
                                    <ColumnDefinition Width="{Binding ColumnWidthSec}"/>
                                    <ColumnDefinition Width="{Binding ColumnWidthThird}"/>
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                </Grid.RowDefinitions>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="0" Grid.Row="0" IsVisible="{Binding VisibleColumn}">
                                    <Image Source="{Binding ImgSource}" WidthRequest="30" HeightRequest="30">
                                        <Image.GestureRecognizers>
                                            <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" NumberOfTapsRequired="1" />
                                        </Image.GestureRecognizers>
                                    </Image>
                                </StackLayout>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="1" Grid.Row="0" Margin="20,0,0,0">
                                    <Label Text="{Binding Test1}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" />
                                    <Label Text="{Binding Test4}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" />
                                </StackLayout>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="2" Grid.Row="0">
                                    <Label Text="{Binding Test2}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" />
                                </StackLayout>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="3" Grid.Row="0" IsVisible="{Binding VisibleColumn}">
                                    <Label Text="{Binding Test3}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" />
                                </StackLayout>
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

我现在的问题是,如何检测listview中点击图像的位置? 由于图像中的点击事件,我无法获得该位置

ListView中的ItemTapped事件为我提供了单击项的对象,但不是我单击的列

我如何解决这个问题


谢谢。

您可以做的是,在所有4列中使用按钮而不是标签。 并将每个按钮的命令绑定到视图模型的4个不同命令。使用按钮的tag属性,可以绑定模型的Id,并且可以识别用户点击了哪一行

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:custom="clr-namespace:RoundedCornerViewDemo.ControlsToolkit.Custom"
    x:Class="RoundedCornerViewDemo.RoundedCornerViewPage" x:Name="ThisPage">
    <StackLayout Spacing="20" Padding="20,40,20,20" BackgroundColor="LightGray">
        <Label Text="RoundedCornerView" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="Blue"/>


            <ListView x:Name="lv" RowHeight="70">  
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell Appearing="ViewCell_Appearing" Tapped="">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="{Binding ColumnWidthImg}" />
                                    <ColumnDefinition Width="{Binding ColumnWidth}" />
                                    <ColumnDefinition Width="{Binding ColumnWidthSec}"/>
                                    <ColumnDefinition Width="{Binding ColumnWidthThird}"/>
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="*" />
                                </Grid.RowDefinitions>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="0" Grid.Row="0" IsVisible="{Binding VisibleColumn}">
                                    <Image Source="{Binding ImgSource}" WidthRequest="30" HeightRequest="30">
                                        <Image.GestureRecognizers>
                                            <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" NumberOfTapsRequired="1" />
                                        </Image.GestureRecognizers>
                                    </Image>
                                </StackLayout>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="1" Grid.Row="0" Margin="20,0,0,0">
                                    <Button Text="{Binding Test1}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" Command="{Binding Path=BindingContext.ButtonCommand, Source={x:Reference Name=ThisPage}}" CommandParameter="{Binding Id}"/>
                                    <Label Text="{Binding Test4}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" />
                                </StackLayout>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="2" Grid.Row="0">
                                    <Label Text="{Binding Test2}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" />
                                </StackLayout>
                                <StackLayout Orientation="Vertical" VerticalOptions="Center" HorizontalOptions="FillAndExpand" Grid.Column="3" Grid.Row="0" IsVisible="{Binding VisibleColumn}">
                                    <Label Text="{Binding Test3}" FontFamily="Trebuchet MS" FontSize="16" TextColor="Black" />
                                </StackLayout>
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <Label Text="RoundedCornerView" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="Blue"/>
            <Label Text="RoundedCornerView" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="Blue"/>
            <Label Text="RoundedCornerView" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="Blue"/>
            <Label Text="RoundedCornerView" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="Blue"/>
            <Label Text="RoundedCornerView" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="Blue"/>
            <Label Text="RoundedCornerView" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="Blue"/>
         </custom:RoundedCornerView>
        </StackLayout>
</ContentPage>

是的,您可以将每列的命令绑定到viewmodel的4个不同命令。 这里是阿卡利亚罗github的演示。你可以查一下

虽然它是用c#而不是xaml编码的,但您可以轻松地将其转换为xaml

主要代码是:

this.BindingContext = new MyPageViewModel();


TapGestureRecognizer tgrTrash = new TapGestureRecognizer();
            tgrTrash.SetBinding(TapGestureRecognizer.CommandProperty, new 
Binding("BindingContext.TrashCommand", source: this));
            tgrTrash.SetBinding(TapGestureRecognizer.CommandParameterProperty, ".");
类MyPageViewModel(BindingContext)

[ImplementPropertyChanged]
公共类MyPageViewModel
{
bool_isLabelEmptyVisible{get;set;}
模型_selectedItem{get;set;}
bool_istaped{get;set;}
int_count{get;set;}
整数计数{
获取{return\u count;}
设置{u count=value;
IsListViewVisible=(u计数!=0);
IsLabelEmptyVisible=(_count==0);}
}
public bool IsLabelEmptyVisible{get;set;}
公共布尔IsListViewVisible{get;set;}
公共ObservableCollection列表{get;set;}=new ObservableCollection();
公共MyPageViewModel()
{
addRows();
this.TrashCommand=新命令(异步(对象对象)=>{
尝试
{
如果(_istaped)
返回;
如果(obj!=null)
System.Diagnostics.Debug.WriteLine(“Obj不为空”);
其他的
System.Diagnostics.Debug.WriteLine(“Obj为空”);
_ISTAPP=真;
var ret=wait Application.Current.MainPage.DisplayAlert(“注意”,“删除此行?”,“是”,“否”);
如果(ret)
{
//int idx=List.IndexOf((模型)obj);
列表。删除((型号)obj);
Count=List.Count;
}
_isTapped=false;
}
捕获(例外情况除外){
_isTapped=false;
等待应用程序.Current.MainPage.DisplayAlert(“注意”,例如消息“Ok”);
}
});             
}
私有void addRows(){
添加(新型号{Description=“D1”,成本=10.0,数量=1,BackgroundColor=“#9ac16e”,TextColor=“#001833”});
}
公共模型SelectedItem{
获取{return\u selectedItem;}
设置{
_选择editem=值;
如果(_selectedItem!=null){
//Task.Run(异步()=>
//{
Device.BeginInvokeMainThread(异步()=>
{
[ImplementPropertyChanged]
public class MyPageViewModel
{
    bool _isLabelEmptyVisible { get; set; }
    Model _selectedItem { get; set; }
    bool _isTapped { get; set; }
    int _count { get; set; }

    int Count {
        get { return _count; }
        set { _count = value;
            IsListViewVisible = (_count != 0);
            IsLabelEmptyVisible = (_count == 0); }
    }

    public bool IsLabelEmptyVisible { get; set; }
    public bool IsListViewVisible { get; set; }
    public ObservableCollection<Model> List { get; set; } = new ObservableCollection<Model>();

    public MyPageViewModel()
    {

        addRows();

        this.TrashCommand = new Command(async (object obj) => {

            try
            {
                if (_isTapped)
                    return;

                if (obj != null)
                    System.Diagnostics.Debug.WriteLine("Obj is not null");
                else
                    System.Diagnostics.Debug.WriteLine("Obj IS null");


                _isTapped = true;
                var ret = await Application.Current.MainPage.DisplayAlert("Attention", "Delete this row?", "Yes", "No");

                if (ret)
                {

                    //int idx = List.IndexOf((Model)obj);

                    List.Remove((Model)obj);
                    Count = List.Count;
                }

                _isTapped = false;

            }
            catch (Exception ex) {
                _isTapped = false;
                await Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
            }
        });             
    }

    private void addRows() {

        List.Add(new Model { Description = "D1", Cost = 10.0, Qty = 1, BackgroundColor = "#9ac16e", TextColor = "#001833" });

    }

    public Model SelectedItem { 
        get { return _selectedItem; }
        set {
            _selectedItem = value;

            if (_selectedItem != null) {

                //Task.Run(async () =>
                //{
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        var ret = await Application.Current.MainPage.DisplayActionSheet("Select", "Cancel", "Destruction", new string[] { "Edit", "Delete" });


                        if (ret == "Edit")
                        {

                            PromptConfig promptConfig = new PromptConfig();
                            promptConfig.CancelText = "CANCEL";
                            promptConfig.InputType = InputType.Number;
                            promptConfig.Message = "Modify QTA";
                            promptConfig.OkText = "OK";
                            promptConfig.Title = "UPDATE";
                            PromptResult result = await UserDialogs.Instance.PromptAsync(promptConfig);
                            if (result.Ok)
                                SelectedItem.Qty = int.Parse(result.Value);

                        }
                        else if (ret == "Delete")
                        {
                            List.Remove(SelectedItem);
                            Count = List.Count;
                        }
                        else { }
                    });
                //});
            }
        }
    }

    public ICommand TrashCommand { get; protected set;}

}