绑定到WPF ToggleButton的IsChecked状态

时间:2009-10-07 21:10:37

标签: wpf xaml binding togglebutton

我想使用WPF ToggleButton来扩展和折叠我的应用程序中的一些控件。我如何使用XAML来实现这一目标?

我想我可以某种方式将某些控件的Visibility属性绑定到ToggleButton的{​​{1}}状态,但我不知道该怎么做。

也许我需要IsChecked ToggleButton,然后使用Name绑定?然后我需要一个ElementName来在布尔值和可见性之间进行转换,对吗?我怎样才能为此目的制作通用ValueConverter

3 个答案:

答案 0 :(得分:42)

您需要通过转换器绑定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但是使用一些附加功能编写自己的代码很容易:

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映射到Collapsedfalse映射到Visible的转换器:

<BooleanToVisibilityConverter
  x:Key="InverseBooleanToVisibilityConverter" InvertVisibility="True"/>

答案 1 :(得分:8)

使用BooleanToVisibilityConverter:

<BooleanToVisibilityConverter x:Key="bvc" />
<TextBlock Visibility="{Binding IsChecked, ElementName=toggle, Converter={StaticResource bvc}}" />

答案 2 :(得分:0)

您是否有理由不仅使用Expander?无论如何,它都基于ToggleButton。