I am having trouble getting this button (with an image in its content) to correctly change the ImageSource
on click. Here is my Xaml and Code Behind.
XAML:
<Window.Resources>
<Style x:Key="NoChromeButton" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid x:Name="Chrome" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="#ADADAD"/>
<Setter Property="Opacity" TargetName="Chrome" Value="0.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button x:Name="DrawCircleButton" Height="56" Width="157"
Margin="10,10,0,0" VerticalAlignment="Top"
HorizontalAlignment="Left" Click="DrawCircleButtonClick"
Style="{DynamicResource NoChromeButton}"
>
<Image x:Name="imgButtonState" >
<Image.Source>
<BitmapImage UriSource="Resources/off.gif" />
</Image.Source>
</Image>
</Button>
<ScrollViewer Margin="0,50,0,0">
<TextBlock Name="textBlock1" TextWrapping="Wrap" FontSize="20" FontWeight="Bold" />
</ScrollViewer>
</Grid>
Code Behind:
private void DrawCircleButtonClick(object sender, RoutedEventArgs e)
{
var t = ButtonState;
ButtonState = t;
}
public bool ButtonState
{
get
{
return (bool)GetValue(ButtonStateProperty);
}
set
{
var t = new BitmapImage(new Uri("Resource/on.gif", UriKind.Relative));
DrawCircleButton.Content = !value ? imgButtonState.Source = new BitmapImage(new Uri("on.gif", UriKind.Relative)) : imgButtonState.Source = new BitmapImage(new Uri("off.gif", UriKind.Relative));
SetValue(ButtonStateProperty, !value);
}
}
public static readonly DependencyProperty ButtonStateProperty = DependencyProperty.Register("ButtonState", typeof(bool), typeof(bool));
So initially, the button is set to 'off'. But as it gets clicked, it toggles between 'on' and 'off'. I'm sure I did something wrong cause what gets displayed is text to the path of the images. Any ideas?