WPF DataGrid切换选择模式& CellTemplate中的按钮 [英] WPF DataGrid toggle selection mode & Button in CellTemplate

查看:132
本文介绍了WPF DataGrid切换选择模式& CellTemplate中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建POS应用程序,并且希望最终用户能够为数据网格(即I.E.)设置切换选择模式。他们可以单击多行,每个单击的项目将累积在SelectedItems属性上-也单击已选择的行将取消选择该行。我在另一个stackoverflow问题中找到了这段代码:

I'm building a POS application, and I want the end user to be able to have a toggle selection mode for the datagrid, I.E. they can click on multiple rows and each clicked item will accumulate on the SelectedItems property - also clicking on a row that was already selected will deselect the row. I found this code in another stackoverflow question:

<DataGrid.Resources>
    <Style TargetType="{x:Type DataGridCell}">
        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DoCheckRow" />
    </Style>
</DataGrid.Resources>

public void DoCheckRow(object sender, MouseButtonEventArgs e)
{
    DataGridCell cell = sender as DataGridCell;
    if (cell != null && !cell.IsEditing)
    {
        DataGridRow row = VisualHelpers.TryFindParent<DataGridRow>(cell);
        if (row != null)
        {
            row.IsSelected = !row.IsSelected;
            e.Handled = true;
            Debug.WriteLine(sender);
        }
    }
}

这实际上给了我想要切换到选择模式,但是,当我将按钮添加为CellTemplate时,单击按钮不会触发按钮命令,因为我正在设置 e.Handled = true; 将停止事件气泡。

That effectively gives me what I want as far as the toggle selection mode, however, when I add a button as a CellTemplate, the buttons command isn't fired when clicked because I'm setting e.Handled = true; in the above code which stops the event bubble. Is there a way that I can accommodate both?

推荐答案

我能够通过使用一些辅助函数来找到视觉效果,从而解决了这两种问题。孩子/父母和一些命中测试:

I was able to solve it by using some helper functions to find the visual child / parent and some hit testing:

public void DoCheckRow(object sender, MouseButtonEventArgs e)
{
    DataGridCell cell = sender as DataGridCell;
    if (cell != null && !cell.IsEditing)
    {
        DataGridRow row = VisualHelpers.TryFindParent<DataGridRow>(cell);
        if (row != null)
        {
            Button button = VisualHelpers.FindVisualChild<Button>(cell, "ViewButton");

            if (button != null)
            {
                HitTestResult result = VisualTreeHelper.HitTest(button, e.GetPosition(cell));

                if (result != null)
                {
                    // execute button and do not select / deselect row
                    button.Command.Execute(row.DataContext);
                    e.Handled = true;
                    return;
                }
            }

            row.IsSelected = !row.IsSelected;
            e.Handled = true;
        }
    }
}

不是最优雅的解决方案,但它可以与我使用的MVVM模式一起使用。

Granted its not the most elegant solution, but it works with the MVVM pattern that I use.

这篇关于WPF DataGrid切换选择模式&amp; CellTemplate中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆