C#嵌套的bindingsource父子关系

时间:2016-02-03 21:23:26

标签: c# data-binding nested parent-child bindingsource

为了让我的问题更容易理解,我们假设我们有一个包含2个组合框(父组合和子组合)的表单。当您选择父组合框时,子组合框的项目会相应更改。州郡就是一个很好的例子。

以下是数据模型。

public class item
{
    public string childname { get; set; }
    public item(string n) { childname = n; }
}

public class itemparent
{
    public BindingSource<item> Children { get; set; }

    public string parentName { get; set; }

    public itemparent(string parentname,item n)
    {
        Children = new BindingSource<item>();

        this.parentName = parentname;
    }
}


public class BindingSource<T> : BindingSource
{
    public new T Current
    {
        get
        {
            return (T)base.Current;
        }
    }
}

下面就是我如何绑定它们。

        public BindingSource<itemparent> bsource { get; set; }
    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            this.bsource = new BindingSource<itemparent>()
            {
                new itemparent("parent Henry",new item("child name Marry")) ,
                new itemparent("parent Todd",new item("child name Alex")) 
            };

            //this works fine
            var bnd = new Binding("DataSource", this, "bsource");
            this.combo_parents.DataBindings.Add(bnd);
            this.combo_parents.DisplayMember = "parentName";

             //not working as i expect it, does not uplate data source if the above combo changes
            //and i cannot bind to bsource.Children.Current (throws exception complaining that Current prop no found)
            combo_children.DataBindings.Add("DataSource", this, "bsource.Children");
            combo_children.DisplayMember = "childname";

        }
        catch (Exception ex)
        {
            Debugger.Break();
        }
    }
}

我也想为孩子们使用bindingsource.current,并且能够:

 Get Selected Parent Item
 bsource.Current
 Get Selected Child item
 bsource.Current.Children.Current

我知道还有其他方法可以做到,但我觉得这样做是最干净的。然后使用BindingSource在任何时候进行绑定,您可以获得所选项目。 该试用版的完整VStudio解决方案可用here

1 个答案:

答案 0 :(得分:1)

有趣的想法。但是您需要考虑一个细节 - 您无法绑定到列表对象的属性。所以你需要稍微改变你的设计。

首先,自定义绑定源类不应继承BindingSource,但应具有此{/ 1}} 属性

BindingSource

然后绑定就像这样

public class BindingSource<T>
{
    public BindingSource() { Source = new BindingSource(); }
    public BindingSource Source { get; set; }
    public T Current { get { return (T)Source.Current; } }
    public event EventHandler CurrentChanged
    {
        add { Source.CurrentChanged += value; }
        remove { Source.CurrentChanged -= value; }
    }
}