Button display on selected datagridrow

I have a datagrid with multiple rows. Each row has a DeleteRow button. Only the selected row should have this button. As I see it, there can be at least two solutions:

a) binding the Button Visibility property to the IsSelected property for the containing DatGridRow

or

b) using a trigger in a button only for display when the selected row is selected.

This is the code that I have for option b that does not work:

<DataGridTemplateColumn Width="50"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Content="X" Tag="{Binding}" Click="DeletRow_Click" Visibility="Hidden"> <Button.Style> <Style x:Name="ButtonVisibility"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}},Path=IsSelected}" Value="True"> <Setter Property= "Button.Visibility" Value="Visible"/> </DataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> </DataTemplate> </DataGridTemplateColumn.CellTemplate> 

This is probably very easy, but I look so closely that I am now blinding: S

Thanks

+6
source share
2 answers

This does not work due to the priority value of the dependency property . You cannot change the local value within Style . Move Visibility.Hidden to Style and it will work.

 <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Content="X" Tag="{Binding}" Click="DeletRow_Click"> <Button.Style> <Style x:Name="ButtonVisibility"> <Setter Property="Button.Visibility" Value="Hidden"/> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="True"> <Setter Property="Button.Visibility" Value="Visible"/> </DataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> </DataTemplate> </DataGridTemplateColumn.CellTemplate> 
+11
source

You can use the BooleanToVisibiltyConverter converter provided by WPF to switch the visibility of your button -

 <DataGrid> <DataGrid.Resources> <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> </DataGrid.Resources> <DataGrid.Columns> <DataGridTemplateColumn Width="50"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Content="X" Tag="{Binding}" Visibility="{Binding IsSelected, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGridRow}}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> 
+2
source

Source: https://habr.com/ru/post/924742/


All Articles