首页 文章

绑定到ListView的SelectedItem属性时设置初始选定项

提问于
浏览
3

我有一个Xamarin.Forms xaml页面,其中我使用ListView允许用户从列表中选择单个项目 . 我将ListView的SelectedItem属性绑定到我的ViewModel上的属性,这很好 . 一旦用户更改了所选项目,我的viewmodel中的属性也会更新 .

但是,即使我最初将我的ViewModel中的属性设置为列表中的一个值,当页面加载ListView时,SelectedItem属性为null,这又将ViewModel属性设置为null . 我需要的是另一个方向,我希望ListView最初选择我在VM属性中设置的项目 .

我可以通过在代码隐藏文件中编写额外代码来明确设置初始选定项目来解决一个解决方案,但这会引入额外的属性和复杂性并且非常难看 .

设置所选项目的ListView的初始选定项目绑定到viewmodel属性的正确方法是什么?

-编辑-

我被要求提供我用于绑定的代码 . 它非常简单,标准:

<ListView x:Name="myList" ItemsSource="{Binding Documents}" SelectedItem="{Binding SelectedDocument}">

设置为listview的绑定上下文的视图模型将被实例化 before 页面已创建,如下所示:

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是一个函数,如果新值与旧值(经典绑定代码)不同,它会简单地改变INotifyPropertyChanged事件 .

1 回答

  • 1

    我在XAML上有点生疏,但你不需要双向绑定吗?

    例如 .

    { Binding SelectedDocument, Mode=TwoWay }
    

    只要SelectedDocument属性更改引发INotifyPropertyChanged事件,您就应该获得所需的效果 .

相关问题