user2056563
user2056563

Reputation: 640

Image Binding to string

I am unable to display the image which is in this location Resources/Images/abc.png.

Here is what i am doing:

public class A
    {
private string image;
public string Image
        {
            get { return image; }
            set
            {
                if (value != this.image)
                {
                    image = value;
                }
            }
        }

}

In my .CS file:

if (somecondition)
                    {
                        a.Image = @"Resources/Images/abc.png";
                    }

In my XAML file:

 <DataTemplate x:Key="TopicDataTemplate" >
<Image Stretch="None" 
                               Grid.Row="1"
                               Source="{Binding Image}"/>
</DataTemplate>

But its not displaying the image, how to fix this ? What am i doing wrong here ?

Upvotes: 0

Views: 85

Answers (1)

Clemens
Clemens

Reputation: 128013

Your image path should be ok, provided that there actually is a file named abc.png in a folder named Images in another folder named Resources in your Visual Studio project, and that its Build Action is set to Resource (which is the default).

Update I'm not sure if the above is also true for Windows Phone. I guess that the default conversion from string to ImageSource might not be as capable on that platform as it is in WPF.


However, on either platform, if you want to change the Image property during runtime, you need to implement a property change mechanism that notifies the data binding that the Image property has changed. One way is to implement the INotifyPropertyChanged interface in your class A:

public class A : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string image;
    public string Image
    {
        get { return image; }
        set
        {
            image = value;
            RaisePropertyChanged("Image");
        }
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Obviously it is also necessary that the Image binding is properly set up, i.e. that the DataContext of the templated item holds a reference to an instance of class A.

Upvotes: 2

Related Questions