Using:
- Visual Studio Community Edition 2015
- .Net 4.0
I implemented this answer by creating my own CheckBox class with IsChecked DependencyProperty . This property is supported by the IsChecked property in WPF CheckBox or will be if it works. Work will mean that my getter and setter is called when the checkmark is switched.
If I rename my property to IsChecked_temp and modify the XAML to match, it works fine. I think this is a name conflict, but why ElementName n't the ElementName resolve it? My minimum test follows.
EDIT 0: I forgot to mention, I have no errors or warnings.
EDIT 1: This answer was originally accepted because it works for a test case, but apparently this is not the whole answer. Applying it to my project (and renaming the CheckBox class to ToggleBox ), every time I use the property, we get a XamlParseException :
Binding cannot be set in the IsChecked property of the ToggleBox type. Binding can only be set in the DependencyProperty of a DependencyObject.
I will try to get a minimal test case to show this.
Checkbox.xaml
<UserControl x:Class="CheckBox_test.CheckBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Self"> <StackPanel> <CheckBox IsChecked="{Binding IsChecked, ElementName=Self}" /> </StackPanel> </UserControl>
Checkbox.xaml.cs
using System.Windows; using System.Windows.Controls; namespace CheckBox_test { public partial class CheckBox : UserControl { public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register( "IsChecked", typeof(bool), typeof(CheckBox), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)); public bool IsChecked { get { return (bool)GetValue(IsCheckedProperty); } set { SetValue(IsCheckedProperty, value); } } public CheckBox() { InitializeComponent(); } } }
MainWindow.xaml
<Window x:Class="CheckBox_test.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:CheckBox_test"> <Grid> <local:CheckBox /> </Grid> </Window>
MainWindow.xaml.cs (for completeness)
using System.Windows; namespace CheckBox_test { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }