WPF,TabItem图像

时间:2016-09-29 21:43:21

标签: c# wpf binding

有TabControl,它绑定到数组,需要添加到TabItem不同的图标/图像。 haml代码:

<Grid>
        <TabControl VirtualizingPanel.VirtualizationMode="Recycling" Style="{StaticResource TabControl}" 
         ItemsSource="{Binding Workspaces}" SelectedIndex="{Binding CurrentPage,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}">
        <TabControl.ItemContainerStyle>
            <Style BasedOn="{StaticResource TabItem}" TargetType="{x:Type TabItem}">
                <Setter Property="Header" Value="{Binding HeaderText}"/>
            </Style>
        </TabControl.ItemContainerStyle>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding Content}" />
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

1 个答案:

答案 0 :(得分:0)

您应该在TabControl中设置ItemTemplateSelector:

<TabControl VirtualizingPanel.VirtualizationMode="Recycling" Style="{StaticResource TabControl}" 
    ItemsSource="{Binding Workspaces}" SelectedIndex="{Binding CurrentPage,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
    ItemTemplateSelector="{StaticResource myItemDataTemplateSelector}" >

您的TemplateSelector应如下所示:

public class MyItemDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        FrameworkElement element = container as FrameworkElement;

        if (element != null && item != null && item is MyItem)
        {
            var myItem = item as MyItem;
            var window = Application.Current.MainWindow;

            switch (myItem.SpecialFeatures)
            {
                case SpecialFeatures.None:
                    return 
                        element.FindResource("Item_None_DataTemplate") 
                        as DataTemplate;
                case SpecialFeatures.Color:
                    return 
                        element.FindResource("Item_Color_DataTemplate") 
                        as DataTemplate;
            }
        }

        return null;
    }
}

参考:https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplateselector(v=vs.110).aspx