开发者

How do I insert ToolBar separators when binding ItemSource

I am binding a ToolBar to a collection of command view model objects. The objects in the collection have a property IsSeparator that when true I would like represented with a <Separator/> in the ToolBar.

My basic markup looks like this:

<ToolBar Grid.Row="1" ItemsSource="{Binding Path=ToolBarCommands}">
    <ToolBar.ItemTemplate>
        <DataTemplate>
            <Button ToolTip="{Binding Path=ToolTip}" Command="{Binding Path=Command}">
                <Button.Content>
                    <Image Width="16" Height="16"  Source="{Binding Path=IconStream}"/>
                </Button.Content>
            </Button>                    
        </DataTemplate>
    </ToolBar.ItemTemplate>
</ToolBar>

I've played around with ItemContainerStyle much like this example for MenuItems but t开发者_运维知识库o no avail.

Any help is appreciated.


I followed Josh's suggestion about using a DataTemplateSelector and I'm just going to post code to help others.

public class ToolBarItemTemplateSelector : DataTemplateSelector
{
    public DataTemplate ButtonTemplate { get; set; }
    public DataTemplate SeparatorTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        var toolBarItem = (ToolBarItemViewModel) item;
        Debug.Assert(toolBarItem != null);
        if (!toolBarItem.IsSeparator)
        {
            return ButtonTemplate;
        }
        return SeparatorTemplate;
    }
}

    <DataTemplate x:Key="buttonTemplate" DataType="{x:Type infrastructure:ToolBarItemViewModel}">
        <Button Command="{Binding Command}" ToolTip="{Binding ToolTip}" Style="{DynamicResource ResourceKey={x:Static ToolBar.ButtonStyleKey}}">
            <Image Source="{Binding ImageSource}" Width="16" Height="16" />
        </Button>
    </DataTemplate>

    <DataTemplate x:Key="separatorTemplate">
        <Separator Style="{StaticResource {x:Static ToolBar.SeparatorStyleKey}}" />
    </DataTemplate>

    <local:ToolBarItemTemplateSelector ButtonTemplate="{StaticResource buttonTemplate}" SeparatorTemplate="{StaticResource separatorTemplate}" x:Key="toolBarItemTemplateSelector" />


<ToolBar AutomationProperties.AutomationId="toolBar" ItemsSource="{Binding ToolBarItems}" x:Name="toolBar" Band="1" BandIndex="1" ItemTemplateSelector="{StaticResource toolBarItemTemplateSelector}"/>


Rather than inserting Separator objects, you could just grab Separator's ControlTemplate (in Blend, right click a separator -> Edit Template -> Edit a Copy) and incorporate it directly into your button template. You can use a DataTrigger to control its visibility, perhaps binding to a "BeginGroup" property on your object.

If you want to have a dedicated Separator object in your collection you could use a DataTemplateSelector.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜