如何通过数据绑定设置 WPF 超链接的文本? [英] How can I set the text of a WPF Hyperlink via data binding?
问题描述
在 WPF 中,我想创建一个导航到对象详细信息的超链接,并且我希望超链接的文本是对象的名称.现在,我有这个:
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:
<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>
但是,Hyperlink 类没有适合数据绑定的 text 或 content 属性(即依赖属性).
However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).
有什么想法吗?
推荐答案
看起来很奇怪,但确实有效.我们在我们的应用程序中大约有 20 个不同的地方这样做.Hyperlink
隐式构造一个 <Run/>
如果您将文本放入其内容"中,但在 .NET 3.5 <Run/>
中code> 不会让您绑定到它,因此您必须明确使用 TextBlock
.
It looks strange, but it works. We do it in about 20 different places in our app. Hyperlink
implicitly 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
.
<TextBlock>
<Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">
<TextBlock Text="{Binding Path=Name}"/>
</Hyperlink>
</TextBlock>
<小时>
更新:请注意,从 .NET 4.0 开始,Run.Text 属性 现在可以绑定:
Update: Note that as of .NET 4.0 the Run.Text property can now be bound:
<Run Text="{Binding Path=Name}" />
这篇关于如何通过数据绑定设置 WPF 超链接的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!