CheckBox显示/隐藏TextBox WPF

时间:2014-10-29 10:39:29

标签: c# .net wpf xaml mvvm

正如标题所说,Iam试图在WPF中显示/隐藏TextBox,而无需在MainWindow.xaml.cs文件中编写代码。

型号:

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

查看:

<Window x:Class="PiedPiper.View.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window"
    Title="WPF" Height="400" Width="400">

    <CheckBox Content="Show comment" Name="CommentCheckBox"/>
    <TextBox Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" Visibility="Hidden" Name="CommentTextBox"></TextBox>
</Grid>

视图模型:

    public class PersonViewModel : INotifyPropertyChanged
    {
    public PersonViewModel(Person person)
    {
        Comment = person.Comment;
    }

    private string _comment;
    public string Comment
    {
        get { return _comment; }
        set { _comment = value; OnPropertyChanged("Comment"); }
    }

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

因此TextBox应该在开始时隐藏,但在选中复选框时可见。请帮忙!

感谢。

1 个答案:

答案 0 :(得分:11)

您可以将TextBox.Visiblity绑定到CheckBox.IsChecked。如果您想在HiddenVisible之间切换,则需要编写自定义IValueConverter或创建简单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>

如果您想在CollapsedVisible之间切换,有一种更简单的方法,您可以在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>