I have a DataGrid with 3 Text columns and one CheckBox column :
<DataGrid x:Name="EquipmentArray" Style="{StaticResource DataGridEquipment}">
<DataGrid.Columns>
<DataGridTextColumn Header="Description" Binding="{Binding Description}"/>
<DataGridTextColumn Header="IP Adress" Binding="{Binding IPAdress}"/>
<DataGridTextColumn Header="Connection Type" Binding="{Binding ConnectionType}"/>
<DataGridTemplateColumn Header="Choice">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGridColumns>
</DataGrid>
I would like to make it so that when the user double clicks on a row, it checks the CheckBox in the according row.
private void DataGridRow_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
// checking the checkbox in the sender's row
}
}
How could I do this and what would be the best way?
CodePudding user response:
You should add a boolean property like IsEnabled
to your data model and bind it to the CheckBox
:
DataItem.cs
class DataItem : INotifyPropertyChanged
{
// Let property raise the INotifyPropertyChanged.PropertyChanged event
public bool IsEnabled { get; set; }
}
MainWindow.xaml
<DataGrid ItemsSource="{Binding DataItems}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<EventSetter Event="PreviewMouseDoubleClick"
Handler="OnDataGridRowPreviewMouseDoubleClick" />
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Choice">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsEnabled}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGridColumns>
</DataGrid>
MainWindow.xaml.cs
private void OnDataGridRowPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var row = sender as DataGridRow;
(row.Item as DataItem).IsEnabled = true;
}