2

I have a DataGrid which bound a List<T>, this is the structure:

<DataGrid x:Name="myDataGrid"
          ItemSource="{Binding myList}" />

I want enable a button only if there is items myDataGrid, actually I'm able to enable the button only if the user have selected an item in this way:

<Button>
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="IsEnabled" Value="True" />
            <Setter Property="Opacity" Value="1" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=SelectedItem, ElementName=myDataGrid}" Value="{x:Null}">       
                     <Setter Property="IsEnabled" Value="False" />
                    <Setter Property="Opacity" Value=".5" />
                </DataTrigger>
            </Style.Triggers>
       </Style>
   </Button.Style>
</Button>

how can I do that?

Gahoooole
  • 21
  • 1

3 Answers3

2

You could make the collection you're binding an observablecollection. Then use a datatrigger which checks count on that.

<Button Content="SomeButton">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="IsEnabled" Value="True" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding myObservableCollection.Count}" Value="0">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
Andy
  • 11,864
  • 2
  • 17
  • 20
0

Give me a name to the button:

<Button x:Name="myBTN"> ...

Make a method that do the check and enable or disable the button:

void CheckList()
{
    if(list.Count == 0)
    {
        myBTN.IsEnabled = false;
    }
    else
        myBTN.IsEnabled = true;
}

And now everytime you call myList.add() or myList.remove(), call the CheckList() method.

Or check this: How to handle add to list event? Make a new class inheriting from List, and add an event handler to Add and Remove.

M.Boukhlouf
  • 303
  • 2
  • 10
0

DataGrid has boolean HasItems property. Bind IsEnabled directly.

<Setter Property="Opacity" Value="1" /> repeats the default and can be omitted.

And finally since button IsEnabled was set via Binding, a Trigger can be used instead of DataTrigger:

<Button IsEnabled="{Binding Path=HasItems, ElementName=myDataGrid}">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <Trigger property="IsEnabled" Value="False">
                    <Setter Property="Opacity" Value=".5" />
                </Trigger>
            </Style.Triggers>
       </Style>
   </Button.Style>
</Button>
ASh
  • 34,632
  • 9
  • 60
  • 82