WPF 工具栏 - 自定义样式
我想更改 wpf 工具栏的标准样式。我在控制资源中使用以下样式,效果很好:
<Style x:Key="{x:Type ToolBar}" TargetType="{x:Type ToolBar}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToolBar}">
<Border>
<DockPanel VerticalAlignment="Stretch" Height="38">
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
但是,如果我将项目添加到工具栏,这些项目不会显示:
<ToolBar x:Name="myToolbar">
<Label>test</Label>
</ToolBar>
我不想在模板中添加项目,而是在使用该项目的特定工具栏中添加项目模板。
谁能给我提示吗?
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>
<ControlTemplate 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您用自己的控件模板替换了工具栏的控件模板。但您尚未在该模板中指定应在何处显示项目。通常,您可以通过添加 ItemsPresenter 来完成此操作:
或者通过在模板内的面板上设置
IsItemsHost="True"
来实现:但是,如果您尝试替换工具栏的项目面板(如我的第二个示例),它不会工作,因为 ToolBar 期望 ToolBarPanel 是项目面板。
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:
Or by setting
IsItemsHost="True"
on a panel inside the template: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.
模板定义了控件的呈现方式,对于某些控件,所有内容都在模板内,而对于其他控件,控件希望在模板中找到它将操作的命名元素。如果查看 ToolBar 模板,您会发现工具栏期望在模板中找到名为 PART_ToolBarPanel 的元素和名为 PART_ToolBarOverflowPanel 的元素:
http://msdn.microsoft.com/en-us/library/aa970772.aspx
例如,它需要找到名为 PART_ToolBarPanel 的元素才能添加项目到工具栏。
如果您想向工具栏模板添加新元素,通常您会首先复制现有模板,然后开始添加/删除元素。
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.