本文介绍了处理所有超链接MouseEnter事件在一个加载松散的Flowdocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WPF的新手,正在开展我的第一个项目。我一直困在这个问题上一周,所以我试图在这里找到一些帮助。



我的应用程序中有一个FlowDocumentReader,它加载了几个FlowDocuments独立文件作为松散的xaml文件)。



我需要处理加载的文档中的所有超链接的MouseEnter事件,但是我无法在XAML中将MouseEnter =myHandler设置为这是松散的XAML文件。



有没有办法解析FlowDocument并在加载时设置处理程序?



任何其他解决方案?对于Newbie的问题,谢谢A LOT。

解决方案

加载您的 FlowDocument 您可以使用 LogicalTreeHelper 枚举所有UIElements。它将允许您找到所有超链接。然后,您可以直接订阅他们的 MouseEnter 事件。这是一个代码:

  void SubscribeToAllHyperlinks(object sender,RoutedEventArgs e)
{
var hyperlinks = GetVisuals(本).OfType<超链接>();
foreach(超链接中的var link)
link.MouseEnter + = Hyperlink_MouseEnter;
}

public static IEnumerable< DependencyObject> GetVisuals(DependencyObject root)
{
foreach(LogicalTreeHelper.GetChildren(root)中的var child).OfType< DependencyObject>())
{
yield return child;
foreach(GetVisuals(child)中的var后代)
yield返回后代;
}
}

private void Hyperlink_MouseEnter(object sender,MouseEventArgs e)
{
//做任何你想要的
}

我已经使用以下XAML进行了测试:

 < FlowDocumentReader> 
< FlowDocument>
< Paragraph>
< Hyperlink> asf< / Hyperlink>
< / Paragraph>
< / FlowDocument>
< / FlowDocumentReader>


I'm new to WPF, working on my first project. I've been stuck in this problem for a week so I'm trying to find some help here.

I have a FlowDocumentReader inside my app, wich loads several FlowDocuments (independent files as loose xaml files).

I need to handle the MouseEnter event for all the Hyperlinks in the loaded document but I cannot set MouseEnter="myHandler" in XAML as theese are loose XAML files.

Is there any way to parse de FlowDocument and set the handlers when loading it?

Any other solution? Sorry for the Newbie question, thanks A LOT in advance.

解决方案

After loading your FlowDocument you can enumerate all UIElements using LogicalTreeHelper. It will allow you to find all hyperlinks. Then you can simply subscribe to their MouseEnter event. Here is a code:

    void SubscribeToAllHyperlinks(object sender, RoutedEventArgs e)
    {
        var hyperlinks = GetVisuals(this).OfType<Hyperlink>();
        foreach (var link in hyperlinks)
            link.MouseEnter += Hyperlink_MouseEnter;
    }

    public static IEnumerable<DependencyObject> GetVisuals(DependencyObject root)
    {
        foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
        {
            yield return child;
            foreach (var descendants in GetVisuals(child))
                yield return descendants;
        }
    }

    private void Hyperlink_MouseEnter(object sender, MouseEventArgs e)
    {
        // Do whatever you want here
    }

I've tested it with following XAML:

<FlowDocumentReader>
    <FlowDocument>
        <Paragraph>
            <Hyperlink>asf</Hyperlink>
        </Paragraph>
    </FlowDocument>
</FlowDocumentReader>

这篇关于处理所有超链接MouseEnter事件在一个加载松散的Flowdocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:55