[英]Binding to a WPF ToggleButton's IsChecked state
I would like to use a WPF ToggleButton
to expand and collapse some controls in my application. 我想使用WPF ToggleButton
来扩展和折叠我的应用程序中的一些控件。 How can I use XAML to accomplish this? 我如何使用XAML来实现这一目标?
I'm thinking that I could somehow bind the Visibility
attribute of some controls to the ToggleButton
's IsChecked
state, but I do not know how to do this. 我想我可以某种方式将某些控件的Visibility
属性绑定到ToggleButton
的IsChecked
状态,但我不知道该怎么做。
Maybe I need to give my ToggleButton
a Name
, then bind using ElementName
? 也许我需要给我的ToggleButton
一个Name
,然后使用ElementName
绑定? Then I would need a ValueConverter
for converting between a boolean value and a Visibility, correct? 那么我需要一个ValueConverter
来在布尔值和可见性之间进行转换,对吗? How could I make a generic ValueConverter
for this purpose? 我怎样才能为此目的制作通用的ValueConverter
?
You need to bind the Visibility
through a converter: 您需要通过转换器绑定Visibility
:
<Window
x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<StackPanel>
<ToggleButton x:Name="toggleButton" Content="Toggle"/>
<TextBlock
Text="Some text"
Visibility="{Binding IsChecked, ElementName=toggleButton, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</Window>
In Silverlight there is no BooleanToVisibilityConverter
but it is easy to write your own with some added features: 在Silverlight中没有BooleanToVisibilityConverter
但很容易编写自己的一些附加功能:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication1 {
public class BooleanToVisibilityConverter : IValueConverter {
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
if (targetType == typeof(Visibility)) {
var visible = System.Convert.ToBoolean(value, culture);
if (InvertVisibility)
visible = !visible;
return visible ? Visibility.Visible : Visibility.Collapsed;
}
throw new InvalidOperationException("Converter can only convert to value of type Visibility.");
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
throw new InvalidOperationException("Converter cannot convert back.");
}
public Boolean InvertVisibility { get; set; }
}
}
Now you can specify a converter that maps true
to Collapsed
and false
to Visible
: 现在,您可以指定将true
映射到Collapsed
并将false
映射到Visible
的转换器:
<BooleanToVisibilityConverter
x:Key="InverseBooleanToVisibilityConverter" InvertVisibility="True"/>
Use the BooleanToVisibilityConverter: 使用BooleanToVisibilityConverter:
<BooleanToVisibilityConverter x:Key="bvc" />
<TextBlock Visibility="{Binding IsChecked, ElementName=toggle, Converter={StaticResource bvc}}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.