I have a simple toggle button which works perfectly well . I can click on the toggle button and change the image that it shows . What i now want to do is the same thing from the code behind . Found a link that is similar
EDIT : This is what i want to do
I read up on the following thread that tells exactly what i need to do
WPF ToggleButton.IsChecked binding does not work
Programmatically my code does not seem to have any effect . if i click on the UI it works but i really wanna change state from within the program . The below program is just a prototype .
I cant figure out whats wrong in my XAML or code . Finnally decided to paste all of it as it a test program !
Xaml :
<Window x:Class="ToggleButtonImageChange.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ToggleButtonImageChange"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Image Source="secured.jpg"
x:Key="MyImage1" />
<Image Source="unsecured.jpg"
x:Key="MyImage2" />
<Style TargetType="{x:Type ToggleButton}"
x:Key="MyToggleButtonStyle">
<Setter Property="Content"
Value="{DynamicResource MyImage2}" />
<Style.Triggers>
<Trigger Property="IsChecked"
Value="True">
<Setter Property="Content"
Value="{DynamicResource MyImage2}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<ToggleButton Style="{StaticResource MyToggleButtonStyle}" Name="tgbtn" Margin="0,29,0,139" IsChecked="{Binding Path=isAdmin, Mode=TwoWay}"/>
</Grid>
</Window>
Code behind :
namespace ToggleButtonImageChange
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window,INotifyPropertyChanged
{
bool _isAdmin;
public MainWindow()
{
InitializeComponent();
isAdmin = true;
OnPropertyChanged("isAdmin");
}
public bool isAdmin
{
get
{
return _isAdmin;
}
set
{
_isAdmin = value;
OnPropertyChanged("isAdmin");
}
}
private void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
public event PropertyChangedEventHandler PropertyChanged;
}
I went into the debugger and saw that even though i set isAdmin to true the button isChecked remains false and hence the incorrect image is displayed . I cant quite understand what wrong did do & how to get the isChecked changed through code .