Remotec
Remotec

Reputation: 10758

DataGrid two way binding

I have a DataGrid which shows a list of type Product. What I want to do is to have a sort of master/detail view where the grid shows the master data, and then a collection of text boxes (etc) shows the detail view. The detail is mainly for large text columns where it is not appropriate to show them in the grid due to the size of the text. There are also some data items that are shown in both the grid and the detail area.

Additionally, I need it so that both the grid and the detail area are bound together, so that a change in either causes the underlying data source to be updated - and if (e.g.) the grid is changed those changes are immediately reflected in the detail area and vice versa.

I think that this can be achieved with binding and dependency properties - but how would I set this up?

Note: as the user can control what columns are displayed on the grid the bindings are defined manually in code..

    var column = new DataGridTextColumn()
    {
        Header = attribute.Name,
        Binding = new Binding(attribute.ColumnName) { TargetNullValue = string.Empty },
        IsReadOnly = attribute.IsReadOnly
    };

    dgProductsList.Columns.Add(column);

Upvotes: 1

Views: 985

Answers (1)

brunnerh
brunnerh

Reputation: 184296

If you have named the DataGrid all you need to do is bind the DataContext of your details area to the SelectedItem of the grid, all bindings inside the area then will be to the item's properties e.g.

<DataGrid Name="dg" .../>
<Border DataContext="{Binding SelectedItem, ElementName=dg}">
    <StackPanel>
        <TextBox Text="{Binding SomeTextProperty, UpdateSourceTrigger=PropertyChanged}"/>
        <!-- ... -->
    </StackPanel>
</Border>

This is two way by default, add UpdateSourceTrigger=PropertyChanged to make the property update immediately, otherwise the text is changed when the focus leaves the TextBox.

Upvotes: 2

Related Questions