Xamly determine if a ListBox.Items.Count > 0

2019-02-16 03:54发布

Is there a way in XAML to determine if the ListBox has data?

I wanna set its IsVisibile property to false if no data.

标签: wpf xaml listbox
4条回答
家丑人穷心不美
2楼-- · 2019-02-16 04:37

The ListBox contains a HasItems property you can bind to. So you can just do this:

<BooleanToVisibilityConverter x:Key="BooleanToVisibility" />
...
<ListBox 
    Visibility="{Binding HasItems, 
      RelativeSource={RelativeSource Self}, 
      Converter=BooleanToVisibility}" />

Or as a Trigger so you don't need the converter:

<ListBox>
  <ListBox.Style>
    <Style TargetType="{x:Type ListBox}">
      <Setter Property="Visibility" Value="Visible" />
      <Style.Triggers>
        <DataTrigger 
            Binding="{Binding HasItems, RelativeSource={RelativeSource Self}}"
            Value="False">
          <Setter Property="Visibility" Value="Hidden" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListBox.Style>
</ListBox>

I haven't tested the bindings so there might be some typos but you should get the idea.

查看更多
太酷不给撩
3楼-- · 2019-02-16 04:45

You can probably make this work using a ValueConverter and normal binding.

Set Visibility to be:

Visibility = "{Binding myListbox.Items.Count, Converter={StaticResource VisibilityConverter}}"

Then set up your converter to return Visibility.Collapsed etc based on the value of the count.

查看更多
混吃等死
4楼-- · 2019-02-16 04:47

Do it in a trigger and you won't need a ValueConverter:

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

So that shows the ListBox by default, but if Items.Count is ever 0, the ListBox is hidden.

查看更多
Bombasti
5楼-- · 2019-02-16 04:51
<ListBox.Style>
    <Style TargetType="ListBox">
        <Setter Property="Visibility" Value="Visible"/>
        <Style.Triggers>
            <Trigger Property="HasItems" Value="False">
                <Setter Property="Visibility" Value="Hidden"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.Style>
查看更多
登录 后发表回答