0

I created a custom checkbox using a UserControl with Image and Label inside. I want to swap the Checked and Unchecked images whenever i click it. So far i tried doing the following

<Image Source="{Binding StateImage}"/>

I have a property named StateImage

public String StateImage
{
     get
     {
         return is_checked?"{StaticResource Checked}":"StaticResource Unchecked";
     }
}

My code doesn't work and i ended up doing like this:

public String StateImage
    {
         get
         {
             return is_checked?"/Resources/Images/Checked.png":"/Resources/Images/Unchecked.png";
         }
    }

the is_checked variable is modified under MouseDown Event of the UserControl

Is there an easier way I can call the image without writing the whole path and filename?

3
  • You can always ditch the UserControl and create a custom control based on Checkbox, have different image properties for each state and swap the images via ControlTemplate.Triggers. However, this suggestion is a bit far from your question, so I don't feel like it should be a full blown answer for now. Commented Sep 13, 2017 at 6:59
  • 1
    You wouldn't even need a custom control. An appropriate CheckBox Style is sufficient. Commented Sep 13, 2017 at 8:15
  • I'm new to WPF and I'm having a hard time analyzing control templates. That's why I used a method I am comfortable with. But I guess, there's no other way but to study on how to override their default template. Commented Sep 13, 2017 at 14:13

1 Answer 1

2

You could define the resources as strings in the UserControl:

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             xmlns:s="clr-namespace:System;assembly=mscorlib">
    <UserControl.Resources>
        <s:String x:Key="Checked">pic.png</s:String>
        <s:String x:Key="UnChecked"></s:String>
    </UserControl.Resources>
    <Grid Background="Yellow">
        <Image Source="{Binding StateImage}"/>
    </Grid>
</UserControl>

private bool is_checked;
public String StateImage
{
    get
    {
        return is_checked ? Resources["Checked"] as string : Resources["UnChecked"] as string;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.