问题描述
我想使用 WPF ToggleButton
来展开和折叠我的应用程序中的一些控件.如何使用 XAML 来完成此操作?
I would like to use a WPF ToggleButton
to expand and collapse some controls in my application. How can I use XAML to accomplish this?
我想我可以以某种方式将某些控件的 Visibility
属性绑定到 ToggleButton
的 IsChecked
状态,但我确实这样做了不知道该怎么做.
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.
也许我需要给我的 ToggleButton
一个 Name
,然后使用 ElementName
绑定?然后我需要一个 ValueConverter
来在布尔值和可见性之间进行转换,对吗?我怎样才能为此目的制作一个通用的 ValueConverter
?
Maybe I need to give my ToggleButton
a Name
, then bind using ElementName
? Then I would need a ValueConverter
for converting between a boolean value and a Visibility, correct? How could I make a generic ValueConverter
for this purpose?
推荐答案
需要通过转换器绑定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>
Silverlight 中没有 BooleanToVisibilityConverter
,但使用一些附加功能可以轻松编写自己的:
In Silverlight there is no BooleanToVisibilityConverter
but it is easy to write your own with some added features:
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; }
}
}
现在您可以指定一个将 true
映射到 Collapsed
并将 false
映射到 Visible
的转换器:
Now you can specify a converter that maps true
to Collapsed
and false
to Visible
:
<BooleanToVisibilityConverter
x:Key="InverseBooleanToVisibilityConverter" InvertVisibility="True"/>
这篇关于绑定到 WPF ToggleButton 的 IsChecked 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!