I have several buttons, each implemented as a UserControl
, on a screen, and only 1 will be enabled at a time. Now there is a sidebar type Rectangle
next to all buttons in the UserControl
, which should only be visible for 1 button, whichever is enabled. Tried several bindings to control the visibility of the rectangle with IsEnabled
, but failed. Also have a visibility converter ready. Here's my code:
<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>
CodePudding user response:
You could use a Style
with a DataTrigger
that sets the Visibility
property of the Rectangle
based on the value of the IsEnabled
property of the 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>
CodePudding user response:
Create an instance of a BooleanToVisibilityConverter
converter in any resources in scope.
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>
Then bind the 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 Visible
and false
to Collapsed
.
<Rectangle Grid.Column="0" Fill="LightGray" Margin="-4,0,0,0"
Visibility="{Binding IsEnabled, ElementName=BtnUC, Converter={StaticResource BooleanToVisibilityConverter}}"/>
Alternatively, if there is no button name, refer to the parent Button
via RelativeSource
.
<Rectangle Grid.Column="0" Fill="LightGray" Margin="-4,0,0,0"
Visibility="{Binding IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type Button}}, Converter={StaticResource BooleanToVisibilityConverter}}"/>