【问题标题】:WPF listbox binding , auto select selected item from viw ModelWPF列表框绑定,从viw模型中自动选择所选项目
【发布时间】:2020-08-07 12:05:57
【问题描述】:

我有一个 listbox 和一个 modelview ,用来绑定来自 obervable 集合的 listbox 项。

我的要求是我需要从视图模型中设置 selectedItem 以及 selectedIndex,以便用户可以看到所选项目。

希望有人能帮我解决

【问题讨论】:

    标签: c# wpf binding listbox viewmodel


    【解决方案1】:

    在您的视图模型中创建一个 SelectedItem 属性,然后您可以编写类似这样的内容

    SelectedItem="{Binding SelectedItem,UpdateSourceTrigger=PropertyChanged}"
    

    在您的 XAML 中。

    【讨论】:

    • 我希望这段代码对列表进行var charles = new Person() { FirstName = "Charles", LastName = "Darwin" }; viewModel.SelectedPerson = charles; 更改
    • 这是我的视图类public Person SelectedPerson { get { return m_SelectedPerson; } set => SetProperty(ref m_SelectedPerson, value); }中的selectedPerson属性@
    • 在我的 xaml 中我有 <StackPanel Margin="0,0,-0.4,113"> <ListBox Name="personsListBox" SelectedIndex="{Binding SelectedPerson.Index }" ItemsSource="{Binding Persons}" DisplayMemberPath="LastName" SelectedItem="{Binding SelectedPerson,UpdateSourceTrigger=PropertyChanged}" /> <Label Content="Selected person"/> <Label Content="{Binding SelectedPerson.FirstName}"/> <Label Content="{Binding SelectedPerson.LastName}"/> </StackPanel>
    • 如果您想在视图模型加载到窗口后更改它,您应该在视图模型中实现 INotifyPropertyChanged。
    • 所选项目已经在工作,我希望它反映在列表中[在 UI 中被选中]
    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多