【发布时间】:2015-12-16 18:22:55
【问题描述】:
我在我的 UWP 应用程序中使用 x:Bind(编译绑定)将 TextBlock 绑定到 ViewModel 中的整数属性,该属性由值转换器转换为字符串。我在工作线程的 ViewModel 中使用一种方法来设置属性并调用 PropertyChanged 事件。但是,我收到一个异常(具体来说,它在 MainPage.g.cs 文件的 XamlBindingSetters 类中)说,“应用程序调用了一个为不同线程编组的接口。” According to this post,这在 WPF 中应该可以正常工作;是否在 WinRT/UWP 中删除了这种易于使用的功能,还是我做错了什么?
这正是我正在做的事情。
我的属性是这样定义的:
private int myProperty;
public int MyProperty
{
get { return myProperty; }
set
{
Set(ref myProperty, value);
}
}
Set 方法是 Template 10 库的一部分并被定义:
public bool Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (object.Equals(storage, value))
return false;
storage = value;
RaisePropertyChanged(propertyName);
return true;
}
据我所见,没有错;它只是确保新值与旧值不同,然后调用 RaisePropertyChanged(propertyName) 以确保应用程序实际运行(不在设计模式下),然后引发 PropertyChanged 事件。
我从工作线程设置我的属性:
MyProperty = newValue;
当它到达 XamlBindingSetters 类时:
internal class XamlBindingSetters
{
public static void Set_Windows_UI_Xaml_Controls_TextBlock_Text(global::Windows.UI.Xaml.Controls.TextBlock obj, global::System.String value, string targetNullValue)
{
if (value == null && targetNullValue != null)
{
value = targetNullValue;
}
obj.Text = value ?? global::System.String.Empty;
}
};
它在最后一行中断 (obj.Text = ...),并告诉我应用程序调用了一个为不同线程编组的接口。我做错了什么?
【问题讨论】:
-
您从错误的线程更新 UI。请参阅此问题以获取答案stackoverflow.com/questions/10579027/…
-
好的,谢谢。我希望它会像在 WPF 中一样自动处理,但我自己实现这一点并不难。
标签: c# multithreading windows-runtime winrt-xaml uwp