gpt4 book ai didi

c# - 复选框显示/隐藏文本框 WPF

转载 作者:太空狗 更新时间:2023-10-29 21:01:31 24 4
gpt4 key购买 nike

正如标题所说,我试图在 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>

View 模型:

    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.Visiblity 绑定(bind)到 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 之间切换,有一个更简单的方法,你可以使用 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>

关于c# - 复选框显示/隐藏文本框 WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26628213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com