malymato malymato - 2 months ago 20
C# Question

WPF - Bind UserControl visibility to a property

I have a ListView bound to ObservableCollection. Data are loaded from the internet and then added to collection. The download takes few seconds and I want to indicate user that the data is loading.

I created an UserControl that indicates activity. I placed it inside of ControlTemplate.

<ControlTemplate x:Key="ListViewControlTemplate1" TargetType="{x:Type ListView}">
<Grid>
<local:ActivityIndicatorControl
HorizontalAlignment="Center"
Height="Auto"
Margin="0"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>


I would like to bind Visibility of
ActivityIndicatorControl
to a property, let's say
bool IsLoading
and set it to Visible/Collapsed correspondingly.

Thanks!

Answer

I would recommend using a IValueConverter to accept your boolean, and return a member of Visibility enumeration.

Here is a good example of one: http://jeffhandley.com/archive/2008/10/27/binding-converters---visibilityconverter.aspx

The XAML would look like this:

First you define a resource for the converter (put this in a resource dictionary):

<local:BooleanToVisibilityConverter x:Key="myBoolToVisibilityConverter" />

And then change your template like this:

<ControlTemplate x:Key="ListViewControlTemplate1" TargetType="{x:Type ListView}">
    <Grid Visibility="{Binding IsLoading, Converter={StaticResource myBoolToVisibilityConverter}}>
        <local:ActivityIndicatorControl 
            HorizontalAlignment="Center" 
            Height="Auto" 
            Margin="0" 
            VerticalAlignment="Center"/>
    </Grid>
</ControlTemplate>
Comments