我有一个 Xamarin.Forms xaml 页面,我在其中使用 ListView 允许用户从列表中选择单个项目。我已将 ListView 的 SelectedItem 属性绑定(bind)到我的 ViewModel 上的一个属性,这工作正常。一旦用户更改所选项目,我的 View 模型中的属性也会更新。
但是,即使我最初将 ViewModel 中的属性设置为列表中的值之一,当页面加载时 ListView 的 SelectedItem 属性为空,这反过来也将 ViewModel 属性设置为空。
我需要的是另一个方向,我希望 ListView 最初选择我在 VM 属性中设置的项目。
我可以通过在代码隐藏文件中编写额外的代码来显式设置初始选定项来组合解决方案,但这会引入额外的属性和复杂性并且非常难看。
设置 ListView 的初始选定项的正确方法是什么?谁的选定项绑定(bind)到 viewmodel 属性?
-编辑-
我被要求提供我用于绑定(bind)的代码。
这很简单,标准:
<ListView x:Name="myList" ItemsSource="{Binding Documents}" SelectedItem="{Binding SelectedDocument}">
设置为 ListView 的绑定(bind)上下文的 View 模型被实例化 之前 页面已创建,如下所示:
public class DocumentSelectViewModel : ViewModelBase
{
private Document selectedDocument;
public List<Document> Documents
{
get { return CachedData.DocumentList; }
}
public Document SelectedDocument
{
get { return selectedDocument; }
set { SetProperty(ref selectedDocument, value);
}
public DocumentSelectViewModel()
{
SelectedDocuement = CachedData.DocumentList.FirstOrDefault();
}
}
SetProperty 是一个函数,如果新值与旧的经典绑定(bind)代码不同,它会简单地触发 INotifyPropertyChanged 事件。
最佳答案
我对 XAML 有点生疏,但您不需要进行双向绑定(bind)吗?
例如。
{ Binding SelectedDocument, Mode=TwoWay }
只要 SelectedDocument 属性更改引发 INotifyPropertyChanged 事件,那么您应该获得所需的效果。
关于xaml - 绑定(bind)到 ListView 的 SelectedItem 属性时设置初始选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495409/