WPF Listbox - Empty List Display Message

非 Y 不嫁゛ 提交于 2019-12-12 09:31:49

问题


Can anyone suggest the best way to display a Textblock (with a text such as "List Empty") so that it's visibility is bound to the Items.Count.

I have tried the following code and can't get it to work, so think that I must be doing it wrong.

    <ListBox x:Name="lstItems" 
        ItemsSource="{Binding ListItems}">
    </ListBox>
    <TextBlock Margin="4" FontStyle="Italic" FontSize="12" Text="List is empty" Visibility="Collapsed">
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=lstItems, Path=Items.Count}" Value="0">
                        <Setter Property="Visibility" Value="Visible" />
                    </DataTrigger>  
                </Style.Triggers>
            </Style>                            
        </TextBlock.Style>
    </TextBlock>

回答1:


The problem in your code is that setting the value of Visibility in the text block itself has higher priority than setting it in the style. So, even when the trigger occurs, the setting inside the trigger has no effect. Change the XAML to:

  <TextBlock Margin="4" FontStyle="Italic" FontSize="12" Text="List is empty" >
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
           <Setter Property="Visibility" Value="Collapsed" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=lstItems, Path=Items.Count}" Value="0">
                    <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>  
            </Style.Triggers>
        </Style>                            
    </TextBlock.Style>
  </TextBlock>

Where the setting of Visibility is all in the style and it works (at least in my demo project).



来源:https://stackoverflow.com/questions/2446903/wpf-listbox-empty-list-display-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!