1

我有这个列表视图

<ListView x:Name="LocationsListView" ItemsSource="{Binding ListOfFuel}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <StackLayout>
          <StackLayout>
            <Button CommandParameter="{Binding Id}" Clicked="Button_Clicked"></Button>
          </StackLayout>
        </StackLayout>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

使用事件背后的代码,我想获取作为 ItemsSource 列表一部分的 CommandParameter,即 Id 值。

我正在这样做:

private void Button_Clicked(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    int Idvalue = btn.Id;
}

使用这种方法,应用程序抱怨按钮 Id 是 guid 值,但在列表中我将 Id 作为整数,所以我假设 Id 是按钮本身的某种标识,而不是来自项目源的实际 Id 值。

在按钮单击列表视图 ID 或该列表中的某些其他属性时,我有哪些选择?

4

2 回答 2

2

您只能 在Command中获取CommandParameter

在xml中:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="xxx.MainPage"
             x:Name="contentPage">//set the name of contentPage here
<StackLayout>
         <Button CommandParameter="{Binding Id}" Command="{Binding Source={x:Reference contentPage}, Path=BindingContext.ClickCommand}"></Button>
</StackLayout>

在您的 ViewModel 中:

public ICommand ClickCommand { get; set; }

//...

public MyViewModel()
{
   //...

   ClickCommand = new Command((arg)=> {

    Console.WriteLine(arg);

  });
}

这里的arg是您绑定属性Id的值的CommandParameter

于 2019-08-13T07:30:47.540 回答
0

我可以给你两个解决方案。1. 您可以使用 Listview 的 ItemSelected 事件,而不是在 Nested StackLayout 中使用 Button。在该方法中,您可以使用 e.SelectedItem 获取整个 Item 并将其转换为您的类类型

ListView.ItemSelected += (object sender, SelectedItemChangedEventArgs e) =>
{
    var item = (YourClass) e.SelectedItem;

    // now you can any property of YourClass.  
};
  1. 你可以找到最高的Parent,然后得到它的BindingContext。

    private void Button_Clicked(object sender, EventArgs e) { StackLayout stc = ((sender as Button).Parent as StackLayout).Parent as StackLayout; // 然后获取BindingContext

    }

于 2019-08-19T07:33:41.817 回答