图像源绑定不起作用
问题描述:
我将图像Source
绑定到我的代码中的BitmapImage
,但它不显示。图像源绑定不起作用
XAML:
<Window x:Class="bleh.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="600" d:DesignWidth="600">
<Grid x:Name="LayoutRoot">
<Image x:Name="current" HorizontalAlignment="Center" Stretch="None" VerticalAlignment="Center" Source="{Binding Picture}" />
</Grid>
</Window>
和我的CS:
public partial class MainWindow : Window, INotifyPropertyChanged
{
/// <summary>
/// Event implementing INotifyPropertyChanged interface.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
public BitmapImage Picture { get; set; }
public MainWindow()
{
Uri uri = new Uri("Images/xpto.jpg", UriKind.Relative);
this.Picture = new BitmapImage(uri);
InitializeComponent();
//setup();
}
}
奇怪的是,窗口与图像的大小打开,但我看不到图像。我也尝试在xaml中手动分配,并且它可以工作。
做current.source="Images/xpto.jpg"
也有效。
答
您的视图(MainWindow)的DataContext未设置,因此没有要绑定的“图片”属性。如果您希望视图绑定到自己,请向您的MainWindow构造函数中添加
this.DataContext = this;
。
答
您没有为属性实现INotifyPropertyChanged图片: public BitmapImage Picture {get;组; } 你必须做的:
BitmapImage _picture;
public BitmapImage Picture {
get {return _picture;}
set{
_picture=value;
OnPropertyChanged("Picture");
}`
}
+0
这解决了我的问题。 +1 – MiloDC 2015-06-05 02:11:50
工程,你是如何做到这一点在XAML?我在窗口标签上试过'DataContext =“MainWindow”'并且看起来不起作用 – GriffinHeart 2012-07-19 00:17:15
为你的窗口命名(例如x:Name =“Main”),然后使用Source =“{Binding Picture,ElementName = Main}“ – lesscode 2012-07-19 00:23:32
请注意,尽管您可以绑定Xaml中窗口的DataContext(或其中的任何元素),但您必须绑定到视图中已有的东西(因为当然,您没有DataContext ...) – lesscode 2012-07-19 00:29:30