xaml - 绑定(bind)到 ListView 的 SelectedItem 属性时设置初始选定项

标签 xaml listview binding xamarin.forms

我有一个 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/

相关文章:

c# - stackpanel 中动态添加的控件在 wpf c# 中不可见

c# - 为什么 ListView 只显示 12 个项目?

c++ - 禁用 ListView 中的项目变灰

android - EditText 与下面的建议列表

cocoa - 绑定(bind)和 NSButton

c# - 使用 MVVM 框架动态更改 ComboBox 中元素的可见性

c# - 如何绑定(bind)位于隔离存储中的图像

c++ - 从我的应用程序的 ListView 拖放到外部应用程序(例如 Windows 资源管理器)

binding - let-rebinding 和标准分配有什么区别?

binding - 将向量作为绑定(bind)传递给 for 宏时出现问题