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

rde*_*etz 124 data-binding wpf hyperlink

在WPF中,我想创建一个导航到对象细节的超链接,我希望超链接的文本是对象的名称.现在,我有这个:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock>
Run Code Online (Sandbox Code Playgroud)

但我希望"对象名称"绑定到对象的实际名称.我想做这样的事情:

<TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock>
Run Code Online (Sandbox Code Playgroud)

但是,Hyperlink类没有适合数据绑定的文本或内容属性(即依赖项属性).

有任何想法吗?

Bob*_*ing 203

它看起来很奇怪,但它确实有效.我们在应用程序的大约20个不同的地方进行.Hyperlink隐式构造一个<Run/>如果你把文本放在它的"内容"中,但在.NET 3.5中<Run/>不会让你绑定它,所以你必须明确使用一个TextBlock.

<TextBlock>
    <Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">
        <TextBlock Text="{Binding Path=Name}"/>
    </Hyperlink>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

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

<Run Text="{Binding Path=Name}" />
Run Code Online (Sandbox Code Playgroud)

  • 它只是我或这是否阻止链接实际工作? (4认同)

小智 8

这对我来说是一个"页面".

<TextBlock>
    <Hyperlink NavigateUri="{Binding Path}">
        <TextBlock Text="{Binding Path=Path}" />
    </Hyperlink>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)