WPF图像源绑定不起作用

时间:2014-08-13 18:10:56

标签: c# wpf xaml

我知道Stackoverflow中有很多已回答的问题,但我无法让我的代码处理图像源绑定。我不知道自己做错了什么。我知道答案可能非常简单,但作为WPF的初学者,我真的被卡住了。

XAML是:     

    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>    

和C#代码是:

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"));

}
}
}

1 个答案:

答案 0 :(得分:0)

XAML中的绑定表达式中存在拼写错误。在调试器中运行应用程序时,应该会看到绑定错误消息。

更改

Source="{Binding ImagetoDisplay}"

Source="{Binding ImageToDisplay}"