问题
public class Thumbnail : INotifyPropertyChanged
{
public BitmapImage testimage { get; set; }
Thumbnail()
{
testimage = new BitmapImage(new Uri("http://www.diseno-art.com/news_content/wp-content/uploads/2012/09/2013-Jaguar-F-Type-1.jpg"));
}
}
And a image element in a custom control:
<Image x:Name="previewImage" x:FieldModifier="public" Margin="8" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="{Binding Path=thumbnail.testimage}" Stretch="Fill" />
When i create a control, i do this:
MyControl MC = new MyControl();
MC.DataContext = new Thumbnail();
And image doesn't show up - why?
回答1:
XAML:
<Image x:Name="previewImage" x:FieldModifier="public" Margin="8" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="{Binding Path=testimage}" Stretch="Fill" />
code (cleaner):
public class Thumbnail : INotifyPropertyChanged
{
private BitmapImage tmpbmp;
public BitmapImage testimage { get { return tmpbmp; } set { tmpbmp = value; OnPropertyChanged("testimage"); } }
public Thumbnail()
{
tmpbmp = new BitmapImage(new Uri("http://www.diseno-art.com/news_content/wp-content/uploads/2012/09/2013-Jaguar-F-Type-1.jpg"));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
回答2:
Thumbnail class doesn't have public constructor, doesn't implement INotifyPropertyChanged members (not needed at all in your example). And XAML should be:
<Image x:Name="previewImage" x:FieldModifier="public" Margin="8" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="{Binding Path=testimage}" Stretch="Fill" />
来源:https://stackoverflow.com/questions/20146657/binding-to-bitmapimage