【问题标题】:WPF, Listbox items as source to other ListboxWPF,列表框项目作为其他列表框的源
【发布时间】:2016-12-19 14:45:27
【问题描述】:

假设您在 WPF 中有一个列表框,其中包含 1、2、3、4、5 等项目。您如何在第一个列表框旁边创建另一个列表框,根据第一个列表框中的选择显示其项目?因此,如果您在 Listbox 中选择“item 2”,您将在 Listbox2 中获得 2A、2B、2C 等,如果您选择“item 3”,您将在 Listbox3 中获得 3A、3B、3C 等

Can't embed the picture yet but here's the example of what i need

【问题讨论】:

  • ItemsSource="{Binding SelectedItem.ChildCollection, ElementName=yourFirstList}"

标签: c# wpf xaml listbox items


【解决方案1】:

这里有一个如何根据推荐的 MVVM 设计模式实现这种级联组合框的示例:https://blog.magnusmontin.net/2013/06/17/cascading-comboboxes-in-wpf-using-mvvm/

您可以将第一个 ListBox 的 SelectedItem 属性绑定到视图模型的源属性。然后在这个的 setter 中设置另一个集合属性,将第二个 ListBox 的 ItemsSource 属性绑定到,例如:

<ListBox ItemsSource="{Binding Numbers}" SelectedItem="{Binding SelectedNumber}" />

<ListBox ItemsSource="{Binding SubNumbers}" />

private object _selectedNumber;
public object SelectedNumber
{
    get { return _selectedNumber; }
    set
    {
        _selectedNumber = value;
        NotifyPropertyChanged();

        //set items
        SubNumbers = new List<string> { "3A", "3B", "..." };
        NotifyPropertyChanged("SubNumbers");
    }
}

确保您的视图模型类实现 INotifyPropertyChanged 接口并引发更改通知以使其正常工作:https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

或者,如果您的模型类以这样一种方式定义,即第一个 ListBox 中的每个项目都有一个返回其相关项目的集合属性,您可以将第二个 ListBox 直接绑定到第一个 ListBox 中 SelectedItem 的属性:

<ListBox x:Name="lb1" ItemsSource="{Binding Numbers}"/>

<ListBox x:Name="lb2" ItemsSource="{Binding SelectedItem.SubProperty, ElementName=lb1}" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多