首页 > 解决方案 > Xamarin listview 按钮单击获取命令参数值

问题描述

我有这个列表视图

<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 或该列表中的某些其他属性时,我有哪些选择?

标签: xamarinxamarin.forms

解决方案


您只能 在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


推荐阅读