如何使用复选框使文本框可见和隐藏? [英] How do I make a textbox visible and hidden with a checkbox?
问题描述
因此,当未选中复选框时,我试图使我的文本框不可见.一切正常,直到我选中该框,然后再次取消选中它.文本框将保持可见.
So I am trying to make my textbox invisible when a checkbox is not checked. Everything works fine untill I check the box and then uncheck it again. The textbox will stay visible.
private void chbon_Checked_1(object sender, RoutedEventArgs e)
{
if (cchbon.IsChecked == true)
{
txtshow.Visibility = System.Windows.Visibility.Visible;
}
if (chbon.IsChecked == false)
{
txtshow.Visibility = System.Windows.Visibility.Hidden;
}
}
这是复选框的 XAML:
This is the XAML for the Checkbox:
<CheckBox x:Name="chbon" Content="On" HorizontalAlignment="Left" Margin="175,84,0,0" VerticalAlignment="Top" Checked="chbon_Checked_1"/>
<TextBox x:Name="txtshow" HorizontalAlignment="Left" Height="23" Margin="272,82,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="29" Visibility="Hidden"/>
推荐答案
当取消选中发生时,事件 Checked
不会触发.事件 Unchecked
就是为了这个目的.
The event Checked
does not fire when uncheck happens.
The event Unchecked
is for that purpose.
... Checked="chbon_Checked" Unchecked="chbon_Unchecked"/>
并且不需要在后面的代码中监控cchbon.IsChecked
:
and no need to monitor cchbon.IsChecked
in code behind:
private void chbon_Checked(object sender, RoutedEventArgs e)
{
txtshow.Visibility = System.Windows.Visibility.Visible;
}
private void chbon_Unchecked(object sender, RoutedEventArgs e)
{
txtshow.Visibility = System.Windows.Visibility.Hidden;
}
或者,您可以通过绑定和转换器来实现:
Alternatively, you can do it via binding and a converter:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>
...
<CheckBox x:Name="chbon"/>
<TextBox x:Name="txtshow" Visibility="{Binding ElementName=chbon, Path=IsChecked,
Converter={StaticResource BoolToVis}, FallbackValue=Hidden}"/>
请注意,管理此方法后,您可能希望实现自定义转换器,因为内置 BooleanToVisibilityConverter
为 True<返回
Visible
/Collapsed
/code>/False
输入(而不是 Visible
/Hidden
)
Note that,
Once you managed this approach you may want to implement a custom converter since the built-in BooleanToVisibilityConverter
returns Visible
/Collapsed
for True
/False
input (and not Visible
/Hidden
)
这篇关于如何使用复选框使文本框可见和隐藏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!