I have a wpf datagrid with 2 columns (ProductID and Description). ProductID column is a combobox and the Description is a Textbox. On the SelectionChanged event of the ProductID, I want to assign a value to the Description column. I need to know how to assign the value to the Description textbox for the row of the combobox that fired the SelectionChanged event. Can someone please provide a sample code? This seems so simple but I can't find an answer. Thanks
A:
Use data binding, have a structure like,
Inventory : ObservableCollection ProductID String Description
Bind ObservableCollection to your datagrid. In your ViewModel handle the ProductID's property changed and then update the description as you want.
You should read about MVVM pattern, refer http://msdn.microsoft.com/en-us/magazine/dd419663.aspx.
bjoshi
2010-10-26 03:46:04
A:
A better way to do this is by using Binding to Properties like
private ProductIdEnum m_productId;
public ProductIdEnum ProductId
{
get
{
return m_productId;
}
set
{
m_productId = value;
// Value changed...
}
}
To add an EventHandler for the SelectionChanged event of the ComboBox you could do this but I wouldn't recommend it.
<DataGridComboBoxColumn Header="ProductID"
...">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="{x:Type ComboBox}">
<EventSetter Event="SelectionChanged" Handler="ProductIdChanged" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
And in code behind
public T GetVisualParent<T>(object childObject) where T : Visual
{
DependencyObject child = childObject as DependencyObject;
while ((child != null) && !(child is T))
{
child = VisualTreeHelper.GetParent(child);
}
return child as T;
}
void ProductIdChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox comboBox = sender as ComboBox;
DataGridRow dataGridRow = GetVisualParent<DataGridRow>(comboBox);
SomeClass myClass = dataGridRow.Item as SomeClass;
// Set description
}
Meleak
2010-10-26 15:09:20
Thanks! This will work. What if I have a TextBox in DataGrid that is not bind to a Class object? It simply there to display purpose and I want to display a value.
Seecott
2010-10-29 17:01:36