我有一个带有文本属性的Label绑定到类:
<TextBlock Visibility="Hidden" TextTrimming="WordEllipsis" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" Text="{Binding DisplayText}" TextWrapping="Wrap" FontSize="10"></TextBlock>
如果DisplayText
是链接,则应使用超链接。我绑定的类也提供Uri
和布尔isLink
。我尝试将Hyperlink
元素放在Textblock
内,并将其NavigateUri
设置为类中的Uri
,但这对我不起作用。
有人为此提供了一个干净的解决方案吗?
答案 0 :(得分:1)
我认为您可以根据属性绑定模板。
<ContentControl>
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding IsLink}" Value="True">
<Setter Property="ContentTemplate" >
<Setter.Value>
<DataTemplate>
<TextBlock>
<Hyperlink NavigateUri="{Binding DataContext.Url, RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType= ContentControl} }">
<TextBlock Text="{Binding DataContext.DisplayText, RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ContentControl} }"/>
</Hyperlink>
</TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding IsLink}" Value="False">
<Setter Property="ContentTemplate" >
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding DataContext.DisplayText,RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ContentControl} }"/>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
答案 1 :(得分:0)
您可以使用这两个控件,并根据isLink
属性更改其可见性。
<Grid>
<TextBlock>
<Hyperlink NavigateUri="{Binding Uri}"
RequestNavigate="Hyperlink_RequestNavigate">
<TextBlock Text="{Binding DisplayText}"/>
</Hyperlink>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsLink}" Value="False">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Text="{Binding DisplayText}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsLink}" Value="True">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
在代码背后:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}