我的MVVM模式出了问题。
class MagnetometrViewModel : INotifyPropertyChanged
{
private Compass compass;
double temp;
public MagnetometrViewModel()
{
compass = Compass.GetDefault();
CompassControl_Loaded();
}
private double heading;
public double Heading
{
get
{
return heading;
}
set
{
heading = value;
OnPropertyChanged("Heading");
}
}
private void CompassControl_Loaded()
{
compass = Windows.Devices.Sensors.Compass.GetDefault();
if (compass != null)
{
compass.ReadingChanged += CompassReadingChanged;
}
}
private void CompassReadingChanged(Windows.Devices.Sensors.Compass sender, Windows.Devices.Sensors.CompassReadingChangedEventArgs args)
{
temp = Convert.ToDouble(args.Reading.HeadingMagneticNorth);
Heading = temp;
//Heading = Convert.ToDouble(args.Reading.HeadingMagneticNorth);
}
#region PropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
当我在那条线路上进行调试时 temp = Convert.ToDouble(args.Reading.HeadingMagneticNorth); 它得到结果,但我的其他方法OnPropertyChanged抛出异常: System.Runtime.InteropServices.COMException
答案 0 :(得分:0)
您需要在UI线程上触发PropertyChanged
事件,如果您正在使用Silverlight Windows Phone应用程序,那么您可以执行类似的操作:
protected delegate void OnUIThreadDelegate();
/// <summary>
/// Allows the specified delegate to be performed on the UI thread.
/// </summary>
/// <param name="onUIThreadDelegate">The delegate to be executed on the UI thread.</param>
protected static void OnUIThread(OnUIThreadDelegate onUIThreadDelegate)
{
if (onUIThreadDelegate != null)
{
if (Deployment.Current.Dispatcher.CheckAccess())
{
onUIThreadDelegate();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(onUIThreadDelegate);
}
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
OnUIThread(() =>
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
});
}
如果您使用的是更现代的通用风格应用,那么只需将OnUIThread
实施更改为更像:
protected async void OnUIThread(DispatchedHandler onUIThreadDelegate)
{
if (onUIThreadDelegate != null)
{
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
if (dispatcher.HasThreadAccess)
{
onUIThreadDelegate();
}
else
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, onUIThreadDelegate);
}
}
}