【发布时间】:2011-04-15 18:40:22
【问题描述】:
目前,当我离开牢房时,我的 DataGrid(Silverlight 4) 正在更新。每当单元格的值发生更改时,我都需要它进行更新。
【问题讨论】:
标签: silverlight datagrid
目前,当我离开牢房时,我的 DataGrid(Silverlight 4) 正在更新。每当单元格的值发生更改时,我都需要它进行更新。
【问题讨论】:
标签: silverlight datagrid
我得出了自己的答案,它类似于用于立即更改 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();
}
【讨论】:
只需在您设置数据网格的 itemssource 的类上实现 INotifyPropertyChanged。
例如
public class CustomType:INotifyPropertyChanged
{
}
List<CustomType> list=new List<CustomType>();
添加项目
datagrid.ItemsSource=list;
绑定模式=TwoWay
【讨论】:
INotifyPropertyChanged。当网格改变时,我需要改变发生在相反的方向,对象也应该改变。即时,无需走出牢房。