我正在使用SQLite和CommunityToolkit.Mvvm.ComponentModel技术。
我有一个包含朋友信息的数据表,可以将其绑定到CollectionView上。我遵循https://www.youtube.com/watch?v=8_cqUvriwM8的教程,但尝试使用MVVM方法。
我可以通过SelectionChanged事件使其正常工作,但无法通过SelectionChangedCommand访问列表中的Friend项目。
以下是相关的XAML代码:
<CollectionView Grid.Row="2"
x:Name="FriendsList"
SelectionMode="Single"
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="{Binding .}"
SelectionChanged="OnSelectionChanged" >
以下是相关代码部分(我只是为了测试而使用xaml的代码):
public MainPage()
{
InitializeComponent();
this.BindingContext = this; //cool for binding the xaml to the code behind.
}
...
//This works fine (so why do I bother with mvvm?)
public void OnSelectionChanged(Object sender, SelectionChangedEventArgs e)
{
Console.WriteLine("Selection changed click");
Friend f = e.CurrentSelection[0] as Friend;
Console.WriteLine(f.LName);
}
//Can't get this to work, though it will register the click
public ICommand SelectionChangedCommand => new Command(SelectionChangedControl);
public void SelectionChangedControl()
{
Console.WriteLine("selection made");
}
我的想法是,如果我可以这样做来获取Friend项目,因为CommandParameter是提供对象的,按照我理解的方式?
public ICommand SelectionChangedCommand => new Command<Friend>(SelectionChangedControl);
public void SelectionChangedControl(Friend f)
{
Console.WriteLine("selection made");
}
但是这个命令现在甚至都没有触发。显然我错得离谱。
请问你有什么想法?(哦,顺便说一句,我已经尝试注释掉其中一个,以防万一。)
顺便说一下,是否有一份参考资料(不是微软文档),可以用初学者的术语解释这些东西?是否有一个关于.NET Maui的API参考?
编辑:来自https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/collectionview/selection的文档:
单选 当SelectionMode属性设置为Single时,CollectionView中只能选择一个项目。当选定一个项目时,SelectedItem属性将被设置为所选项目的值。 当此属性更改时,SelectionChangedCommand将被执行(使用SelectionChangedCommandParameter的值传递给ICommand),并且SelectionChanged事件将被触发。
我如何获取SelectionChangedCommandParameter的值,即行对象,即我的Friend对象?
编辑2:我想我需要获取CurrentSelection[0]的值,但我不知道该怎么做。
我了解到我可以像这样做(从文档中):
SelectionChangedCommand="{Binding SelectionChangedCommand}"
SelectionChangedCommandParameter="Hello G"
并且
public ICommand SelectionChangedCommand => new Command<string>( (String s) =>
{
Console.WriteLine($"selection made {s}");
});
命令被捕获并显示,因此我的想法是不使用 {Binding .} 是我不想要的,但我应该绑定什么?
SelectionChangedCommandParameter ={Binding ???}
感谢,G。
SelectionChangedCommandParameter
是否真的有用。你应该能够将SelectedItems
绑定到VM属性,并在SelectionChangedCommand
中使用该属性。 - Jason{Binding SomePropertyName}
来绑定属性。 - Jason