【问题标题】:Tabitem template get displayindex?Tabitem模板获取displayindex?
【发布时间】:2015-04-20 01:29:42
【问题描述】:

我想为我的 tabitems 创建一个具有以下属性的样式: - 第一个 tabitem 将在左角设置一个角半径 - 最后一个 tabitem 会在右上角设置一个圆角半径

预期结果:

问题 1: 所以我需要能够获取模板中当前 tabitem 的索引(以及 tabcontrol 中 tabitem 的数量。

我希望能够以一种风格做到这一点。我目前正在使用 3 种样式(一种用于第一种,一种用于最后一种,另一种用于其他),但在我的应用程序中,我经常需要隐藏一两个 tabitems,所以我需要检查是否必须设置一个新的代码中的样式并不是真正有用的。

问题2:我想改变当前选中的tabitem之前所有tabitem的样式。

这可能只使用一种样式吗?

谢谢

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    3 种样式部分没问题,您缺少的是 StyleSelector,它将根据 ItemIndex 选择样式

    public class TabItemStyleSelector : StyleSelector
        {
            public override Style SelectStyle(object item, DependencyObject container)
            {
                var itemsControl = ItemsControl.ItemsControlFromItemContainer(container);
                var itemIndex = itemsControl.ItemContainerGenerator.IndexFromContainer(container);
    
                //first index
                if(itemIndex == 0)
                {
                    return (Style)itemsControl.FindResource("FirstTabItemItemStyle");
                }
                //last index
                if (itemIndex == itemsControl.Items.Count - 1)
                {
                    return (Style)itemsControl.FindResource("LastTabItemItemStyle");
                }
    
                //other indecies
                return (Style)itemsControl.FindResource("OtherTabItemItemStyle");
    
                //return base.SelectStyle(item, container); return this if OtherTabItemItemStyle does not exist
            }
        }
    

    将其添加到您的资源中

    <Window.Resources>
            <local:TabItemStyleSelector x:Key="TabItemStyleSelector" />
     </Window.Resources>
    

    并在您的TabControl 中使用它作为:

     <TabControl ItemsSource="{Binding Items}" ItemContainerStyleSelector="{StaticResource TabItemStyleSelector}">
    </TabControl>
    

    请注意,上述选择器适用于任何ItemsControl,而不仅仅是TabControl

    【讨论】:

      猜你喜欢
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2017-11-09
      • 2011-02-10
      • 2012-02-18
      相关资源
      最近更新 更多