在做的一个c#的项目中发现Datagrid没办法直接对鼠标单击进行响应,
调用MouseDown事件也需要点击某一行第二次才能响应。
所以借助EventSetter来简单的实现了一个。
界面部分的代码
<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="10,38,0,0"
VerticalAlignment="Top" Height="257" FontSize="13.333"
AutoGenerateColumns="False" AlternationCount="2" CanUserAddRows="False"
MinWidth="504" Width="513" SelectionUnit="FullRow">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<EventSetter Event="GotFocus" Handler="Item_GotFocus"/>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn />
<DataGridTextColumn Header="歌曲名" Width="200" Binding="{Binding Path=Title}" IsReadOnly="True"/>
<DataGridTextColumn Header="艺术家" Width="127" Binding="{Binding Path=Artist}" IsReadOnly="True"/>
<DataGridTextColumn Header="专辑" Width="140" Binding="{Binding Path=Album}" IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
对应的c#的代码
private void Item_GotFocus(object sender, RoutedEventArgs e)
{
var item = (DataGridRow)sender;
FrameworkElement objElement = dataGrid.Columns[0].GetCellContent(item);
if (objElement != null)
{
CheckBox objChk = (CheckBox)objElement;
objChk.IsChecked = !objChk.IsChecked;
}
}
附上用mousedown事件的代码
private void DataGrid_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var se = dataGrid.SelectedItem;
FrameworkElement objElement = dataGrid.Columns[0].GetCellContent(se);
if (objElement != null)
{
CheckBox objChk = (CheckBox)objElement;
objChk.IsChecked = !objChk.IsChecked;
}
}
}
需要在这个界面的构造函数中添加
dataGrid.MouseDown += DataGrid_MouseDown;