WPF的DATAGRID中对行添加单击事件

在做的一个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;

再附上一个效果图
在这里插入图片描述

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BeanGo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值