当Silverlight DataGrid更新绑定数据时,如何更改?

时间:2011-04-15 18:40:22

标签: silverlight datagrid

当我离开单元格时,我的DataGrid(Silverlight 4)正在更新。每当更改单元格的值时,我都需要更新它。

2 个答案:

答案 0 :(得分:1)

我得到了自己的答案,它类似于用于立即更改TextBox的绑定源(see here)的行为注入。我将DataGrid子类化,并添加了以下代码:

    protected override void OnPreparingCellForEdit(DataGridPreparingCellForEditEventArgs e)
    {
        base.OnPreparingCellForEdit(e);

        TextBox textBox = e.EditingElement as TextBox;
        if (textBox != null)
        {
            textBox.TextChanged -= OnTextChanged;
            textBox.TextChanged += OnTextChanged;
        }

        ComboBox comboBox = e.EditingElement as ComboBox;
        if (comboBox != null)
        {
            comboBox.SelectionChanged -= OnSelectionChanged;
            comboBox.SelectionChanged += OnSelectionChanged;
        }
    }

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBox comboBox = sender as ComboBox;

        if (comboBox == null)
            return;

        BindingExpression expression = comboBox.GetBindingExpression(ComboBox.SelectedValueProperty);
        if (expression != null)
            expression.UpdateSource();

        expression = comboBox.GetBindingExpression(ComboBox.SelectedItemProperty);
        if (expression != null)
            expression.UpdateSource();
    }

    private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox textBox = sender as TextBox;

        if (textBox == null)
            return;

        BindingExpression expression = textBox.GetBindingExpression(TextBox.TextProperty);

        if (expression == null)
            return;

        expression.UpdateSource();
    }

答案 1 :(得分:0)

在您设置datagrid的itemssource的类上实现INotifyPropertyChanged。

例如

 public class CustomType:INotifyPropertyChanged
 {

 }

 List<CustomType> list=new List<CustomType>();

添加项目

datagrid.ItemsSource=list;

绑定模式= TwoWay

相关问题