绑定到一个WPF切换按钮的状态器isChecked

绑定到一个WPF切换按钮的状态器isChecked

本文介绍了绑定到一个WPF切换按钮的状态器isChecked的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:44