我正在编写自定义超链接控件(通过继承Hyperlink),在我的自定义样式中,我有多个文本块,我想允许使用我的自定义控件的用户能够为这些文本块本身分配样式并应用静态资源只有当用户没有定义任何内容时才在我的资源中使用样式。
MyHyerlink.cs
public partial class MyHyperlink : HyperlinkButton
{
public MyHyperlink()
{
this.DefaultStyleKey = typeof(MyHyperlink);
}
protected override void OnApplyTemplate()
{
_txtTitle = GetTemplateChild(TextTitle) as TextBlock;
_txtContent = GetTemplateChild(TextContent) as TextBlock;
base.OnApplyTemplate();
}
public static readonly DependencyProperty TitleStyleProperty = DependencyProperty.Register(
nameof(TitleStyle),
typeof(Style),
typeof(MyHyperlink),
new PropertyMetadata(null));
public Style TitleStyle
{
get { return (Style)GetValue(TitleStyleProperty); }
set { SetValue(TitleStyleProperty, value); }
}
public static readonly DependencyProperty DescriptionStyleProperty = DependencyProperty.Register(
nameof(DescriptionStyle),
typeof(Style),
typeof(MyHyperlink),
new PropertyMetadata(null));
public Style DescriptionStyle
{
get { return (Style)GetValue(DescriptionStyleProperty); }
set { SetValue(DescriptionStyleProperty, value); }
}
}
MyHyperlink.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Myproject.Controls">
<Style TargetType="TextBlock" x:Key="UrlTitleStyle">
<Setter Property="FontSize" Value="12" />
<Setter Property="FontWeight" Value="Bold" />
</Style>
<Style TargetType="TextBlock" x:Key="UrlDescriptionStyle">
<Setter Property="FontSize" Value="9" />
</Style>
<Style TargetType="local:MyHyperlink">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyHyperlink">
<Grid>
<!--Url Part template with parsed image and http content-->
<Border Name="UrlPartTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Image VerticalAlignment="Stretch"
Name="imgLogo"
Grid.Column="0"
/>
<TextBlock Name="txtTitle"
Grid.Column="1"
Margin="5 0"
VerticalAlignment="Center"
TextWrapping="Wrap"
MaxLines="2"
Style="{StaticResource UrlTitleStyle}"
TextTrimming="CharacterEllipsis"/>
<TextBlock Name="txtContent"
Grid.Row="1"
Grid.ColumnSpan="2"
Margin="5, 5"
TextWrapping="Wrap"
MaxLines="3"
Style="{StaticResource UrlDescriptionStyle}"
TextTrimming="CharacterEllipsis" />
</Grid>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
所以在上面的xaml中,只有当代码中声明的TitleStyle和DescriptionStyle依赖道具没有提供任何内容时,控件txtContent和txtTitle才能从静态资源中获取样式。
任何人都可以帮我解决这个问题,谢谢
答案 0 :(得分:2)
您可以像这样在控件的样式中给出属性的默认值。
<Style TargetType="local:MyHyperlink">
<Setter Property="DescriptionStyle" Value="{StaticResource UrlDescriptionStyle}"/>
...
</Style>