如何通过数据绑定设置 WPF 超链接的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/140996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:40:08  来源:igfitidea点击:

How can I set the text of a WPF Hyperlink via data binding?

wpfdata-bindinghyperlink

提问by rdeetz

In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:

在 WPF 中,我想创建一个导航到对象详细信息的超链接,并且我希望超链接的文本是对象的名称。现在,我有这个:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock>

But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:

但我希望将“对象名称”绑定到对象的实际名称。我想做这样的事情:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock>

However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).

但是,Hyperlink 类没有适合数据绑定的 text 或 content 属性(即依赖属性)。

Any ideas?

有任何想法吗?

回答by Bob King

It looks strange, but it works. We do it in about 20 different places in our app. Hyperlinkimplicitly constructs a <Run/>if you put text in its "content", but in .NET 3.5 <Run/>won't let you bind to it, so you've got to explicitly use a TextBlock.

看起来很奇怪,但确实有效。我们在我们的应用程序中大约有 20 个不同的地方这样做。如果您将文本放入其“内容”中,则Hyperlink隐式构造 a <Run/>,但在 .NET 3.5 中<Run/>不允许您绑定到它,因此您必须显式使用TextBlock.

<TextBlock>
    <Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">
        <TextBlock Text="{Binding Path=Name}"/>
    </Hyperlink>
</TextBlock>


Update: Note that as of .NET 4.0 the Run.Text propertycan now be bound:

更新:请注意,从 .NET 4.0 开始,现在可以绑定Run.Text 属性

<Run Text="{Binding Path=Name}" />

回答by Jamie Clayton

This worked for me in a "Page".

这在“页面”中对我有用。

<TextBlock>
    <Hyperlink NavigateUri="{Binding Path}">
        <TextBlock Text="{Binding Path=Path}" />
    </Hyperlink>
</TextBlock>

回答by Ivan I?in

On Windows Store app (and Windows Phone 8.1 RT app) above example does not work, use HyperlinkButton and bind Content and NavigateUri properties as ususal.

在 Windows Store 应用程序(和 Windows Phone 8.1 RT 应用程序)上,上面的示例不起作用,请使用 HyperlinkBut​​ton 并像往常一样绑定 Content 和 NavigateUri 属性。