我试图让文本 block 中所有 URI 可点击的单词。这是我采用的方法:
private static void onTextChanged(DependencyObject dependObj, DependencyPropertyChangedEventArgs e)
{
WrapPanel wrapPanel = ((HyperlinkTextBlock)dependObj).LayoutRoot;
wrapPanel.Children.Clear();
// TODO: use a real wordbreaker?
// adding an extra space to the end of the last word. Cry.
IList<string> words = ((string)e.NewValue).Split(' ').Select(word => word + " ").ToList();
foreach (string word in words)
{
Uri uri;
if (Uri.TryCreate(word, UriKind.Absolute, out uri))
{
// TODO the style is off - the text is too big
wrapPanel.Children.Add(new HyperlinkButton()
{
Content = word,
NavigateUri = uri,
TargetName = "_blank",
Margin = new Thickness(0),
Padding = new Thickness(0),
});
}
else
{
wrapPanel.Children.Add(new TextBlock() { Text = word, TextWrapping = TextWrapping.Wrap });
}
}
}
(我完全愿意采用更面向 XAML/声明的方式来执行此操作,但我不确定我将如何去做。)
这工作正常(除了使用真正的分词器会很好),除了 HyperlinkButton
看起来很有趣。它太大了,文本不会换行。它似乎也有一些偏移,我试图通过将 Margin
和 Padding
设置为 0 来解决这个问题,但它并没有解决问题。
还有其他想法吗?真的,我想要 HyperlinkText
而不是 HyperlinkButton
,但我不认为 Windows Phone 7 的 Silverlight 3 提供了这一点。
最佳答案
这是我通过提取超链接按钮的样式,然后对我关心的区域(如您提到的奇怪缩进)进行修改而提出的解决方案。这样,除了您要更改的内容外,行为完全相同。
当您创建超链接按钮时,还要设置样式属性,如下所示:
var button = new HyperlinkButton
{
...
Style = (Style) Resources["HyperlinkButtonWithNoIndent"]
};
然后在你的页面中,在资源中添加如下样式:
<Style x:Key="HyperlinkButtonWithNoIndent" TargetType="HyperlinkButton">
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMedium}"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="HyperlinkButton">
<Border Background="Transparent">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Pressed">
<Storyboard>
<DoubleAnimation Duration="0" To="0.5" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextElement"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="TextElement">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}">
<TextBlock x:Name="TextElement" Text="{TemplateBinding Content}" TextDecorations="Underline" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
关于Silverlight:使超链接按钮看起来像文本 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4556927/