c# - 如何捕获容器中的超链接单击事件 - 松散耦合的方式?

标签 c# wpf events

开始 - this question这正是我想要实现的目标,但没有遍历每个超链接的运行时开销。

有没有办法在更高级别(例如在Window中)捕获HyperlinkClick事件?

PreviewMouseDown 事件为我提供了 Hyperlink 所在的 Run 元素(通过 e.Sourcee.OriginalSource),而不是 Hyperlink 本身。

编辑 - 解决方案,感谢@nit:

Why Setter Property is not applied on Hyperlink?

最佳答案

我认为这是您可以在 PreviewMouseDown 事件处理程序中执行的操作:

private void Window_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {

            Run r = e.OriginalSource as Run;

            if(r != null)
            {
                Hyperlink hyperlink = r.Parent as Hyperlink;

                if(hyperlink != null)
                {

                    //Your code here
                }
            }
        }
    }

或者,如果您希望所有超链接点击都应重定向到 ViewModel 中的相同命令处理程序,您可以添加样式来执行此操作,如下所示:

    <Style TargetType="{x:Type Hyperlink}">
        <Setter Property="Command" Value="{Binding MyCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>
        <Setter Property="CommandParameter" Value="{Binding}"/>
    </Style>

谢谢

关于c# - 如何捕获容器中的超链接单击事件 - 松散耦合的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18516580/

相关文章:

c# - WPF View 在关闭时将 ViewModel 属性设置为 null

c# - 用特殊字符替换 C# 中的所有函数

c# - MVC 核心集 IHostingEnvironment 开发

wpf - 如何在WPF中为listviewitem添加垂直线

c# - C# WPF 中的上下文菜单绑定(bind)

javascript - 使用 JSTree 上下文菜单捕获新创建的节点

jquery - 根据 ID 按顺序显示 LI

c# - WinForm 尝试提交来自 CellValueChanged 事件的 DataGridView 更改

c# - ref 用于变量而不是函数中的参数

C# 销毁对象及其所有引用