Reputation: 217
I have a datagrid bound to an ObservableCollection<MyClass>
, and I have another datagrid which has two DataGridTextColumns - Name and Value. The Name column is prepopulated with the names of properties whose values should be displayed in the Value column. MyClass implements INotifyPropertyChanged
, so any change in the properties of MyClass
objects updates the first datagrid. Now, I would like to display the properties of the currently selected object (SelectedItem) of the first datagrid in the Value column of the second datagrid and see the property changes as they happen, like in the first datagrid. How can I accomplish this?
If you wonder about the reason, only some of the properties are displayed in the original datagrid, so the other one should display almost all of them. Is datagrid even a good choice for displaying properties in 2 columns or should I consider some other control?
Upvotes: 1
Views: 861
Reputation: 4965
This sounds like one convenient solution to a fairly common problem.
The easiest way to do this with two data grids will be for you to use some code behind and reflection. First define a type to display the Name and value of each property:
class PropertyModel {
private readonly string _name = "";
private readonly object _value = null;
public PropertyModel(string name, object value) {
_name = name ?? "";
_value = _value;
}
public string Name {
get { return _name; }
}
public object Value {
get { return _value; }
}
}
Then add an event handler to your code-behind to handle selection changes on your first datagrid:
private void _onDataGrid1SelectionChanged(object sender, SelectedCellsChangedEventArgs e) {
if (e.AddedCells.Count > 0) {
var props = new Collection<PropertyModel>();
var obj = _dataGrid1.SelectedItem;
foreach(var prop in obj.GetType().GetProperties()) {
props.Add(new PropertyModel(prop.Name, prop.GetValue(obj, null)));
}
_dataGrid2.ItemsSource = props;
}
}
Note that the code above is very rough, and will only work if DataGrid1 has SelectionMode set to Single. However this is a good place to start, if you are willing to do it quick and dirty (with an event handler).
Another great solution is to use row details. This is a pretty good intro tutorial on using row details. Of course you should also read the msdn article on the subject.
Upvotes: 2