简体   繁体   English

当comboBox中的选择更改时,动态更改listBox项

[英]changing listBox items dynamically when selection changes in comboBox

I have a comboBox which allows user to choose the selection they want. 我有一个comboBox,它允许用户选择他们想要的选择。 Based on the selection of the comboBox, i would display the listBox with a list of strings that is related to the user selection. 基于comboBox的选择,我将显示listBox以及与用户选择相关的字符串列表。

Example: User chooses "Animals" on comboBox, listBox will display "Monkeys, Horses, Pigs". 示例:用户在comboBox上选择“动物”,列表框将显示“猴子,马,猪”。

Trying to create this simple binding with minimal coding( XAML driven) but to no avail for 1 day. 尝试以最少的编码(由XAML驱动)创建这种简单的绑定,但是1天都无济于事。 Thanks in advance! 提前致谢!

Edit: 编辑:

Hi for those interested in doing it another way (using only the xaml and a class to store all your data) you could check out the answer by Jehof in the link provided. 嗨,对于那些有兴趣以另一种方式(仅使用xaml和一个类来存储所有数据)的用户,您可以在提供的链接中查看Jehof的答案。 It is quite a simple way to achieve this. 这是一种非常简单的方法。

ListBox does not display the binding data ListBox不显示绑定数据

Here is a quick example of what you are looking for(to get you started). 这是您正在寻找的快速示例(入门)。

First create an object that contains all your data and bind that to the ComboBox , the use the Comboboxes SelectedItem to populate the ListBox . 首先创建一个包含所有数据的对象,并将其绑定到ComboBox ,然后使用Comboboxes SelectedItem填充ListBox

Code: 码:

public partial class MainWindow : Window
{
    public MainWindow()
    { 
        InitializeComponent(); 
        Categories.Add(new Category { Name = "Animals", Items = new List<string> { "Dog", "Cat", "Horse" } });
        Categories.Add(new Category { Name = "Vehicles", Items = new List<string> { "Car", "Truck", "Boat" } });

    }

    private ObservableCollection<Category> _categories = new ObservableCollection<Category>();
    public ObservableCollection<Category> Categories
    {
        get { return _categories; }
        set { _categories = value; }
    }
}

public class Category
{
    public string Name { get; set; }
    public List<string> Items { get; set; }
}

Xaml: XAML:

<Window x:Class="WpfApplication10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Name="UI">

        <StackPanel DataContext="{Binding ElementName=UI}">
            <ComboBox x:Name="combo" ItemsSource="{Binding Categories}" DisplayMemberPath="Name"/>
            <ListBox ItemsSource="{Binding SelectedItem.Items, ElementName=combo}"/>
        </StackPanel>
</Window>

Result: 结果:

在此处输入图片说明在此处输入图片说明在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM