【问题标题】:Xamarin listview button click get command argument valueXamarin listview 按钮单击获取命令参数值
【发布时间】:2019-08-19 15:33:41
【问题描述】:

我有这个列表视图

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

【问题讨论】:

  • 问题是CommandParamter 用于Commands,而您正在使用Clicked 事件处理程序。你可以查看这个帖子:stackoverflow.com/a/50912352/10608418。了解如何在事件处理程序中提取 CommandParameter 的值。但在我看来,更简洁的方法是使用Command 而不是Clicked 事件。

标签: xamarin xamarin.forms


【解决方案1】:

CommandParameter只能在Command中获取。

在 xaml 中:

<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

【讨论】:

  • 嗨卢卡斯。 &gt; 设备用于“块引用”,用于指示被引用的材料是由其他人说或写的。所以,如果你引用一本书、演讲、电影、杂志、手册等,那么使用它是合适的。如果您只是为自己的代码块标记标题或介绍,那么普通的段落文本更有意义。谢谢!
【解决方案2】:

我可以给你两个解决方案。 1. 您可以使用 Listview 的 ItemSelected 事件,而不是使用嵌套 StackLayout 中的按钮。在该方法中,您可以使用 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

    }

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 2014-09-27
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多