Making the ToolBar Button Style apply to UserControls in the Toolbar

江枫思渺然 提交于 2019-12-22 05:39:26

问题


How do I force UserControls in WPF that are inside a ToolBar to use the ToolBar's default button style?

I have a simple user control called ImageButton which has XAML something like this:

<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>

I have some dependency properties in the code behind for those binding paths and everything works fine.

That is until I put it in a ToolBar. Normally when you put buttons in a ToolBar they are restyled by the ToolBar to look like toolbar buttons. I've found out how I can change this style (see ToolBar.ButtonStyleKey. But how can I apply the already defined style to my User Control's Button Style dependency property?


回答1:


Ooh, my apologies! I misinterpreted your question. Give this a shot:

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

The style only targets buttons, so it can only be applied to buttons. (Which won't be a problem by the look of your comment.)




回答2:


I found a way, that seems to work, although I'm interested in other ways of solving this.

I added a loaded event handler to my UserControl and put this inside it.

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

Where button is the name of the button inside my UserControl.




回答3:


You would require some powerful black magic in order to get it to create a functioning new style for your usercontrol automatically. There are built-in styles for each type of built-in control that you may add to the toolbar. (Notice that ToolBar.ButtonStyleKey is not alone.) You'll need to craft and apply your own style that matches the standard toolbar elements yourself.



来源:https://stackoverflow.com/questions/947293/making-the-toolbar-button-style-apply-to-usercontrols-in-the-toolbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!