XAML
<StackPanel Margin="40">
<TextBlock Text="Pizza Toppings"/>
<CheckBox Content="Pepperoni" x:Name="pepperoniCheckbox"
Click="toppingsCheckbox_Click"/>
<CheckBox Content="Beef" x:Name="beefCheckbox"
Click="toppingsCheckbox_Click"/>
<CheckBox Content="Mushrooms" x:Name="mushroomsCheckbox"
Click="toppingsCheckbox_Click"/>
<CheckBox Content="Onions" x:Name="onionsCheckbox"
Click="toppingsCheckbox_Click"/>
<!-- Display the selected toppings. -->
<TextBlock Text="Toppings selected:"/>
<TextBlock x:Name="toppingsList"/>
</StackPanel>
以下是 Click 事件的事件处理程序。 每次单击某个复选框时,它会检查所有复选框以查看选中的复选框并更新选择的佐料列表。
C#
private void toppingsCheckbox_Click(object sender, RoutedEventArgs e)
{
string selectedToppingsText = string.Empty;
CheckBox[] checkboxes = new CheckBox[] { pepperoniCheckbox, beefCheckbox,
mushroomsCheckbox, onionsCheckbox };
foreach (CheckBox c in checkboxes)
{
if (c.IsChecked == true)
{
if (selectedToppingsText.Length > 1)
{
selectedToppingsText += ", ";
}
selectedToppingsText += c.Content;
}
}
toppingsList.Text = selectedToppingsText;
}
CheckBox 控件继承自 ToggleButton,可拥有三种状态:
状态 属性 值
已选中 IsChecked true
取消选中 IsChecked false
不确定 IsChecked null