开发者

How do I change when a Silverlight DataGrid updates bound data?

Currently my DataGrid(Silverlight 4) 开发者_如何学编程is updating when I step off of a cell. I need it to update whenever the value of a cell is changed.


I came to my own answer and its similar to the behavior injection used to instantly change a TextBox's binding source (see here). I subclassed DataGrid and added the following code:

    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();
    }


just implement INotifyPropertyChanged on class which you set itemssource of datagrid.

for example

 public class CustomType:INotifyPropertyChanged
 {

 }

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

add items

datagrid.ItemsSource=list;

Binding Mode=TwoWay

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜