如何将数据源链接到另一个数据源中的值

本文关键字:数据源 另一个 链接 | 更新日期: 2023-09-27 18:29:19

我将用WinForms和C#中的一个例子来解释这个问题:

class Foo { List<Bar> Bars { get; } ... }
class Bar { ... }
var foos = new List<Foo>();

首先,我将Foo的列表设置为ListBox:的数据源

var fooListBox = new ListBox();
fooListBox.DataSource = foos;

现在我想要第二个ListBox,它的数据源始终是所选FooBars的列表(否则为null)。概念上:

var barListBox = new ListBox();
barListBox.DataSource = fooListBox.SelectedValue.Bars;

这个问题有简单的解决方案吗

我目前正在手动连接它,如下所示:

barListBox.DataSource = fooListBox.SelectedValue != null ? ((Foo)fooListBox.SelectedValue).Bars : null;
fooListBox.SelectedValueChanged += (s,e) => barListBox.DataSource = fooListBox.SelectedValue != null ? ((Foo)fooListBox.SelectedValue).Bars : null;

但我忍不住认为我忽略了一些重要的事情。

如何将数据源链接到另一个数据源中的值

相反,您可以使用BindingSource来保持对象同步。

// first binding source that points to your List of Foos
BindingSource bindingSourceFoos = new BindingSource();
bindingSourceFoos.DataSource = foos;
// create a second binding source that references the first's Bars property
BindingSource bindingSourceBars = new BindingSource(bindingSourceFoos, "Bars");
// set DisplayMember to the property in class Foo you wish to display in your listbox
fooListBox.DisplayMember = "FooName"; // my example, replace with actual name
fooListBox.DataSource = bindingSourceFoos;
// again, set DisplayMember to the property in Bar that you want to display in ListBox
barListBox.DisplayMember = "BarInfo"; // my example, replace with actual name
barListBox.DataSource = bindingSourceBars;

因此,从这一点开始,当你点击FooListBox中的某个东西时,它会自动将BarListBox的内容更改为Foo's Bar集合。

更新:

MSDN-到用户控制的数据绑定

这个链接应该告诉你你需要知道的一切,但以防万一:

像这样装饰你的用户控件:

[System.ComponentModel.LookupBindingProperties
  ("DataSource", "DisplayMember", "ValueMember", "LookupMember")]
public partial class FooSelector : UserControl, INotifyPropertyChanged

将这些成员添加到您的用户控件:

    public object DataSource
    {
        get
        {
            return fooListBox.DataSource;
        }
        set
        {
            fooListBox.DataSource = value;
        }
    }
    public string DisplayMember
    {
        get { return fooListBox.DisplayMember; }
        set { fooListBox.DisplayMember = value; }
    }
    public string ValueMember
    {
        get { return fooListBox.ValueMember; }
        set
        {
            if ((value != null) && (value != ""))
                fooListBox.ValueMember = value;
        }
    }
    public string LookupMember
    {
        get
        {
            if (fooListBox.SelectedValue != null)
                return fooListBox.SelectedValue.ToString();
            else
                return "";
        }
        set
        {
            if ((value != null) && (value != ""))
                fooListBox.SelectedValue = value;
        }
    }

然后,就像在我最初的例子中一样,您以与绑定到正常列表框相同的方式进行绑定:

// fooSelector1 is your FooSelector user control
fooSelector1.DisplayMember = "Name";
fooSelector1.DataSource = bindingSourceFoos;