WPF列表框为空的数据模板

我想知道人们如何处理没有项目的ListBox控件? 例如,我想绑定一个search结果列表,但如果没有find结果,我想显示“找不到结果”。

我目前解决这个问题的方法是,如果结果集计数= 0,则隐藏列表框,并显示带有“未find结果”消息的标签。 理想情况下,我想像ASP .NET datagrid EmptyTemplate解决scheme。

干杯

我已经取得了一些成功的代码:

<Style TargetType="ListBox" x:Key="ListStyle" BasedOn="{StaticResource {x:Type ListBox}}"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Items.Count}" Value="0" > <Setter Property="Template"> <Setter.Value> <ControlTemplate> <TextBlock>No items to display</TextBlock> </ControlTemplate> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> 

基于@Matt Hamilton公认的答案,作为参考,我创build了一个不需要绑定的变体,因为它使用ListBoxHasItems属性来触发空模板:

 <ListBox.Style> <Style x:Key="EmptyListStyle" TargetType="ListBox" BasedOn="{StaticResource {x:Type ListBox}}"> <Style.Triggers> <!-- Use ListBox.HasItems instead of Binding --> <Trigger Property="HasItems" Value="False"> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <TextBlock>No items to display</TextBlock> </ControlTemplate> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> </ListBox.Style> 

这允许全局使用样式,而不必知道列表绑定到的属性名称。 绑定到XAML中定义的CollectionViewSource时,我发现它很有用。

我不知道这种方法的任何缺点,如果你应该find任何意见,欢迎评论。