1

我有以下样式,Tabitem其中包含一个关闭按钮。

<Style x:Key="StudioTabItem" TargetType="{x:Type TabItem}">
    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TabItem}">
                ...
                <Button Grid.Column="2" 
                        Width="15" 
                        Height="15" 
                        HorizontalAlignment="Center" 
                        VerticalAlignment="Center" 
                        Visibility={Binding}> 
                ...

StudioTabItem当我使用实际控件时,我想使 s 按钮的可见性成为可选的。所以像

<TabControl x:Name="tabControl" 
            Style="{StaticResource StudioTabControl}"
            ItemsSource="{Binding Workspaces}" 
            SelectedIndex="{Binding SelectedIndex}"
            TabStripPlacement="Top" >
        <TabControl.ItemContainerStyle>
            <Style TargetType="TabItem" 
                   BasedOn="{StaticResource StudioTabItem}"
                   IsCloseButtonVisible="False"> <-- How to do this?

IsCloseButtonVisible上面最后一行的。我知道这很可能涉及DependencyProperties。这可能吗?我怎样才能做到这一点?

谢谢你的时间。

4

1 回答 1

1

这可以通过创建Attached Property下面的类似内容并在样式设置器中设置其属性来实现

    public static class TabItemBehaviour
    {
        public static readonly DependencyProperty IsCloseButtonVisibleProperty =
            DependencyProperty.RegisterAttached("IsCloseButtonVisible", typeof(bool), typeof(TabItemBehaviour), new UIPropertyMetadata(true, IsButtonVisiblePropertyChanged));

        public static bool GetIsCloseButtonVisible(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsCloseButtonVisibleProperty);
        }

        public static void SetIsCloseButtonVisible(DependencyObject obj, bool value)
        {
            obj.SetValue(IsCloseButtonVisibleProperty, value);
        }

        public static void IsButtonVisiblePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            TabItem item = o as TabItem;
            if (item != null)
            {
               Button closeButton = item.Template.FindName("CloseButton", item) as Button;
               if ((bool)e.NewValue == true)
               {
                   closeButton.Visibility = Visibility.Visible;
               }
               else
               {
                   closeButton.Visibility = Visibility.Collapsed;
               }
            }
        }
    }

然后TabItemstyle 只需设置属性:

<Style TargetType="TabItem" 
                   BasedOn="{StaticResource StudioTabItem}"
                   > 
<Setter Property="behaviours:TabItemBehaviour.IsCloseButtonVisible" Value="False"/>

此外,您还必须Button在您的ControlTemplate

于 2013-09-22T15:33:29.520 回答