为工具栏内的自定义控件定义默认样式

时间:2014-07-10 18:49:02

标签: .net wpf

我有一个自定义控件,我想放在WPF工具栏中。没问题,但我不想在工具栏中为每个项目设置特殊样式。对于本机.NET控件(如Button,Checkbox等),有一个

{x:Static ToolBar.ButtonStyleKey}

你可以覆盖。但它似乎只适用于原生控制。是否可以在工具栏中为我的自定义控件设置defaultstylekey?或者我可以实现类似的模式作为工具栏的扩展?有人知道吗?

根据要求提供了我的问题的简短例子:

<ToolBar HorizontalAlignment="Left">
    <common:MyCustomControl Style="{StaticResource DefaultStyleInsideToolBar}" />
    <Button Content="I get styled through ToolBar.ButtonStyleKey" />
 </ToolBar>

现在我希望我的CustomControl以默认方式设置样式,就像Button通过一个特殊的StyleKey一样,所以每次我在ToolBar中设置它时都不需要设置样式(并且只在ToolBar里面!)。

详细信息我正在寻找实施ToolBar See Line 474

的方法

1 个答案:

答案 0 :(得分:1)

假设您有一个已在其他地方定义过键“DefaultStyleInsideToolBar”的样式,只需在工具栏的资源中添加一个样式,该样式的目标是基于您之前定义的样式的MyCustomControl的所有实例:

<ToolBar HorizontalAlignment="Left">
    <ToolBar.Resources>
        <Style TargetType="{x:Type common:MyCustomControl}" BasedOn="{StaticResource DefaultStyleInsideToolBar}"/>
    </ToolBar.Resources>
    <common:MyCustomControl />
    <Button Content="I get styled through ToolBar.ButtonStyleKey" />
</ToolBar>