i am working on a wpf project in c# using the mvvm pattern. My problem is, that i have a datagrid in my main window which uses a collection of items as the item source. It is defined like this:
<Border Grid.Column="1" Style="{StaticResource BorderStyle}" Padding="5">
<DataGrid ItemsSource="{Binding SampleCollection.Samples}"
AutoGenerateColumns="False"
CanUserAddRows="False"
Grid.Column="1"
SelectedItem="{Binding Selected, Mode=TwoWay}"
SelectionMode="Single">
But now i need a checkbox in the header of the table which binds directly to a variable in the main window view model.
<DataGrid.Columns>
<DataGridCheckBoxColumn
Binding="{Binding StrStatus, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
<DataGridCheckBoxColumn.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<CheckBox IsChecked="{Binding ActivateAllSampleSTR, Mode=TwoWay}" Background="AliceBlue" Height="16" VerticalAlignment="Top" />
</Grid>
<Grid Grid.Column="1">
<TextBlock Text="STR-Status"/>
</Grid>
</Grid>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
The idea was to use a checkbox in the table header to set a boolean in the main view model, which triggers a function which sets all Status of the bound collection to true.
CodePudding user response:
You can bind your CheckBox.IsChecked
to main view-model using RelativeSource
to take DataContext
of DataGrid
itself, for example, like this:
IsChecked="{Binding DataContext.ActivateAllSampleSTR, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"
Or maybe simpler to have your DataGrid
named, for example, <DataGrid x:Name='Grid'
and then use:
IsChecked="{Binding DataContext.ActivateAllSampleSTR, Mode=TwoWay, ElementName=Grid}"