CheckBox显示/隐藏TextBox WPF

And*_*sti 9 .net c# wpf xaml mvvm

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

模型:

public class Person
{
    public string Comment { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

视图:

<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>
Run Code Online (Sandbox Code Playgroud)

视图模型:

    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;
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

dko*_*ozl 16

你可以绑定TextBox.VisiblityCheckBox.IsChecked.如果要在两者之间切换Hidden,Visible则需要编写自定义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>
Run Code Online (Sandbox Code Playgroud)

如果你想在之间切换Collapsed,Visible有一种更简单的方法,你可以使用内置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>
Run Code Online (Sandbox Code Playgroud)