Alex Rivera | Logout

Binding visibility of a control to 'Count' of an IEnumerable

Asked 2011-09-27T00:19:34.270
17

I have a list of objects contained in an IEnumerable<>. I would like to set the visibility of a control based on the count of this list. I have tried:

 Visibility="{Binding MyList.Count>0?Collapsed:Visible, Mode=OneWay}"

But this doesn't work. I tried binding MyList.Count to the text in a text block to ensure that the count value was correct, and it is. It just doesn't seem to set the visibility correctly.

Edit
Report

1 Answer

44

You cannot use logical or code-expressions in bindings (it expects a PropertyPath). Either use a converter or triggers, which is what i would do:

<YourControl.Style>                     
    <Style TargetType="YourControl">
        <Setter Property="Visibility" Value="Collapsed" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding MyList.Count}" Value="0">
                <Setter Property="Visibility" Value="Visible" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</YourControl.Style>

(You can of course refactor the style into a resource if you wish.)

answered 2011-09-27T00:47:58.630

Your Answer