[英]WPF - Bind UserControl visibility to a property
I have a ListView bound to ObservableCollection.我有一个绑定到 ObservableCollection 的 ListView。 Data are loaded from the internet and then added to collection.
数据从 Internet 加载,然后添加到集合中。 The download takes few seconds and I want to indicate user that the data is loading.
下载需要几秒钟,我想告诉用户数据正在加载。
I created an UserControl that indicates activity.我创建了一个指示活动的 UserControl。 I placed it inside of ControlTemplate.
我把它放在 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.我想将
ActivityIndicatorControl
可见性绑定到一个属性,假设bool IsLoading
并将其设置为 Visible/Collapsed 相应。
Thanks!谢谢!
I would recommend using a IValueConverter
to accept your boolean, and return a member of Visibility enumeration.我建议使用
IValueConverter
来接受您的布尔值,并返回 Visibility 枚举的成员。
Here is a good example of one: http://jeffhandley.com/archive/2008/10/27/binding-converters---visibilityconverter.aspx这是一个很好的例子: http : //jeffhandley.com/archive/2008/10/27/binding-converters---visibilityconverter.aspx
The XAML would look like this: XAML 看起来像这样:
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>
.NET 3 has a built in BooleanToVisibilityConverter . .NET 3 有一个内置的BooleanToVisibilityConverter 。
(Note: May not be available on all platforms, ex: mobile) (注意:可能并非在所有平台上都可用,例如:移动)
First add it to your Resources首先将其添加到您的资源中
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="bool2vis"></BooleanToVisibilityConverter>
</UserControl.Resources>
Then use it on an element然后在元素上使用它
<Label Visibility="{Binding IsSomeProperty, Converter={StaticResource bool2vis}}" />
How do I invert BooleanToVisibilityConverter? 如何反转 BooleanToVisibilityConverter?
If you want to invert the converter (ex: hide the element when your property is true), this answer has a custom implementation of IValueConverter
that supports that via XAML如果你想反转转换器(例如:当你的属性为真时隐藏元素),这个答案有一个
IValueConverter
的自定义实现,它通过 XAML 支持它
<Application.Resources>
<app:BooleanToVisibilityConverter
x:Key="BooleanToVisibilityConverter"
True="Collapsed"
False="Visible" />
</Application.Resources>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.