根据对另一个列表框的选择来填充WPF列表框 [英] Populate WPF listbox based on selection of another listbox

查看:94
本文介绍了根据对另一个列表框的选择来填充WPF列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到observablecollection的列表框.可观察的集合包含一个对象列表,每个对象都有其自己的可观察的集合.我想要的是单击第一个列表框中的一个项目,并将其列表显示在第二个列表框中.我可以在纯WPF中做到这一点吗?

I have a listbox that is bound to an observablecollection. The observable collection contains a list of objects, each with it's own observablecollection. What i want is to click an item in the first listbox and have it's list of things displayed in the second listbox. Can I do this in pure WPF?

推荐答案

只需将第二个列表框的ItemsSource绑定到第一个列表框的SelectedItem.

Just bind the ItemsSource of the second listbox to the SelectedItem of the first list box.

这是一些代码.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        TestItems = new ObservableCollection<Test>();
        InitializeComponent();

        for (int i = 0; i < 5; i++)
            TestItems.Add(InitTest(i));
    }

    public ObservableCollection<Test> TestItems { get; set; }

    private Test InitTest(int index)
    {
        Test test = new Test();
        test.Name  = "Test" + index.ToString();
        test.Test2Items =  new ObservableCollection<Test2>();

        for (int i = 0; i <= index; i++)
        {
            Test2 test2 = new Test2();
            test2.Label = test.Name + "_label" + i.ToString();
            test.Test2Items.Add(test2);
        }
        return test;
    }
}

public class Test
{
    public string Name { get; set; }
    public ObservableCollection<Test2> Test2Items { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

public class Test2
{
    public string Label { get; set; }
    public override string ToString()
    {
        return Label;
    }
}

Xaml

 <Window x:Class="WpfApplication1.MainWindow"
        x:Name="MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Example" Height="300" Width="400">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <ListBox x:Name="ListBox1" Grid.Column="0" ItemsSource="{Binding TestItems, ElementName=MyWindow}" />
        <ListBox Grid.Column="1" ItemsSource="{Binding SelectedItem.Test2Items, ElementName=ListBox1}" />
    </Grid>
</Window>

这篇关于根据对另一个列表框的选择来填充WPF列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆