我有一个要求,更新我的仪表板上的图像,一旦它已更新到下一页(配置文件页)。
导航栏:Dashboard ->个人资料页->更新图片->仪表盘(按下后退键)
XAML
<ImageButton x:Name="profilePicThumbnail"
....
Command="{Binding UserProfileBtn}"
IsVisible="{Binding IsRemotePic}">
<ImageButton.Source>
<UriImageSource Uri="{Binding UserPic, Mode=TwoWay}"
CachingEnabled="false"/>
</ImageButton.Source>
</ImageButton>
ViewModel.cs
private Uri userpic;
public Uri UserPic
{
get { return userpic; }
set
{
userpic = value;
OnPropertyChanged();
}
}
如何输入UserPic
UserPic = new Uri(dash.student_details.profile_pic); //URL as a string
然而,我的图像没有更新,虽然我在个人资料页面更新后调用相对方法,并回到仪表板。我从后端接收的Url字符串总是相同的(但更新后的图像不一样)
有办法我可以做到这一点吗??
更新:
另一种方法是使用MessagingCenter或WeakReferenceMessenger(对于WeakReferenceMessenger,您必须安装CommunityToolkit)。Mvvm package from nuget.org .
假设ProfilePage中有一个用于按钮的Clicked方法来更新UserPic。在这个方法的ProfilePage中,我们发送了一条消息,告诉Dashboard的视图模型更新UserPic。
void Button_Clicked(System.Object sender, System.EventArgs e)
{
Uri newUri = new Uri("...");
MessagingCenter.Send<ProfilePage, Uri>(this, "Hi", newUri);
}
在DashboardViewModel中,我们订阅这个消息然后更新值
public DashboardViewModel()
{
MessagingCenter.Subscribe<ProfilePage, Uri>(this, "Hi", (sender, arg) =>
{
UserPic = arg;
});
}
别忘了实现INotifyPropertyChanged.
现在当你返回或按下返回按钮时,该值应该更新。
如果你想使用WeakReferenceMessenger,那几乎是一样的,
发送消息:
WeakReferenceMessenger.Default.Send(new MyMessage(item));
接收消息:
WeakReferenceMessenger.Default.Register<MyMessage>(this, (r, item) =>
{
UserPic = item.value;
});
如果你有任何问题,请提出来。
===================起源回答===============
如果我理解正确的话,您想要更新ProfilePage中的Dashboard属性。我做了一个演示来分享我的想法。
假设ProfilePage中有一个用于更新UserPic的Clicked方法。
在这个方法中,我们做了以下事情:
首先创建Dashboard页面和
然后改变bindingContext的UserPic属性(ViewModel page绑定到)
最终导航到仪表盘页面
void mybutton_Clicked(System.Object sender, System.EventArgs e) { var page = new Dashboard(); DashboardViewModel bindingContext = page.BindingContext as DashboardViewModel; // Here you could change the ViewModel's UserPic, then navigation bindingContext.UserPic = new Uri(...); Navigation.PushAsync(page); }
别忘了为Dashboard设置BindingContext:
this.BindingContext = new DashboardViewModel();
希望它对你有用。