C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: Sorry for the unimaginative names. It would be better to use more descriptive names that convey meaning.
Next: We add the Checked and Unchecked event handlers to the CheckBox. We allow Visual Studio to create a new event handler (CheckBox_Checked).
CheckBoxExample markup: XAML
<Window x:Class="WpfApplication26.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button"
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top"
Width="75"
Name="MainButton"/>
<CheckBox Content="CheckBox"
HorizontalAlignment="Left"
Margin="10,35,0,0"
VerticalAlignment="Top"
Checked="CheckBox_Checked"
Unchecked="CheckBox_Checked"
Name="MainCheckBox"/>
</Grid>
</Window>
Example code: C#
using System.Windows;
namespace WpfApplication26
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
// ... Access MainCheckBox by name.
// Use its IsChecked property.
bool? state = this.MainCheckBox.IsChecked;
if (state.HasValue)
{
// ... Access MainButton by name.
this.MainButton.Content = state.ToString();
}
}
}
}
Tip: This is the easiest way to get a specific control. No searching or loop-based algorithm is needed.
Instead: The Name from the XAML is transformed into a property on the MainWindow class, ready for use.
Property