I have a List<Data>
where:
class Data
{
public string Name { get; set; }
}
and I use this list as the ItemsSource
of a ListView
.
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
.
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.
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 has a full implementation already.
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. If you already have the property and simply want to bind that existing property to the GridView
, then the code below should help.
Assuming the DataContext
of the GridView is already set, you can use something similar to the example at 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 )
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.