使工具栏按钮样式应用于工具栏中的用户控件

8
我该如何强制WPF中位于工具栏内的UserControl使用工具栏默认按钮样式?
我有一个简单的名为ImageButton的用户控件,其XAML大致如下:
<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.ButtonStyleKey)。但是,我如何将已定义的样式应用于我的用户控件的Button Style依赖属性?
3个回答

22

哦,我道歉!我误解了你的问题。试一下这个:

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

这个样式只针对按钮,因此它只能应用于按钮。(根据您的评论看起来这不是问题。)


4

我找到了一种方法,似乎可以解决问题,但我也对其他解决方法感兴趣。

我在我的UserControl中添加了一个loaded事件处理程序,并将其放置在其中。

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

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


0
你需要一些强大的黑魔法才能让它自动创建一个功能正常的用户控件新样式。每种内置控件都有内置样式,可以添加到工具栏中。(注意ToolBar.ButtonStyleKey并不是唯一的。)你需要自己制作和应用与标准工具栏元素相匹配的样式。

我不想自动创建一个,我只想将现有的按钮样式应用于我的UserControl内部的按钮。 - Ray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接