我有很多地方使用以下XAML代码来创建超链接(这样做,所以我通过Caliburn Micro的基于约定的绑定挂钩了一个与控件同名的事件):
<Button Style="{StaticResource HyperlinkButton}" x:Name="AddFile">
<TextBlock>
<Hyperlink>Add file</Hyperlink>
</TextBlock>
</Button>
当然,在每个链接中我都会自定义名称和链接文本。我决定创建一个用户控件来简化这一过程。 HyperlinkButton.xaml文件中的XAML如下所示:
<UserControl x:Class="SampleApp.UserControls.HyperlinkButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
>
<Button Style="{StaticResource HyperlinkButton}">
<TextBlock>
<Hyperlink>
<TextBlock Text="{Binding Path=LinkText}"/>
</Hyperlink>
</TextBlock>
</Button>
</UserControl>
在我的代码隐藏中,我为LinkText创建了一个DependencyProperty:
public static readonly DependencyProperty LinkTextProperty = DependencyProperty.Register("LinkText",
typeof(string),
typeof(HyperlinkButton),
new UIPropertyMetadata("Fill in LinkText", new PropertyChangedCallback(OnLinkTextChanged), new CoerceValueCallback(OnCoerceLinkText)));
public string LinkText
{
get { return (string)GetValue(LinkTextProperty); }
set { SetValue(LinkTextProperty, value); }
}
最后,我试图在另一个文件中使用该控件:
<uc:HyperlinkButton LinkText="Add File" x:Name="AddFile"/>
屏幕上实际上没有显示任何内容(好吧,除了我预期链接的空白点)。
我在哪里错了?
答案 0 :(得分:2)
UserControl中的绑定绑定到HyperlinkButton.DataContext.LinkText
,而不是Hyperlink.LinkText
您需要更改绑定的源以指向HyperlinkButton对象,而不是使用默认的.DataContext进行绑定。
<TextBlock Text="{Binding Path=LinkText,
RelativeSource={RelativeSource AncestorType={x:Type local:HyperlinkButton}}}"/>