我们的应用程序中的按钮具有特定的外观和感觉,这些按钮以ButtonBase
的命名样式定义,它也恰好是Button
,ToggleButton
的默认样式, RepeatButton
。
我们还有ToolbarButtons
来自ButtonBase
,并包含Text
和Icon
等额外属性。这些用于在ToolbarButton
上放置特定文字和图标。
ToolbarButtons
的主题在Themes/generic.xaml
中定义如下:
<Style TargetType="{x:Type c:ToolbarButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:ToolbarButton}">
<Button Command="{TemplateBinding Property=Command}">
.. controls to place text and icon etc ..
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
正如您所看到的,我在基于Button
的控件中使用ButtonBase
控件,并将Command
绑定到包含Command
的{{1}} }。这个hack确保我可以通过定义Button
默认样式来覆盖Toolbar
中使用的“Button”的样式。
这一切看起来效果都很好,但在Button
内使用Button
感觉不对。我还在想我是不是做对了。有什么想法吗?
答案 0 :(得分:1)
您的方法很好,但您不必在模板中使用第二个按钮,而是ContentPresenter。每次重新定义ContentControl的模板(例如按钮)时使用它。 BasedOn属性可用于覆盖特定按钮样式。
看起来像这样:
<Style TargetType="{x:Type c:ToolbarButton}" BasedOn="{StaticResource {x:Type ButtonBase}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ToolbarButton}">
<StackPanel>
<!-- Image -->
<Image Source="{TemplateBinding Image}"/>
<!-- Content -->
<ContentPresenter Content="{TemplateBinding Content}"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
您可以使用ItemsControl找到与ListBox(ListView,ItemsPresenter等)模板相同的机制。
<强>更新强>
要将您的评论记录下来,也许您应该覆盖ContentControl以将特定的Chrome应用到其中:
公共类ButtonContentControl:ContentControl {}
<Style TargetType="{x:Type local:ButtonContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ButtonContentControl}">
<!-- Specific chrome -->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后您可以在ButtonBase和ToolbarButton的模板中使用它:
&LT;
Style TargetType="{x:Type ButtonBase}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:ToolbarButton}">
<ButtonContentControl>
<!-- ContentPresenter or something else -->
</ButtonContentControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type c:ToolbarButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:ToolbarButton}">
<ButtonContentControl>
.. controls to place text and icon etc ..
</ButtonContentControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>