Xamarin.Forms ListView通过代码设置SelectedItem [英] Xamarin.Forms ListView set SelectedItem by Code
问题描述
如何在我的代码中设置ListView的SelectedItem
?我的问题是,当我在代码中预先选择一个项目时,该问题没有突出显示. ListView在xaml文件中定义.
How can I set the SelectedItem
of a ListView in my Code? My problem is, that is isn't highlighted when I preselect an item in my code. The ListView is defined in the xaml file.
<ListView ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
我的ViewModel
My ViewModel
class MyViewModel
{
List<MyItem> Items {get; set;}
MyItem SelectedItem { get; set; }
public MyViewModel()
{
Items = new List<MyItem>{ ... };
SelectedItem = Items.First();
}
}
但是,当我显示视图时,它没有突出显示所选的项目.当我单击一个项目时,它会突出显示并正确设置.我已经尝试过更改属性,但是这不会起作用,因为属性是在构造函数中设置的.
But when I show the view, it is not highlighting the selected item. When I click on an item, it is highlighted and set correctly. I've played around with property changed, but this shouldn't have an effect, because the property is set right in the constructor.
推荐答案
为使视图在MyViewModel
的属性更改时更新,该类必须实现INotifyPropertyChanged
.这是一个示例:
In order for your view to update when properties on MyViewModel
change, that class must implement INotifyPropertyChanged
. Here's an example:
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
但是重要,您必须在设置器中调用OnPropertyChanged
,因此您的SelectedItem
属性将需要如下所示:
But importantly you must call OnPropertyChanged
in your setters, so your SelectedItem
property will need to look something like this:
MyItem _selectedItem;
MyItem SelectedItem {
get {
return _selectedItem;
}
set {
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
此处提供了许多有关Xamarin形式的MVVM的良好信息:从数据绑定到MVVM
Lots of good information on MVVM in Xamarin Forms here: From Data Bindings to MVVM
这篇关于Xamarin.Forms ListView通过代码设置SelectedItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!