Search code examples
c#wpfbindingobservablecollectiontwo-way

Two-Way Collection binding


I have a table with checkboxes that is bound to the ObservableCollection > collection, I want to track changes to this collection when one of the checkboxes changes my view.

This is my code:

<UserControl.Resources>
<DataTemplate x:Key="DataTemplate_Level2">
  <CheckBox IsChecked="{Binding Path=. ,Mode=TwoWay}" Height="40" Width="50" Margin="4,4,4,4"/>
</DataTemplate>
<DataTemplate x:Key="DataTemplate_Level1">
  <ItemsControl x:Name="2st" Items="{Binding Path=. ,Mode=TwoWay}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"/>
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
  </ItemsControl>
</DataTemplate>
</UserControl.Resources>
<ItemsControl Grid.Column="1" Items="{Binding MyCollection, Mode=TwoWay}" x:Name="lst" ItemTemplate="{DynamicResource DataTemplate_Level1}" Background="Gold"/>

My viewModel property

public ObservableCollection<ObservableCollection<bool>> MyCollection
{
        get
        {
            return someCollection;
        }

        set
        {
            someCollection = value;
            RaisePropertyChanged(nameof(MyCollection));
        }
 }

view of table

How Can I pass collection data changes to view model?


Solution

  • You need to declare a new class that will become viewmodel for checkbox with property of type book and proper RaisePropertyChanged invoking. And MyCollection must be collection of collections of instances of that class rather than bool

    public class CheckboxViewModel
    {
       private bool _checkboxValue;
    
       public bool CheckboxValue
       {
          get
          {
             return _checkboxValue;
          }
          set
          {
             _checkboxValue = value;
             RaisePropertyChanged(nameof(CheckboxValue));
          }
       }
    }
    

    Make sure you have two-way binding in checkbox view to that property

    BTW - RaisePropertyChanged at setter of MyCollection raises event with wrong property name in you example.