简体   繁体   English

在运行时添加属性

[英]Add property at run-time

I have a List<Data> where: 我有一个List<Data>其中:

class Data
{
   public string Name { get; set; }
}

and I use this list as the ItemsSource of a ListView . 我将此列表用作ListViewItemsSource

The View of my ListView is a GridView with one GridViewColumn (iniltially) and I bind the property Data.Name using the DisplayMemberBinding of my GridViewColumn . View我的ListViewGridView有一个GridViewColumn (iniltially)和我绑定属性Data.Name使用DisplayMemberBinding我的GridViewColumn

At run-time may happen that I add a new GridViewColumn to my GridView , so i need to bind a new property of Data to this new column. 在运行时, 可能发生了将新的GridViewColumn添加到GridView ,因此我需要将Data属性绑定到此新列。

How can I do this? 我怎样才能做到这一点?

No, you can't add "regular" properties at runtime - frankly, for what you describe might want to bind to a DataTable, and map the data in. You can do this at runtime but it is pretty complex. 不,您不能在运行时添加“常规”属性-坦白地说,您所描述的可能要绑定到DataTable并映射数据。您可以在运行时执行此操作,但这非常复杂。 DataTable has a full implementation already. DataTable已经具有完整的实现。

edit: it looks like I misunderstood the question. 编辑:看来我误解了这个问题。 If you're trying to add a property to the Data class, then I think you're out of luck. 如果您想向Data类添加属性,那么我认为您很不走运。 If you already have the property and simply want to bind that existing property to the GridView , then the code below should help. 如果您已经拥有该属性,并且只想将该现有属性绑定到GridView ,那么下面的代码应该会有所帮助。

Assuming the DataContext of the GridView is already set, you can use something similar to the example at MSDN : 假设已经设置了GridView的DataContext ,则可以使用类似于MSDN中的示例的方法:

GridViewColumn gvc = new GridViewColumn();
gvc.DisplayMemberBinding = new Binding("Surname");
gvc.Header = "Surname";
gvc.Width = 100;
myGridView.Columns.Add(gvc);

Solution with adding actual property to the data instance is rather complicated, 将实际属性添加到数据实例的解决方案相当复杂,

but maybe one of these solutions will be sufficient 但也许这些解决方案之一就足够了

You can use dynamics (more details here: dynamics ) 您可以使用动力学(更多详细信息在这里: dynamics

        dynamic dynamicData = new ExpandoObject();
        dynamicData.Name = "Name";
        dynamicData.Surname = "SomeSurname";

If you can rebuild collection of data items you can use anonymous types (more details here anonymous types ) 如果您可以重建数据项的集合,则可以使用匿名类型(更多详细信息请参见匿名类型

        var data = new Data();
        string newPropertyName = "Surname";
        var data2 = new { Name = data.Name, newPropertyName = "SomeString" };

Unless you are using DataTemplates to bind to contrete type of Data. 除非您使用DataTemplates绑定到数据的约束类型。

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

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