WPF - 将 UserControl 可见性绑定到属性 [英] WPF - Bind UserControl visibility to a property

查看:40
本文介绍了WPF - 将 UserControl 可见性绑定到属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到 ObservableCollection 的 ListView.数据从 Internet 加载,然后添加到集合中.下载需要几秒钟,我想指示用户数据正在加载.

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.

我创建了一个指示活动的用户控件.我把它放在 ControlTemplate 里面.

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>

我想将 ActivityIndi​​catorControl 的 Visibility 绑定到一个属性,比如说 bool IsLoading 并相应地将其设置为 Visible/Collapsed.

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

谢谢!

推荐答案

我建议使用 IValueConverter 接受您的布尔值,并返回可见性枚举的成员.

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

这是一个很好的例子:http://jeffhandley.com/archive/2008/10/27/binding-converters---visibilityconverter.aspx

XAML 看起来像这样:

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>

这篇关于WPF - 将 UserControl 可见性绑定到属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆