开发者

WPF Toolbar - Custom Style

开发者 https://www.devze.com 2023-02-07 21:54 出处:网络
I want to change the standard style of a wpf toolbar. I use the following Style in the Control Resources, which works fine:

I want to change the standard style of a wpf toolbar. I use the following Style in the Control Resources, which works fine:

<Style x:Key="{x:Type ToolBar}" TargetType="{x:Type ToolBar}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTempla开发者_开发知识库te TargetType="{x:Type ToolBar}">
                        <Border>
                            <DockPanel VerticalAlignment="Stretch" Height="38">
                            </DockPanel>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

However, if i add items to a toolbar, these items are not shown:

<ToolBar x:Name="myToolbar">
        <Label>test</Label>
    </ToolBar>

I do NOT want to add the items in the template, but in a specific toolbar which uses that template.

Can anyone give me a hint?


The problem is that you replaced the toolbar's control template with your own. But you haven't specified in that template where items should be shown. Typically you would do it either by adding an ItemsPresenter:

<ControlTemplate TargetType="{x:Type ToolBar}">
    <Border>
        <DockPanel VerticalAlignment="Stretch" Height="38">
            <ItemsPresenter/>
        </DockPanel>
    </Border>
</ControlTemplate>

Or by setting IsItemsHost="True" on a panel inside the template:

<ControlTemplate TargetType="{x:Type ToolBar}">
    <Border>
        <DockPanel IsItemsHost="True" VerticalAlignment="Stretch" Height="38">
        </DockPanel>
    </Border>
</ControlTemplate>

But, if you try to replace the items panel for the ToolBar (as in my second example), it will not work, because ToolBar expects the ToolBarPanel to be the items panel.


A template defines how a control is rendered, for some controls everything is within the template for others the control expects to find named elements within the template which it will manipulate. If you look at the ToolBar template you can see that the toolbar expects to find an element named PART_ToolBarPanel and an element named PART_ToolBarOverflowPanel within the template:

http://msdn.microsoft.com/en-us/library/aa970772.aspx

For example, it needs to locate the element named PART_ToolBarPanel in order to add the items to the toolbar.

If you want to add new elements to the toolbar template, typically you would start by copying the existing template, then start adding / removing element.

0

精彩评论

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

关注公众号