C# – change image source on click

cwpf

I've made a custom image for a checkbox and want it to switch between the checked and the unchecked version every time the image is clicked. My sourcecode:

XAML

<CheckBox Name="checkBox1" Padding="0" BorderThickness="0" Margin="5" Grid.Row="1">
    <Image Name="image1" Margin="-14,0,0,0" Source="checkbox0.png" MouseDown="Image_MouseDown" Stretch="Uniform"/>
</CheckBox>

C#

private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
     if (e.LeftButton == MouseButtonState.Pressed)
     {
         if (checkBox1checked)
         {
             image1.BeginInit();
             image1.Source = new BitmapImage(new Uri("/checkbox0.png", UriKind.RelativeOrAbsolute));
             image1.EndInit();
             checkBox1checked = false;
         }

         if (!checkBox1checked)
         {
             image1.BeginInit();
             image1.Source = new BitmapImage(new Uri("/checkbox1.png", UriKind.RelativeOrAbsolute));
             image1.EndInit();
             checkBox1checked = true;
         }
     }
}

Best Answer

Use the Uncheck and Check event of the checkbox, and set the image source in there

<CheckBox Name="checkBox1" Padding="0" Unchecked="chkbox_Unchecked" Checked="chkbox_Checked BorderThickness="0" Margin="5" Grid.Row="1">
   <Image Name="image1" Margin="-14,0,0,0" Source="checkbox0.png" Stretch="Uniform"/>
</CheckBox>




        private void chkbox_Checked(object sender, RoutedEventArgs e)
        {
            SetImage("/checkbox0.png");
        }

        private void chkbox_Checked(object sender, RoutedEventArgs e)
        {
             SetImage("/checkbox1.png");
        }

    private void SetImage(string path)
    {
        image1.BeginInit();
                image1.Source = new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute));
                image1.EndInit();

    }
Related Topic