问题描述
我想用一个WPF 切换按钮
来展开和折叠在我的应用程序一些控制。如何使用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?
我在想,我可以以某种方式结合能见度
某些控件的属性添加到切换按钮
的器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.
也许我需要给我的切换按钮
A 名称
,然后绑定使用的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?
推荐答案
您需要将可见绑定
通过转换:
<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; }
}
}
现在,你可以指定地图真正
到折叠
和假到
可见
:
Now you can specify a converter that maps true
to Collapsed
and false
to Visible
:
<BooleanToVisibilityConverter
x:Key="InverseBooleanToVisibilityConverter" InvertVisibility="True"/>
这篇关于绑定到一个WPF切换按钮的状态器isChecked的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!