将矩形控件的可见性绑定到按钮的 isEnabled 属性

Binding visibility of rectangle control to button's isEnabled property

我在屏幕上有几个按钮,每个按钮都实现为 UserControl,并且一次只能启用 1 个。现在 UserControl 中的所有按钮旁边都有一个侧边栏类型 Rectangle,它应该只对 1 个按钮可见,以启用的为准。尝试了几个绑定来控制 IsEnabled 矩形的可见性,但失败了。还准备好可见性转换器。这是我的代码:

<Grid>
   <Button Style="{StaticResource MenuButtonStyle}" x:Name="BtnUC">
       <Button.Content>
           <Grid>
               <Grid.ColumnDefinitions>
                   <ColumnDefinition Width="1"/>
                   <ColumnDefinition/>
               </Grid.ColumnDefinitions>

               <Rectangle Grid.Column="0" Fill="LightGray" Margin="-4,0,0,0">
                   
               </Rectangle>
               <Viewbox ....
               </Viewbox>
           </Grid>

       </Button.Content>
   </Button>
</Grid>

在范围内的任何资源中创建 BooleanToVisibilityConverter 转换器的实例。

<Window.Resources>
   <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>

然后将Visibility of the rectangle to the IsEnabled property of your button by referring to it using the element name BtnUC. By specifying the converter, true will be converted to Visiblefalse绑定到Collapsed

<Rectangle Grid.Column="0" Fill="LightGray" Margin="-4,0,0,0"
           Visibility="{Binding IsEnabled, ElementName=BtnUC, Converter={StaticResource BooleanToVisibilityConverter}}"/>

或者,如果没有按钮名称,通过 RelativeSource 引用父 Button

<Rectangle Grid.Column="0" Fill="LightGray" Margin="-4,0,0,0"
           Visibility="{Binding IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type Button}}, Converter={StaticResource BooleanToVisibilityConverter}}"/>

您可以将 StyleDataTrigger 结合使用,根据 [=15] 的值设置 RectangleVisibility 属性 =] 属性 的 Button:

<Rectangle Grid.Column="0" Fill="LightGray" Margin="-4,0,0,0">
    <Rectangle.Style>
        <Style TargetType="Rectangle">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsEnabled,RelativeSource={RelativeSource AncestorType=Button}}" Value="False">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Rectangle.Style>
</Rectangle>