我有一个Xamarin Forms应用程序,它显示绑定到类的图片(RandomChallenge)。该类在视图模型中生成并分配。该类具有一个Uri属性,我们希望将其绑定到视图中的图像。
应用加载时,即使RandomChallenge不为null,也不会显示任何图片。如果我在调试时对UI代码进行更改并保存,则在调试器重新加载图像时可见。好像在页面渲染后填充了RandomChallenge类?如果我要在行RandomChallenge =上放置一个断点,请等待ChallengeDataStore.GetRandomChallenge();。随机挑战已填充。
ViewModel
public class MainMenuViewModel : BaseViewModel
{
public ICommand OpenWebCommand { get; }
public IdentificationChallenge RandomChallenge { get; set; }
public Command LoadChallengeCommand { get; set; }
public MainMenuViewModel()
{
Title = "Main Menu";
LoadChallengeCommand = new Command(async () => await ExecuteLoadChallengeCommand());
this.LoadChallengeCommand.Execute(null);
}
async Task ExecuteLoadChallengeCommand()
{
if (IsBusy)
return;
try
{
RandomChallenge = await ChallengeDataStore.GetRandomChallenge();
Debug.WriteLine("TEst");
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
}
UI
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:microcharts="clr-namespace:Microcharts.Forms;assembly=Microcharts.Forms"
mc:Ignorable="d"
x:Class="HOG.MobileApp.Views.MainMenuPage"
xmlns:vm="clr-namespace:HOG.MobileApp.ViewModels"
xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
Title="{Binding Title}">
<ContentPage.Resources>
<ResourceDictionary>
<Color x:Key="Primary">#72a230</Color>
<Color x:Key="Accent">#72a230</Color>
<Color x:Key="LightTextColor">#72a230</Color>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.ToolbarItems>
<ToolbarItem Text="Help" />
</ContentPage.ToolbarItems>
<ContentPage.Content>
<Image Source="{ Binding RandomChallenge.Picture }" HeightRequest="450" WidthRequest="450" />
</ContentPage.Content>
答案 0 :(得分:1)
所以答案是分配了RandomChallenge时调用OnPropertyChanged。 ViewModel确实在其父类上实现了INotifyPropertyChanged。
async Task ExecuteLoadChallengeCommand()
{
if (IsBusy)
return;
try
{
RandomChallenge = await ChallengeDataStore.GetRandomChallenge();
OnPropertyChanged("RandomChallenge");
Debug.WriteLine("TEst");
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}