Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamly determine if a ListBox.Items.Count > 0

Tags:

wpf

xaml

listbox

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

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

like image 835
Shimmy Weitzhandler Avatar asked Sep 05 '09 22:09

Shimmy Weitzhandler


4 Answers

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.

like image 30
Matt Hamilton Avatar answered Oct 23 '22 18:10

Matt Hamilton


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.

like image 53
Bryan Anderson Avatar answered Oct 23 '22 18:10

Bryan Anderson


<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>
like image 33
Sathya Ram Avatar answered Oct 23 '22 18:10

Sathya Ram


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.

like image 41
Tristan Warner-Smith Avatar answered Oct 23 '22 18:10

Tristan Warner-Smith