简体   繁体   English

将控件绑定到嵌套属性

[英]Binding a control to a nested property

Basic question, which I've exhaustively searched for a full day. 基本问题,我已经穷苦搜索了一整天。

My Account object has a KeyType object, which has a Name property, all generated by Linq to SQL. 我的Account对象具有一个KeyType对象,该对象具有一个Name属性,所有这些都由Linq to SQL生成。

My BindingSource: 我的BindingSource:

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

My ComplexBindingList borrowed from a blog by Bradley Smith has this interface: 我的Bradley Smith从博客借来的ComplexBindingList具有以下接口:

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

This works on my DataGridView: 这适用于我的DataGridView:

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

The data's fine, as this code works just before the exception: 数据很好,因为此代码在异常之前起作用:

var v = account.KeyType.Name;

This doesn't work on my TextBox. 这在我的TextBox上不起作用。 I get an exception "Property accessor 'Name' on object 'EPM.BODA.KeyType' threw the following exception:'Object does not match target type.'" 我收到异常“对象'EPM.BODA.KeyType'上的属性访问器'名称'引发以下异常:'对象与目标类型不匹配。'”

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

I have a general impression that reflection isn't working properly but can't seem to find the details on how to fill in the gap. 我的总体印象是反射无法正常工作,但似乎找不到有关如何填补空白的细节。 Cheers for any help. 为任何帮助加油。

This is what I have so far, as a simple workaround. 到目前为止,这是一个简单的解决方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM