[英]Binding Image.Source from BitmapImage variable using INotifyPropertyChanged
I want to bind my CurrentWallpaper variable to Image.Source and update the Image control when it changes. 我想将CurrentWallpaper变量绑定到Image.Source并在更改时更新Image控件。 That's my code:
那是我的代码:
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public BitmapImage CurrWall = new BitmapImage();
BitmapImage CurrentWallpaper
{
get { return CurrWall; }
set { CurrWall = value; OnPropertyChanged("CurrentWallpaper"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
At the Page tag I've added this DataContext attribute. 在Page标记处,我添加了此DataContext属性。
DataContext="{Binding RelativeSource={RelativeSource Self}}"
And that is my Image control 那就是我的图像控件
<Image x:Name="CurrentWallpaperImage" Source="{x:Bind CurrWall}"/>
When i try to set a new source, the Image control doesn't update. 当我尝试设置新的来源时,图像控件不会更新。
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(path);
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
await CurrentWallpaper.SetSourceAsync(stream);
You are not actually assigning a new value to the CurrentWallpaper property of your page. 您实际上并没有为页面的CurrentWallpaper属性分配新值。 So the OnPropertyChanged isn't triggered.
因此,不会触发OnPropertyChanged。
2 options, or you still use the SetSource method but after that line call the OnPropertyChanged("CurrentWallpaper");
2个选项,或者您仍然使用SetSource方法,但在该行之后调用
OnPropertyChanged("CurrentWallpaper");
yourself to ensure the UI is updated. 您自己,以确保更新用户界面。
Or create a new BitmapImage with the stream you have and fully assing that new bitmapimage to your CurrentWallpaper. 或者使用您拥有的流创建一个新的BitmapImage并将该新的bitmapimage完全添加到CurrentWallpaper中。
CurrentWallpaper = newBitmapImage;
At first, declare CurrentWallpaper
as public
property 首先,将
CurrentWallpaper
声明为public
财产
private BitmapImage currentWall = new BitmapImage();
public BitmapImage CurrentWallpaper
{
get { return currentWall; }
set { currentWall= value; OnPropertyChanged("CurrentWallpaper"); }
}
At second, change Binding
to OneWay
第二,将
Binding
更改为OneWay
<Image x:Name="CurrentWallpaperImage" Source="{x:Bind CurrWall, Mode=OneWay}"/>
If it will not work after first or second steps, try to raise event manually 如果在第一步或第二步后它不起作用,请尝试手动引发事件
await CurrentWallpaper.SetSourceAsync(stream);
OnPropertyChanged("CurrentWallpaper");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.