user3124134
user3124134

Reputation: 85

WPF: Bind to SelectedItem of row in DataGrid

I'm very new to WPF. I'm trying to bind to a property a row in a DataGrid so that when the row's clicked the property is set. The ItemsSource that's bound to the DataGrid is an ObservableCollection of objects of type Field.

I've tried to bind to the SelectedItem attribute on the DataGrid, but the property is not being called. I'm using almost identical code to bind to the SelectedItem of a ComboBox and this is working fine. Is there a difference that I don't know about?

<ComboBox ItemsSource="{Binding RecordTypes}" SelectedItem="{Binding SelectedRecordType}" ...
<DataGrid ItemsSource="{Binding Fields}" SelectedItem="{Binding SelectedField}" ...

In my ViewModel:

private Field SelectedField 
{
    get 
    {
        return _selectedField;
    }
    set 
    {
        _selectedField = value;
    }
}

(I will use auto properties later, it's just currently set up like this so that I could break when the property was set).

I'm not sure if it makes a difference, but the DataGrid is composed of 2 DataGridTextColumns and a DataGridTemplateColumn, which contains a checkbox.

Does anyone have any ideas? I'd really appreciate any suggestions.

To confirm, the reason that I want to listen to the click of a row is so that I can have the checkbox be checked whenever a row is clicked. If there's a better solution for this then please let me know.

Upvotes: 3

Views: 3168

Answers (1)

McGarnagle
McGarnagle

Reputation: 102793

You need to make it a two-way binding:

SelectedItem="{Binding SelectedField,Mode=TwoWay}"

That propagates changes in the view (user selects an item, SelectedItem changes) back to the viewmodel ("SelectedField" property).

Also, as @KevinDiTraglia pointed out, you need to make sure that the viewmodel property SelectedField is public, not private, otherwise the binding will not be able to access the getter/setter.

Upvotes: 1

Related Questions