ControlTemplate中Button的可选可见性

时间:2013-09-22 15:15:32

标签: c# wpf controls

我有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按钮的可见性可选。像

这样的东西
<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。这是可能的,我怎样才能做到这一点?

感谢您的时间。

1 个答案:

答案 0 :(得分: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;
               }
            }
        }
    }

然后TabItem样式设置属性:

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

此外,您必须在Button

中为ControlTemplate提供名称“CloseButton”