Mr. Leeds
Mr. Leeds

Reputation: 164

WPF Binding Return StaticResource as String

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?

Upvotes: 0

Views: 267

Answers (1)

mm8
mm8

Reputation: 169200

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;
    }
}

Upvotes: 2

Related Questions