xamarin - 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 或该列表中的某些其他属性时,我有哪些选择?
解决方案
您只能 在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
推荐阅读
- python - 如何用python打开.ink文件
- python - 如何在函数中获取参数字符串?
- javascript - 反应:保护页面与本地存储反应
- docker - 在 Kubernetes 上部署 Dind 并保护 Docker Registry(冒号问题)
- react-redux - 错误类型错误:makeStore 不是函数
- javascript - map 函数和 for 循环的问题。为什么结果总是“8”?
- r - tolower () 不适用于土耳其语字符
- java - 无法通过命令行运行Java程序,但可以使用Eclipse运行
- flutter - Flutter 切换收音机小部件
- javascript - 是否可以获取或存储以前的重定向 url?