将控件绑定到嵌套属性

时间:2012-04-20 22:59:08

标签: c# winforms linq-to-sql data-binding

基本问题,我已经详尽地搜索了一整天。

我的Account对象有一个KeyType对象,它有一个Name属性,全部由Linq到SQL生成。

My BindingSource:

var result = from account in Schema.Accounts select account as Account;
Data = new ComplexBindingList<Account>(result.ToList<Account>());
DataSource = Data;
ResetBindings(true);

Bradley Smith从博客借来的我的ComplexBindingList有这个界面:

public class ComplexBindingList<T> : List<T>, ITypedList

这适用于我的DataGridView:

Columns.Add(CreateColumn("KeyType.Name", "Key Type");

数据很好,因为此代码在异常之前工作:

var v = account.KeyType.Name;

这对我的TextBox不起作用。我得到一个异常“对象'EPM.BODA.KeyType'上的属性访问者'名称'引发了以下异常:'对象与目标类型不匹配。'”

// Controller is my BindingSource
Binding binding = EditField.DataBindings.Add("Text", Controller, "KeyType.Name");

我的总体印象是反射不能正常工作,但似乎无法找到有关如何填补空白的细节。欢呼任何帮助。

1 个答案:

答案 0 :(得分:0)

这是我到目前为止所做的一个简单的解决方法。

public virtual Binding GetBinding(string fieldName)
{
    string[] pieces = fieldName.Split('.');
    if ( pieces.GetLength(0) == 1 )
    {
        return new Binding("Text", this, fieldName);
    }
    else
    {
        return new Binding("Text",
            Current.GetType().GetProperty(pieces[0]).GetValue(Current, null), pieces[1]);
    }
}

// Calling the helper function and adding the binding
EditField.DataBindings.Add(Controller.GetBinding(mapping.FieldName));