简体   繁体   中英

CheckBox Show/Hide TextBox WPF

As the title says, Iam trying to show\/hide a TextBox in WPF without writing code in MainWindow.xaml.cs file.

public class Person
{
    public string Comment { get; set; }
}

You can bind TextBox.Visiblity to CheckBox.IsChecked . If you want to toggle between Hidden and Visible then you need to either write custom IValueConverter or create simple Style.Trigger

<StackPanel>
    <CheckBox Content="Show comment" Name="CommentCheckBox"/>
    <TextBox Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" Name="CommentTextBox">
        <TextBox.Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Visibility" Value="Hidden"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=CommentCheckBox, Path=IsChecked}" Value="True">
                        <Setter Property="Visibility" Value="Visible"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
</StackPanel>

if you want to toggle between Collapsed and Visible there is an easier way and you can use build in BooleanToVisibilityConverter

<StackPanel>
    <StackPanel.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </StackPanel.Resources>
    <CheckBox Content="Show comment" Name="CommentCheckBox"/>
    <TextBox 
        Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" 
        Visibility="{Binding ElementName=CommentCheckBox, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}" 
        Name="CommentTextBox"/>
</StackPanel>

The simplest way is to write a custom "BooleanToHiddenVisibilityConverter" and use it (like dkozl said). It's a really simple converter and it comes in handy in many situations. I think that every descent WPF application should have one.

public sealed class BooleanToHiddenVisibilityConverter : IValueConverter
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        bool bValue = false;
        if (value is bool) 
        {
            bValue = (bool)value;
        }
        return (bValue) ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is Visibility) 
        {
            return (Visibility)value == Visibility.Visible; 
        }
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM