Sco*_*ski 8 c# binding datagrid object datagridviewcolumn
我正在使用一个具有子对象的对象(参见下面的示例).我试图绑定List<rootClass>
到数据网格.当我绑定List<>
,在包含的单元格中subObject
,我看到以下值... "namespace.subObject" ...
,字符串值正确显示.
理想情况下,我希望看到subObject
datacell中的"描述"属性.如何subObject.Description
在datacell中映射显示?
public class subObject
{
int id;
string description;
public string Description
{ get { return description; } }
}
public class rootClass
{
string value1;
subObject value2;
string value3;
public string Value1
{ get { return value1; } }
public subObject Value2
{ get { return value2; } }
public string Value3
{ get { return value3; } }
}
Run Code Online (Sandbox Code Playgroud)
如果我没有弄错,它会显示在您的subObject上调用.ToString()的结果,因此您可以覆盖它以返回Description的内容.
您是否尝试过绑定到Value1.Description?(我猜它不起作用).
我有一个可以在绑定时使用而不是List的类,它将处理这个,它实现了ITypedList,它允许集合为其对象提供更多"属性",包括计算属性.
我的文件的最后一个版本在这里:
https://gist.github.com/lassevk/64ecea836116882a5d59b0f235858044
使用:
List<rootClass> yourList = ...
TypedListWrapper<rootClass> bindableList = new TypedListWrapper<rootClass>(yourList);
bindableList.BindableProperties = "Value1;Value2.Description;Value3.Description";
gridView1.DataSource = bindableList;
Run Code Online (Sandbox Code Playgroud)
基本上,您绑定到的实例TypedList<T>
而不是List<T>
,并调整BindableProperties属性.我的工作有一些变化,包括一个只是自动构建BindableProperties,但它还没有在主干中.
您还可以添加计算属性,如下所示:
yourList.AddCalculatedProperty<Int32>("DescriptionLength",
delegate(rootClass rc)
{
return rc.Value2.Description.Length;
});
Run Code Online (Sandbox Code Playgroud)
或者使用.NET 3.5:
yourList.AddCalculatedProperty<Int32>("DescriptionLength",
rc => rc.Value2.Description.Length);
Run Code Online (Sandbox Code Playgroud)
既然你提到DataGridViewColumn
(标签),我认为你的意思是winforms.
访问子属性是一件痛苦的事; 货币管理器绑定到列表,因此您默认只能访问直接属性; 但是,如果您绝对需要使用自定义类型描述符,则可以通过此操作.您还需要使用其他标记,例如"Foo_Bar"而不是"Foo.Bar".然而,这是一个重大的,需要的知识工作的量PropertyDescriptor
,ICustomTypeDescriptor
而且很可能TypeDescriptionProvider
,而且几乎可以肯定是不值得的,
最简单的解决方法是将属性公开为shim/pass-thru:
public string Value2Description {
get {return Value2.Description;} // maybe a null check too
}
Run Code Online (Sandbox Code Playgroud)
然后绑定到"Value2Description"等.