控件模板中按钮的可选可见性

本文关键字:可见性 按钮 控件 | 更新日期: 2023-09-27 18:32:23

我有一个包含关闭按钮的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.这可能吗,我怎样才能做到这一点?

谢谢你的时间。

控件模板中按钮的可选可见性

这可以通过创建如下所示的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"/>

此外,您还必须在ControlTemplate中给Button起一个名称"关闭按钮"