2009-06-03 51 views
6

如何强制WPF中的ToolController中的UserControl使用ToolBar的默认按钮样式?使ToolBar按钮样式适用于工具栏中的UserControls

我有具有XAML是这样叫的ImageButton一个简单的用户控件:

<UserControl x:Class="myNameSpace.ImageButtonUserControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Name="imageButton" 
    > 
    <Button Style="{Binding ElementName=imageButton, Path=ButtonStyle}"> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="{Binding ElementName=imageButton, Path=ImageSource}" 
        VerticalAlignment="Center" 
        /> 
      <TextBlock Text="{Binding ElementName=imageButton, Path=Text}" 
         Style="{Binding ElementName=imageButton, Path=TextStyle}" 
         VerticalAlignment="Center" 
         /> 
     </StackPanel> 
    </Button> 
</UserControl> 

我有一些依赖属性后面的代码对那些结合的路径,一切工作正常。

直到我把它放在ToolBar中。通常,当你将按钮放在ToolBar中时,它们会被ToolBar重新设置为看起来像工具栏按钮。我已经发现如何改变这种风格(请参阅ToolBar.ButtonStyleKey。但是我怎样才能将已定义的风格应用到我的用户控件的按钮样式依赖项属性?

回答

19

哦,我的道歉!我误解了你的问题。给这个镜头:

<Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"> 
    Hello, world! 
</Button> 

风格只针对按钮,所以它只能应用于按钮。 (这不会是你的评论的外观问题。)

0

你需要一些强大的黑魔法才能使它为你的usercontrol自动创建一个功能正常的新样式,每种类型的内置控件都有内置样式,你可以添加到工具栏中(注意ToolBar.ButtonStyleKey不是单独的)。你需要制作和运用你自己的风格,自己相匹配的标准工具栏元素。

+0

我不想自动创建一个,我只想将现有的按钮样式应用到我的UserControl中的按钮。 – Ray 2009-06-03 23:00:34

4

我找到了一种方法,似乎工作,但我感兴趣的是解决这个的其他方式。

我添加了一个加载的事件处理程序到我的UserControl并把它放在里面。

if (button.Style == null && this.Parent is ToolBar) 
{ 
    button.Style = (Style)FindResource(ToolBar.ButtonStyleKey); 
} 

其中button是我的UserControl中按钮的名称。