我已经设置了包含两个Button
的TextBlock
元素的样式。一个带有实际文本,另一个带有图标(来自Segoe UI Symbol)。
这是样式的代码:
<Style x:Key="ButtonSettingsStyle" TargetType="Button">
<Setter Property="Content" Value=""/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<StackPanel Background="Transparent" Orientation="Horizontal" Height="60">
<VisualStateManager.VisualStateGroups>
...
</VisualStateManager.VisualStateGroups>
<TextBlock
x:Name="Icon"
Text=""
Margin="10,0,5,0"
Width="40"
Foreground="{TemplateBinding Foreground}"
FontSize="32"
VerticalAlignment="Center"
RenderTransformOrigin="0.5,0.5"
FontFamily="Segoe UI Symbol"></TextBlock>
<TextBlock
x:Name="Text"
Text="{TemplateBinding Content}"
VerticalAlignment="Center"
Style="{StaticResource TextBlockListBoldItem}"
Foreground="{TemplateBinding Foreground}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
问题:
我还希望Icon-TextBlock有一个自定义图标,因此要自定义
Text
-property并可以这样使用(我真的不知道这应该如何工作):<Button Style="{StaticResource ButtonSettingsStyle}" Content="Settings" IconContent="" />
我该如何实现?
Content
-Setter已分配给Text-TextBlock ...谢谢你的帮助!
最佳答案
编辑:我同意@meilke的评论,但问题是您需要依赖项属性来设置TemplateBinding,因此请参见下面的新类ButtonWithIcon
您应该继承Button并添加一个名为IconContent的DependencyProperty:
public class ButtonWithIcon : Button
{
public static readonly DependencyProperty IconContentProperty =
DependencyProperty.Register("IconContent", typeof (string), typeof (ButtonWithIcon), new PropertyMetadata(default(Icon)));
public string IconContent
{
get { return (string) GetValue(IconContentProperty); }
set { SetValue(IconContentProperty, value); }
}
}
并像这样使用它:
<Style x:Key="ButtonSettingsStyle" TargetType="local:ButtonWithIcon">
<Setter Property="Content" Value=""/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ButtonWithIcon">
<StackPanel Background="Transparent" Orientation="Horizontal" Height="60">
<VisualStateManager.VisualStateGroups>
...
</VisualStateManager.VisualStateGroups>
<TextBlock
x:Name="Icon"
Text="{Binding IconContent, RelativeSource={RelativeSource TemplatedParent}}"
Margin="10,0,5,0"
Width="40"
Foreground="{TemplateBinding Foreground}"
FontSize="32"
VerticalAlignment="Center"
RenderTransformOrigin="0.5,0.5"
FontFamily="Segoe UI Symbol"></TextBlock>
<TextBlock
x:Name="Text"
Text="{TemplateBinding Content}"
VerticalAlignment="Center"
Style="{StaticResource TextBlockListBoldItem}"
Foreground="{TemplateBinding Foreground}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<local:ButtonWithIcon Style="{StaticResource ButtonSettingsStyle}" Content="Settings" IconContent="" />
关于c# - 具有多个TextBlocks的XAML样式的按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19050661/