【问题标题】:UWP: Updating UI through data binding from a background threadUWP:通过后台线程的数据绑定更新 UI
【发布时间】: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


【解决方案1】:

您需要在 UI 线程中执行所有图形对象。

典型用法:

obj.Invoke((MethodInvoker) SomeMethod);

How to Use ISynchronizeInvoke interface?

【讨论】:

  • Ken Tucker 的建议更简单,但感谢您提供的信息。
  • MvvmLight?只需使用Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher.RunAsync 调用 UI 线程中的第二个参数函数即可。不需要只包装此代码的框架;)
  • 是的,但是 DispatcherHelper 类(来自 MVVM Light)是用于 UI 线程上的调度程序操作的辅助类...用于多个项目:WPF、通用应用程序、电话, Xamarin for Android, Xamarin for iOS, etc.
  • 我尝试时无法引用 ISynchronizeInvoke。它甚至存在于 UWP 中吗?
猜你喜欢
  • 2020-10-27
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
相关资源
最近更新 更多