Search code examples
wpfxamllistboxdatatemplatedatatrigger

Hide Button in ListBox Item using DataTrigger in WPF ListBox Based on Count


I'm having a ListBox, in that ItemTemplate I'm having one TextBlock and one Delete Button.

My Requirement: If the ObservableCollection<string> Person has only one record, then I need to hide the Delete Button. If more than one record is there then I need to show Delete Button for all the Item.

XAML:

<ListBox ItemsSource="{Binding Person, UpdateSourceTrigger=PropertyChanged}" Background="Transparent"  Margin="0 10" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid HorizontalAlignment="Stretch">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <TextBox Grid.Row="0" Text="{Binding Contact, UpdateSourceTrigger=PropertyChanged}" />
                    <Button  Grid.Row="1" Content="X" Foreground="Red" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Style>
        <Style TargetType="{x:Type ListBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Items.Count, RelativeSource={RelativeSource Self}}"  Value="1">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>
</ListBox>

DataTrigger:

    <ListBox.Style>
        <Style TargetType="{x:Type ListBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Items.Count, RelativeSource={RelativeSource Self}}"  Value="1">
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>

Kindly assist me how to set DataTrigger for my requirement.


Solution

  • The DataTrigger could be in the Button's Style:

    <Button ...>
        <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Items.Count,
                                     RelativeSource={RelativeSource AncestorType=ListBox}}"
                                 Value="1">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>