【问题标题】:Binding a control to a nested property将控件绑定到嵌套属性
【发布时间】:2012-05-02 12:47:48
【问题描述】:

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

My Account 对象有一个 KeyType 对象,它有一个 Name 属性,都是由 Linq to SQL 生成的。

我的绑定来源:

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;

这不适用于我的文本框。我得到一个异常“对象'EPM.BODA.KeyType'上的属性访问器'名称'引发以下异常:'对象与目标类型不匹配。'”

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

我的总体印象是反射无法正常工作,但似乎无法找到有关如何填补空白的详细信息。为任何帮助干杯。

【问题讨论】:

  • 您在哪里初始化帐户?你不是说 result.KeyType.Name 吗?

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


【解决方案1】:

这是我目前所拥有的,作为一种简单的解决方法。

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2012-07-19
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多