使用WPF ListBox中的DataTrigger基于Count

时间:2016-08-18 11:55:06

标签: wpf xaml listbox datatemplate datatrigger

我有一个ListBoxItemTemplate我有一个TextBlock和一个删除Button

我的要求:如果ObservableCollection<string> Person只有一条记录,那么我需要隐藏删除Button。如果有多个记录,那么我需要为所有项目显示删除Button

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>

请帮助我如何根据我的要求设置DataTrigger

1 个答案:

答案 0 :(得分:0)

DataTrigger可以采用Button的样式:

<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>