如果你想在UI线程上执行代码,并且只想更新属性,那么可以使用MVVM和ViewModel继承该类。
public abstract class NotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected async void OnPropertyChanged([CallerMemberName] string propName = "")
{
await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
});
}
}
所有在 Xaml 数据绑定中使用的属性都可以是单向或双向的,属性中需要使用 OnPropertyChanged() 方法。如果我的代码出现异常并报告“Current 为空”,你可以使用
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
//write your code
//in OnPropertyChanged use PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
});
如果您在用户控件或可见以下代码的页面中编写了代码。
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//UI code here
});
CoreDispatcherPriority可以设置优先级,但不应将其设置为高优先级,请参见CoreDispatcherPriority