【发布时间】:2014-10-29 10:39:29
【问题描述】:
正如标题所说,我试图在 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>
视图模型:
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 应该在开始时隐藏,但在选中复选框时可见。请帮忙!
谢谢。
【问题讨论】:
-
我认为您首先需要将 CheckBox 绑定到视图模型上的属性,然后创建一个 Converter 将布尔属性值转换为可见性枚举。