Binding to a WPF ToggleButton's IsChecked state

情到浓时终转凉″ 提交于 2019-12-17 10:57:40

问题


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?

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.

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?


回答1:


You need to bind the Visibility through a converter:

<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:

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"/>



回答2:


Use the BooleanToVisibilityConverter:

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



回答3:


Is there a reason why you aren't just using the Expander? It's based on the ToggleButton anyway.



来源:https://stackoverflow.com/questions/1534208/binding-to-a-wpf-togglebuttons-ischecked-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!