WPF,列表框项目作为其他列表框的源
WPF, Listbox items as source to other Listbox
假设您在 WPF 中有一个列表框,其中包含 1、2、3、4、5 等项目。您如何制作另一个列表框,紧挨着第一个列表框,根据 select第一个列表框中的离子?所以如果你在 Listbox 中 select "item 2" 你会在 Listbox2 中得到 2A、2B、2C 等,如果你 select "item 3" 你会得到 3A、3B、3C 等在 Listbox3
Can't embed the picture yet but here's the example of what i need
这里有一个如何根据推荐的 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");
}
}
确保您的视图模型 class 实现了 INotifyPropertyChanged 接口并引发更改通知以使其正常工作:https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx
或者,如果您的模型 class 定义为第一个 ListBox 中的每个项目都有一个 属性 集合 returns 其相关项目,您可以绑定第二个 ListBox 直接到第一个 SelectedItem 的 属性:
<ListBox x:Name="lb1" ItemsSource="{Binding Numbers}"/>
<ListBox x:Name="lb2" ItemsSource="{Binding SelectedItem.SubProperty, ElementName=lb1}" />
假设您在 WPF 中有一个列表框,其中包含 1、2、3、4、5 等项目。您如何制作另一个列表框,紧挨着第一个列表框,根据 select第一个列表框中的离子?所以如果你在 Listbox 中 select "item 2" 你会在 Listbox2 中得到 2A、2B、2C 等,如果你 select "item 3" 你会得到 3A、3B、3C 等在 Listbox3
Can't embed the picture yet but here's the example of what i need
这里有一个如何根据推荐的 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");
}
}
确保您的视图模型 class 实现了 INotifyPropertyChanged 接口并引发更改通知以使其正常工作:https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx
或者,如果您的模型 class 定义为第一个 ListBox 中的每个项目都有一个 属性 集合 returns 其相关项目,您可以绑定第二个 ListBox 直接到第一个 SelectedItem 的 属性:
<ListBox x:Name="lb1" ItemsSource="{Binding Numbers}"/>
<ListBox x:Name="lb2" ItemsSource="{Binding SelectedItem.SubProperty, ElementName=lb1}" />