Question

I have a WPF DataGrid like this:

<DataGrid
    ItemsSource="{Binding Items}"
    SelectionUnit="CellOrRowHeader">
</DataGrid>

And it's bound like this:

public partial class MainWindow : Window
{
    public ObservableCollection<Item> Items { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        Items = new ObservableCollection<Item>
        {
            new Item()
        };

        this.DataContext = this;
    }
}

public class Item
{
    private string _foo = string.Empty;
    public string Foo
    {
        get { return _foo; }
        set { _foo = value; }
    }

    private string _bar = string.Empty;
    public string Bar
    {
        get { return _bar; }
        set { _bar = value; }
    }
}

The program comes up with one Item. If I change Foo and Bar on the grid, it doesn't bind the changes, even if I switch between cells on the same row. But if i click on the next row, all the changes get bound at once. I'm guessing this has to do with the default UpdateSourceTrigger being set to LostFocus. However I want it to bind when the Cell loses focus, rather than the Row, since I have the grid configured for cell selection. How can I do this?

Was it helpful?

Solution

I am not aware of other way of changing UpdateSourceTrigger for auto generated column other then changing binding on AutoGeneratingColumn event

<DataGrid ItemsSource="{Binding Items}" SelectionUnit="CellOrRowHeader" AutoGeneratingColumn="myDataGrid_AutoGeneratingColumn"/>

and then in code

private void myDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    var column = e.Column as DataGridBoundColumn;
    if (column != null)
    {
        var binding = column.Binding as Binding;
        if (binding != null) binding.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top