【问题标题】:Hyperlink in WPF DataGrid stopping row from being selectedWPF DataGrid 中的超链接停止选择行
【发布时间】:2012-10-14 23:48:50
【问题描述】:

我有一个带有模板列的 DataGrid,其中超链接作为模板

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBlock>
            <Hyperlink Command="{Binding Path=OpenCommand}">
                <TextBlock Text="{Binding Path=Description}" />
            </Hyperlink>
        </TextBlock>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

DataGrid 还有一个上下文菜单,其中包含所选行的命令。当用户右键单击超链接列以外的任何其他列中的行时,该行将被选中并显示上下文菜单。我遇到的问题是当用户右键单击超链接时,为了查看该行的命令,该行不会自动被选中。

问题:如何让超链接忽略鼠标右键单击,让数据网格处理事件并像在其他列中一样选择行?

【问题讨论】:

    标签: wpf datagrid hyperlink


    【解决方案1】:

    我不确定是什么导致了这种行为,但它确实很烦人。

    我不知道您是否可以对超链接或 DataGrid 做一些事情以使其工作,但我认为不能。

    幸运的是,有一个很好的解决方法。

    您可以订阅 DataGridRows 上的 MouseRightButtonDown 事件,并在引发事件时将 IsSelected 属性设置为 true。这样即使您点击Hyperlink,也会选择正确的行。

    像这样在 XAML 中添加事件处理程序:

    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <EventSetter Event="MouseRightButtonDown" Handler="DataGridRow_MouseRightButtonDown" />
        </Style>
    </DataGrid.Resources>
    

    ..并在代码隐藏中设置选择:

    protected void DataGridRow_MouseRightButtonDown(object sender, EventArgs e)
    {
        var row = (DataGridRow)sender;
        row.IsSelected = true;
    }
    

    【讨论】:

    • 我没有使用你建议的确切解决方案,但你肯定给了我正确的方向。非常感谢。
    猜你喜欢
    • 2012-03-12
    • 2023-03-21
    • 2011-02-15
    • 2013-04-19
    • 2015-11-22
    • 2011-03-31
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多