通过DataTemplate分隔

我有一个带有
ItemsSource
ToolBar
,我在运行时使用
DataTemplateSelector
来确定
DataTemplate
(即
Button
/
ToggleButton
)。 我想加一个
Separator
DataTemplate
,我该怎么做?     
已邀请:
ToolBar是一个ItemsControl,因此它希望用“容器”“包装”Items / ItemsSource中定义的项目。容器是可用于显示项目的UIElement。例如,在ListBox的情况下,容器是ListBoxItem。如果一个项目属于正确的类型,那么它也可以是它自己的容器。 此设置允许您将字符串列表传递给ListBox,并使其显示属性和支持选择,键盘导航,样式等。 在ToolBar的情况下,它确实期望它的项目已经是一个容器(即UIElement)。如果该项不是UIElement,那么它将使用ContentPresenter将其包装起来。 现在,容器使用DataTemplateSelecter来确定如何显示它的项目。但是您需要将项目设置为Button,ToggleButton,Separator等。您建议您应该在容器显示的DataTemplate中添加容器。 还有Styles的问题,可以通过这个简单的例子看到:
<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,就像使用按钮一样。     

要回复问题请先登录注册