Reputation: 638
I want to ask why Checked event triggered whenever I scroll down the datagrid with checkbox inside of it. Below is the code that I'm using:
<DataGrid x:Name="dgUser" HorizontalAlignment="Left" Margin="10,243,0,0" VerticalAlignment="Top" Width="433"
ItemsSource="{Binding Person, Mode=TwoWay}" AutoGenerateColumns="False" Height="216"
SelectedItem="{Binding SelectedPerson, Mode=TwoWay}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="ALL">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<mvvm:EventToCommand Command="{Binding DataContext.CheckAllUser,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</i:EventTrigger>
<i:EventTrigger EventName="Unchecked">
<mvvm:EventToCommand Command="{Binding DataContext.UnCheckAllUser,
RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="UserName" Binding="{Binding Path=User.UserName}" />
<DataGridTextColumn Header="Email" Binding="{Binding Path=User.Email}" />
</DataGrid.Columns>
</DataGrid>
below is the screenshot of my screen.
Upvotes: 0
Views: 853
Reputation: 169400
I want to ask why
Checked
event triggered whenever I scroll down the datagrid with checkbox inside of it.
Because of virtualization. Only the visual elements of the currently visible rows are kept in memory, and as you scroll the containers are reused for other items.
So when you scroll a row into view, the IsChecked
property of the CheckBox
gets set to the value of the IsChecked
source property and then the Checked
event is raised.
You can disable the virtualization by setting the VirtualizingPanel.IsVirtualizing
attached property of the DataGrid
to false:
<DataGrid x:Name="dgUser" ... VirtualizingPanel.IsVirtualizing="False">
Note that this may affect the scrolling performance negatively though.
The other option would to handle the logic of exeucting the command in the setter of the IsChecked
source property and get rid of the interaction triggers in the view. In the setter you can easily determine whether the property is actually set to a new value.
Upvotes: 1