Michael A
Michael A

Reputation: 9900

How to show a button when item is selected in WPF datagrid?

I have a WPF datagrid that has two associated buttons for editing and deleting data. Ideally, I'd like to disable or make these buttons invisible when an item is not selected in the grid. How do I approach this?

If it matters my datagrid XAML is:

<DataGrid AutoGenerateColumns="True" Margin="10,174,12,35" Name="dataGridArchiveQueue" Visibility="Visible" AlternatingRowBackground="#01000000" BorderBrush="#FF688CAF" 
                              HorizontalGridLinesBrush="#37000000" VerticalGridLinesBrush="#37000000" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" 
                              SelectedItem="{Binding SelectedItemArchiveGrid}" Grid.ColumnSpan="2">
                              <DataGrid.Resources>
                        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                                                         Color="LightBlue" />
                        </DataGrid.Resources>

                    </DataGrid>

Upvotes: 3

Views: 4079

Answers (2)

pchajer
pchajer

Reputation: 1584

You can use DataTrigger on button to handle the disable/visible of buttons OR you can write the logic on CanExecuteChange event of command which gets binded to button

Data Trigger

        <Button.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{SelectedItemArchiveGrid}" Value="{x:Null}">
                        <Setter Property="IsEnabled"Value="False"></Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>

Command

> public RelayCommand<object> DeletCommand { get; set; }
> 
> DeletCommand = new RelayCommand<object>(OnDelete, OnDeletCanExecute);
> 
> private void OnDelete(object obj) { }
> 
> private bool OnDeletCanExecute(object obj)  {
     return SelectedItemArchiveGrid != null;  }

XAML

<Button Content="Delete" Command="{Delete Command}"/>

Upvotes: 2

Related Questions