【问题标题】:Adding Interaction Behavior to Hyperlink inside RichTextBlock向 RichTextBlock 内的超链接添加交互行为
【发布时间】:2017-03-13 12:03:29
【问题描述】:

我有一个RichTextBlock 和一个Hyperlink

我想在单击超链接时从我的 ViewModel 执行 Command,因此我使用了来自 Microsoft.Xaml.Behaviors 的交互 Behavior

<RichTextBlock>
    <Paragraph>
        <Hyperlink>
            <interactivity:Interaction.Behaviors>
                <core:EventTriggerBehavior EventName="Click">
                    <core:InvokeCommandAction
                        Command="{Binding ShowDocumentCommand}" />
                </core:EventTriggerBehavior>
            </interactivity:Interaction.Behaviors>
            <Hyperlink.Inlines>
                <Run Text="Some link" />
            </Hyperlink.Inlines>
        </Hyperlink>
    </Paragraph>
</RichTextBlock>

但它不起作用。它运行,但没有任何反应。单击Hyperlink 时不执行该命令。

为什么? 我应该怎么做才能让它执行命令?

【问题讨论】:

  • 看起来行为只能附加到从 FrameworkElement 派生的类。但是超链接不继承自它。
  • 好的。那么,除了在代码隐藏中添加处理程序之外,还有什么好方法可以从单击中调用命令?
  • 在下面查看我的答案。

标签: c# xaml uwp win-universal-app


【解决方案1】:

看起来行为只能附加到从 FrameworkElement 派生的类。但是超链接不继承自它。

您可以简单地使用 UWP 社区工具包中的 HyperlinkExtensions,它已经具有所需的附加属性 CommandCommandParameter。或者你可以从github复制粘贴他们的代码。

所以您的代码将如下所示:

<RichTextBlock>
    <Paragraph>
        <Hyperlink xaml:HyperlinkExtensions.Command="{Binding ShowDocumentCommand}">
            <Hyperlink.Inlines>
                <Run Text="Some link" />
            </Hyperlink.Inlines>
        </Hyperlink>
    </Paragraph>
</RichTextBlock>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多