开发者

How do WPF toolbars change their buttons' styles?

开发者 https://www.devze.com 2023-03-04 21:56 出处:网络
In WPF, if you put a Button inside a ToolBar, the button automagically gets a different style: no border by default, different hover effects, etc. What mechanism does WPF use to accomplish that?

In WPF, if you put a Button inside a ToolBar, the button automagically gets a different style: no border by default, different hover effects, etc. What mechanism does WPF use to accomplish that?

I know how to restyle all the buttons in the program, by putting a Style TargetType="Button" into the Resources in App.xaml. I know how to restyle just the buttons in a single parent panel, by putting the same Style TargetType="Button" into the panel's Resources. But I don't know how to make it reusable, so that I can apply it to multiple different panels (but not the whole app) and have it restyle all the Buttons in those panels.

ToolBar has the magic to make an "apply to all my children"开发者_运维百科 style reusable. How does it do that?


It applies the style in a PrepareContainerForItemOverride, which looks like:

protected override void PrepareContainerForItemOverride(DependencyObject element, object item) {
    base.PrepareContainerForItemOverride(element, item);
    FrameworkElement element2 = element as FrameworkElement;
    if (element2 != null) {
        // ...
        ResourceKey name = null;
        if (type == typeof(Button)) {
            name = ButtonStyleKey;
        }
        else if (type == typeof(ToggleButton)) {
            name = ToggleButtonStyleKey;
        }
        else if (type == typeof(Separator)) {
            name = SeparatorStyleKey;
        }
        // ...
         element2.DefaultStyleKey = name;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号