根据所选的单选按钮显示控件

时间:2009-06-25 16:01:49

标签: .net wpf vb.net radio-button

我有一组三个单选按钮。根据选择的单选按钮,我想删除三个控件之一 - 文本框,下拉列表或按钮。如何根据所选单选按钮的结果显示控件?

2 个答案:

答案 0 :(得分:16)

您可以使用BooleanToVisibilityConverter将控件的可见性绑定到RadioButton的IsChecked属性:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <BooleanToVisibilityConverter x:Key="convVisibility"/>
  </Page.Resources>
  <Grid>
    <StackPanel Orientation="Vertical">
      <RadioButton Name="radioButton1" GroupName="group1">Control1</RadioButton>
      <RadioButton Name="radioButton2" GroupName="group1">Control2</RadioButton>
      <RadioButton Name="radioButton3" GroupName="group1">Control3</RadioButton>
      <Grid>
        <Button Visibility="{Binding IsChecked, ElementName=radioButton1, Converter={StaticResource convVisibility}}">1. Button</Button>
        <TextBlock Visibility="{Binding IsChecked, ElementName=radioButton2, Converter={StaticResource convVisibility}}">2. TextBlock</TextBlock>
        <TextBox Visibility="{Binding IsChecked, ElementName=radioButton3, Converter={StaticResource convVisibility}}">3. TextBox</TextBox>
      </Grid>
    </StackPanel>
  </Grid>
</Page>

编辑:

  

这些解决方案效果很好,实施起来很简单。无论如何我可以阻止控件隐藏在设计模式中吗?

我不了解其他设计师(例如Blend),但在Visual Studio设计器中,控件永远不会被隐藏......

无论如何,你可以实现自己的转换器,它总是在设计模式下返回Visible。由于某些不明原因,BooleanToVisibilityConverter类是密封的,因此您无法继承它。如果您不想重写转换逻辑,可以将转换委托给BooleanToVisibilityConverter:

public class MyBooleanToVisibilityConverter : IValueConverter
{
    private BooleanToVisibilityConverter _converter = new BooleanToVisibilityConverter();
    private DependencyObject _dummy = new DependencyObject();

    private bool DesignMode
    {
        get
        {
            return DesignerProperties.GetIsInDesignMode(_dummy);
        }
    }

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (DesignMode)
            return Visibility.Visible;
        else
            return _converter.Convert(value, targetType, parameter, culture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return _converter.ConvertBack(value, targetType, parameter, culture);
    }

    #endregion
}

答案 1 :(得分:1)

为了在设计时保持组件的可见性,您可以在复选框中添加FallbackValue true

<RadioButton x:Name="cbxEmail" Content="Email Details" IsEnabled="{Binding IsEmail, FallbackValue=true}" IsChecked="{Binding IsEmail, Mode=OneWay, FallbackValue=true}"
                                Grid.Column="2"/>