I’m trying to create a dependency property called IsChecked for my user control ToggleImageButton. I just want to be able to set and get the IsChecked Property in the ToggleButton. The dependency property doesn’t seem to reflect the actual value of the ToggleButton’s IsChecked property. Please somebody help.
Here is my code behind file:
public partial class ToggleImageButton : UserControl
{
public ToggleImageButton()
{
InitializeComponent();
}
public ImageSource Image
{
get { return (ImageSource)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register("Image", typeof(ImageSource), typeof(ToggleImageButton), new UIPropertyMetadata(null));
public Boolean IsChecked
{
get { return (Boolean)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
}
And here is the xaml file:
<UserControl x:Class="MyControls.ToggleImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="UC">
<Grid Margin="0,0,0,0">
<ToggleButton Margin="0,0,0,0" IsChecked="{Binding RelativeSource={RelativeSource Self}, Path=Source.IsChecked, Mode=TwoWay}">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<Image Source="{Binding ElementName=UC, Path=Image}"
Stretch="Fill"
Width="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelWidth}"
Height="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelHeight}"
Margin="0,0,0,0"/>
</StackPanel>
</ToggleButton>
</Grid>
Ok, I just found the solution. For the IsChecked binding in the xaml file, I was mistakenly using RelativeSource which I had copied and pasted from the height and width properties. I just fixed the isChecked binding so it is IsChecked=”{Binding ElementName=UC, Path=IsChecked} and it worked –