我有一个带有ComboBox的小型WPF应用程序,用户可以从项目列表中进行选择。我还有一个ListBox,我希望ListBox中的可用项目取决于当前在ComboBox中选择的项目。
假设ComboBox有以下选项:" Fruits"和"蔬菜"。 如果我选择" Fruits",ListBox将包含" Apple"," Banana"," Pear"等等,如果我选择"蔬菜"它将包含" Carrot"," Potato"等
这只是一个虚构的例子,但涵盖了我需要的东西。在我的应用程序中 - ComboBox的数据和ListBox中的任何内容都将来自外部数据源。
我该怎么做?我已经完成了视图模型与视图的绑定,并从数据源填充了ComboBox,但我需要ListBox的内容来反映ComboBox中的选定选项。
我感谢任何帮助!
由于
答案 0 :(得分:1)
制作2个列表,并根据选择将其中一个列表绑定到列表框中。 e.g:
List <string> Fruits=new List<string>(){"apple","banana",..};
List <string> Vegetables=new List<string>(){"tomato","Potato",..};
并在您的Combox选择更改事件中:
private void OComboBox1Changed(object sender, SelectionChangedEventArgs e)
{
if (ComboBox1.Selected.Item=...)
{
listbox1.ItemsSource=Fruits;
}
else
{
listbox1.ItemsSource=Vegetables;
}
}
答案 1 :(得分:0)
您可以将DependencyProperty添加到包含SelectedItem
的viewmodelpublic static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(
"SelectedItem",
typeof(YourType),
typeof(YourViewModel),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(OnSelectedItemChanged)
)
);
public YourType SelectedItem
{
get { return (YourType)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
(将YourType替换为蔬菜/水果类型和YourViewModel与您的模型类型)
并将其绑定到XAML中的Combobox SelectedItem。
<ComboBox x:Name="comboBox" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
您还需要定义一个处理PropertyChangedCallback的方法:
private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Change the listbox item source here.
}
答案 2 :(得分:0)
查看:
&lt; ComboBox ItemsSource =&#34; {Binding Options}&#34; SelectedItem =&#34; {Binding SelectedOption}&#34;宽度=&#34; 200&#34; /&GT;
&lt; ListBox ItemsSource =&#34; {Binding lst}&#34; Grid.Row =&#34; 1&#34;&GT;
视图模型:
公共类MainViewModel:INotifyPropertyChanged {
private string selectedOption;
public string SelectedOption
{
get
{
return this.selectedOption;
}
set
{
this.selectedOption = value;
this.UpdateOnOptionChange();
}
}
public List<string> Options
{
get;
set;
}
public ObservableCollection<string> lst
{
get;
set;
}
public MainViewModel()
{
this.Options = new List<string>() { "Fruits", "Vegetables" };
this.lst = new ObservableCollection<string>();
}
private void UpdateOnOptionChange()
{
this.lst.Clear();
if (this.selectedOption == "Fruits")
{
this.lst.Add("Apple");
this.lst.Add("Banana");
this.lst.Add("Pear");
}
else if (this.selectedOption == "Vegetables")
{
this.lst.Add("Carrot");
this.lst.Add("Potato");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyOnPropertyChange(string astrPropertyName)
{
if (null != this.PropertyChanged)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(astrPropertyName));
}
}
}