C# UWP绑定异步加载的数据
我有两个页面,当我从第一个页面导航到另一个页面时,我会向它发送一个id(在NavigationEvent中)。然后,我在其ViewModel上调用一个函数,该函数传递id,并通过服务将对象异步加载到ViewModel的属性。我在视图中绑定了对象的属性,并尝试在对象的getter中调用PropertyChanged.Invoke,但它始终为null。我如何将我的观点与此obejct绑定 我要绑定的数据类:C# UWP绑定异步加载的数据,c#,events,uwp,binding,viewmodel,C#,Events,Uwp,Binding,Viewmodel,我有两个页面,当我从第一个页面导航到另一个页面时,我会向它发送一个id(在NavigationEvent中)。然后,我在其ViewModel上调用一个函数,该函数传递id,并通过服务将对象异步加载到ViewModel的属性。我在视图中绑定了对象的属性,并尝试在对象的getter中调用PropertyChanged.Invoke,但它始终为null。我如何将我的观点与此obejct绑定 我要绑定的数据类: class Dog: INotifyPropertyChanged { privat
class Dog: INotifyPropertyChanged
{
private int _name;
public int Name
{
get => _name;
set
{
_name= value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
ViewModel:
class MyViewModel : ViewModelBase
{
public Dog Dog{ get; set; }
public MyViewModel()
{
Dog = new Dog();
}
public async void LoadDog(string id)
{
var service = newvDogService();
Dog = await service.GetDogAsync(id);
}
}
观点:
public sealed partial class DogPage : Page
{
private string dogId { get; set; }
public DogPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
dogId = e.Parameter.ToString();
ViewModel.LoadDog(dogId);
}
}
在xaml文件中:
<Page.DataContext>
<ViewModels:MyViewModel x:Name ="ViewModel"/>
</Page.DataContext>
我建议您可以简化绑定过程。对于对象绑定,不需要使用ViewModel。在NavigationEvent中传递id时,可以直接通过id获取新的Dog对象。首先,可以创建一个Name属性为null的Dog对象。然后可以通过新创建的对象更改以前的对象名称 请参考以下代码 Xaml代码:
<StackPanel DataContext="{x:Bind Dog,Mode=OneWay}">
<TextBlock Text="{Binding Name,Mode=OneWay}"/>
</StackPanel>
最好在转到第二页时创建一个新网页,这样您就可以同时拥有第一页和第二页。当您离开第一页时,您会丢失对象。您也不必导航回原始页面,因为您从未离开过该页面。
<StackPanel DataContext="{x:Bind Dog,Mode=OneWay}">
<TextBlock Text="{Binding Name,Mode=OneWay}"/>
</StackPanel>
public sealed partial class MainPage : Page
{
public Dog Dog { get; set; }
public MainPage()
{
this.InitializeComponent();
Dog = new Dog { Name = "" };
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
dogId = e.Parameter.ToString();
var dog = await service.GetDogAsync(dogId);
Dog.Name=dog.Name;
}
}
public class Dog : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}