我有ToolBar
的绑定ItemsSource
,我使用DataTemplateSelector
在运行时确定DataTemplate
(即Button
/ {{1} })。
我想添加ToggleButton
Separator
,我该怎么做?
答案 0 :(得分:3)
ToolBar是一个ItemsControl,因此它希望用“容器”“包装”Items / ItemsSource中定义的项目。容器是可用于显示项目的UIElement。例如,在ListBox的情况下,容器是ListBoxItem。如果一个项目属于正确的类型,那么它也可以是它自己的容器。
此设置允许您将字符串列表传递给ListBox,并使其显示属性和支持选择,键盘导航,样式等。
在ToolBar的情况下,它确实期望它的项目已经是一个容器(即UIElement)。如果该项目不是UIElement,那么它将使用ContentPresenter包装它。
现在,容器使用DataTemplateSelecter来确定如何显示它的项目。但是您需要将项目设置为Button,ToggleButton,Separator等。您建议您应该在容器显示的DataTemplate中添加容器。
还有样式问题,可以通过这个简单的例子看出:
<Window x:Class="TestWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib" Title="Main"
Height="500" Width="500">
<DockPanel LastChildFill="False">
<ToolBar DockPanel.Dock="Top">
<ToolBar.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}" />
</DataTemplate>
</ToolBar.ItemTemplate>
<system:String>Test1</system:String>
<system:String>Test2</system:String>
</ToolBar>
<ToolBar DockPanel.Dock="Top">
<Button>Test1</Button>
<Button>Test2</Button>
</ToolBar>
</DockPanel>
</Window>
顶部工具栏中的按钮将呈现相同的外观,就好像它们不在工具栏中一样。底部工具栏中的按钮将显示“工具栏”外观。分隔符也是如此。
您可以像这样手动应用伴奏:
<Window x:Class="TestWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib" Title="Main"
Height="500" Width="500">
<DockPanel LastChildFill="False">
<ToolBar DockPanel.Dock="Top">
<ToolBar.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}"
Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" /> <!-- Add the Style attribute -->
</DataTemplate>
</ToolBar.ItemTemplate>
<system:String>Test1</system:String>
<system:String>Test2</system:String>
</ToolBar>
<ToolBar DockPanel.Dock="Top">
<Button>Test1</Button>
<Button>Test2</Button>
</ToolBar>
</DockPanel>
</Window>
分隔符会遇到同样的问题。所以你需要像这样手动应用Style:
<DataTemplate x:Key="MySeparatorTemplate">
<Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
</DataTemplate>
您应该可以在DataTemplateSelector中使用上面的DataTemplate,就像使用按钮一样。