复选框显示/隐藏文本框WPF

安德烈·科洛什(Andre Korosh)反复

就像标题所说的那样,Iam试图在WPF中显示/隐藏文本框,而不在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>

ViewModel:

    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;
}

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

谢谢。

dkozl

您可以绑定TextBox.VisiblityCheckBox.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>

如果您想在两者之间进行切换,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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章