benxhhe
benxhhe

Reputation: 3

WPF image source binding doesn't work

I know there are a lot of answered questions in Stackoverflow but I just cannot get my code working on image source binding. I don't know what I did wrong. I know the answers is probably very trivial but as a beginner on WPF I am really stuck.

the XAML is:

    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top"
            Width="75" MouseDoubleClick="Button_MouseDoubleClick"/>
    <Image HorizontalAlignment="Left" Height="100" VerticalAlignment="Bottom" 
           Width="100" Source="{Binding ImagetoDisplay}"/>

</Grid>

</Window>    

and the C# code is:

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    ImageHandler NewImage = new ImageHandler();

    public MainWindow()
    {



        InitializeComponent();
        DataContext = NewImage;

        NewImage.ImageToDisplay = new BitmapImage(new Uri(@"C:\Image\flower.jpg"));
    }

public class ImageHandler : INotifyPropertyChanged
{
    private  ImageSource imageToDisplay;
    public ImageSource ImageToDisplay
{
    get { return imageToDisplay; }
    set
    {
        if (imageToDisplay != value)
        {
            imageToDisplay = value;
            OnPropertyChanged("ImageToDisplay");
        }
    }
 }
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
        handler(this, new PropertyChangedEventArgs(propertyName));
}


  }



private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    NewImage.ImageToDisplay = new BitmapImage(new Uri(@"C:\Image\flower.jpg"));

}
}
}

Upvotes: 0

Views: 2508

Answers (1)

Clemens
Clemens

Reputation: 128013

There is a typo in the binding expression in XAML. When you run your application in the debugger, you should see a binding error message.

Change

Source="{Binding ImagetoDisplay}"

to

Source="{Binding ImageToDisplay}"

Upvotes: 2

Related Questions