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



我有一个自定义控件,我想把它放在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以默认的方式样式,就像按钮一样,通过一个特殊的StyleKey,这样我就不必每次在工具栏中设置它时都设置样式(并且只在工具栏中!)。

详细说明我正在寻找一种实现工具栏的方法参见第474行

假设你已经在其他地方定义了一个键为"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>

最新更新