0
votes

I have bounded a ObservableCollection to a ItemSource to a DataGrid, however, I want to retrieve (via a setter) individual properties via the ViewModel.

Ok sounds confusing so will explain.

in my ObservableCollection, I have a property called "Active" so I want this element to be set when a user clicks on or off on a the checkbox in the DataGrid.

so the XAML

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <CheckBox IsChecked="{Binding Active, Mode=TwoWay}" HorizontalAlignment="Center"></CheckBox>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

And I want this to trigger this code in the ViewModel when the box is unchecked or checked

private bool m_Active = false;

public bool Active
{
    get { return m_Active; }
    set
    {
        m_Active = value;

        OnPropertyChanged("Active");
    }
}

but even with two way mode on, it doesn't. Any reasons why?

Note: On the SelectedItem property of the DataGrid I can get the SelectedRow , so basically I want the selected Individual property!

Thanks

3
The datacontext is different. The datacontext of the checkbox will be the row item, but your property is in your viewmodel.James Sampica
I understand that, so that means I can only get the individual property from he row item for the set DataContext?user3428422

3 Answers

0
votes

It sounds like you are confusing where the datagrid is looking for the 'Active' property. Since the datagrid is bound to an Observable Collection, the objects inside the observable collection need to have the 'Active' property on them, not the view model used for the view. If, however, you actually want to bind all the rows of a datagrid to a single property on the view model, you'll need to look up the ancestor tree to find the control's data context and then bind to the 'Active' property:

<CheckBox IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.Active, Mode=TwoWay}" HorizontalAlignment="Center"></CheckBox>

But, I imagine, you are looking to bind to the 'Active' property of the object in the observable collection. Check your output window when you are running your application and you should see a binding error if that property doesn't exist on the object.

0
votes

Try using a CellEditingTemplate

<DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Active, Mode=TwoWay}" HorizontalAlignment="Center"></CheckBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>

Hope that helps

0
votes

Have you tried setting the UpdateSourceTrigger?

<CheckBox IsChecked="{Binding Active, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center"></CheckBox>