[英]XAML WPF CheckBox Validation
I have a list of CheckBox'es
. 我有一个CheckBox'es
列表。 I would like the user to select at least one before click the next button. 我希望用户在单击下一步之前至少选择一个。
I would want the Button
to remain Enabled
, but use a TextBlock
below the CheckBox
to show the prompt to select at least one CheckBox
. 我希望Button
保持Enabled
,但是使用CheckBox
下面的TextBlock
来显示提示,以选择至少一个CheckBox
。
How can I check that. 我该如何检查。
Code: 码:
XAML XAML
<CheckBox x:Name="CheckBox1" Content="CheckBox1" />
<CheckBox x:Name="CheckBox2" Content="CheckBox2" />
<CheckBox x:Name="CheckBox3" Content="CheckBox3" />
<CheckBox x:Name="CheckBox4" Content="CheckBox4" />
<Button x:Name="NextButton" Click="NextButton_Click"/>
Code Behind 背后的代码
private void NextButton_Click(object sender, RoutedEventArgs e) {
if (CheckBox1.IsChecked ?? false) {
// do something
}
// same for other checkBoxes
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
if (!CheckBox1.IsChecked && !CheckBox2.IsChecked && !CheckBox3.IsChecked && !CheckBox4.IsChecked)
{
// update TextBlock to alert the user
}
else
{
if (CheckBox1.IsChecked)
{
// do something
}
// same for other checkboxes
}
}
You can also do the following, based on the example of just one CheckBox
: 您还可以基于一个CheckBox
的示例执行以下操作:
XAML XAML
<CheckBox x:Name="CheckBox1" Content="CheckBox1" Checked="CheckBox1_OnChecked"/>
// after all your CheckBoxes insert TextBlock below
// which is Visible by default (but invisible once any CheckBox is checked)
<TextBlock x:Name="TextBlock" Visibility="Visible" Text="Please, select at least 1 checkbox"/>
<Button x:Name="NextButton" Click="NextButton_Click" Height="Auto" Width="Auto" Content="Button"/>
Code Behind 背后的代码
private void NextButton_Click(object sender, RoutedEventArgs e)
{
// your code
}
// We make Visibility of TextBox hidden
// Think for yourself how to take into account
// several CheckBoxes checked vs unchecked
private void CheckBox1_OnChecked(object sender, RoutedEventArgs e)
{
TextBlock.Visibility = Visibility.Hidden;
}
Think for yourself how to take into account several CheckBoxes checked vs unchecked, you may also use CheckBoxes
event handler for Unchecked
event: Unchecked="CheckBox1_OnUnchecked"
考虑一下如何考虑多个CheckBoxes已选中和未选中状态,也可以将CheckBoxes
事件处理程序用于Unchecked
事件: Unchecked="CheckBox1_OnUnchecked"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.