【问题标题】:How do I change when a Silverlight DataGrid updates bound data?Silverlight DataGrid 更新绑定数据时如何更改?
【发布时间】:2011-04-15 18:40:22
【问题描述】:

目前,当我离开牢房时,我的 DataGrid(Silverlight 4) 正在更新。每当单元格的值发生更改时,我都需要它进行更新。

【问题讨论】:

    标签: silverlight datagrid


    【解决方案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();
        }
    

    【讨论】:

      【解决方案2】:

      只需在您设置数据网格的 itemssource 的类上实现 INotifyPropertyChanged。

      例如

       public class CustomType:INotifyPropertyChanged
       {
      
       }
      
       List<CustomType> list=new List<CustomType>();
      

      添加项目

      datagrid.ItemsSource=list;
      

      绑定模式=TwoWay

      【讨论】:

      • 这根本不能回答我的问题。我已经在使用INotifyPropertyChanged。当网格改变时,我需要改变发生在相反的方向,对象也应该改变。即时,无需走出牢房。
      • 如果绑定模式设置为 TwoWay 会怎样
      • {绑定路径=PropertyName,Mode=TwoWay}
      • 是的。问题不具有约束力。它的问题是控件在我离开之前不会更改数据。
      • 请您详细解释一下您的示例
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      相关资源
      最近更新 更多