开发者

How to assign a value to wpf datagrid cell

开发者 https://www.devze.com 2023-01-22 03:20 出处:网络
I have a开发者_StackOverflow中文版 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 ProductI

I have a开发者_StackOverflow中文版 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 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
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消