【问题标题】:In Xamarin BindingBase.EnableCollectionSynchronization doesn't Work在 Xamarin BindingBase.EnableCollectionSynchronization 不起作用
【发布时间】:2020-12-08 19:19:31
【问题描述】:

我总是在使用 UWP 的 Xamarin 上出现以下错误:

应用程序调用了为不同线程编组的接口。 (来自 HRESULT 的异常:0x8001010E (RPC_E_WRONG_THREAD))

我想使用:

Xamarin.Forms.BindingBase.EnableCollectionSynchronization(MyList, null, ObservableCollectionCallback);

我不会使用:

Xamarin.Forms.Device.BeginInvokeOnMainThread(() => MyList.Add(DateTime.Now.ToLongTimeString()));

我有我的理由。

这是非常简单的 c# ViewModel 代码。您必须将 Xamarin 项目中的 MyList 与 MainPage 中的 UWP 绑定到 ListView:

    public class MainViewModel : INotifyPropertyChanged
{
    public MainViewModel()
    {
        MyList = new ObservableCollection<string>();
        Xamarin.Forms.BindingBase.EnableCollectionSynchronization(MyList, null, ObservableCollectionCallback);
        Timer timer = new Timer(new TimerCallback(Addtext));
        timer.Change(3000, 1000);
    }
    void ObservableCollectionCallback(IEnumerable collection, object context, Action accessMethod, bool writeAccess)
    {
        lock (collection)
        {
            accessMethod?.Invoke();
        }
    }

    public void Addtext(object state)
    {
        MyList.Add(DateTime.Now.ToLongTimeString());
    }
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private ObservableCollection<string> MyListValue;

    public ObservableCollection<string> MyList
    {
        get { return MyListValue; }
        set
        {
            MyListValue = value;
            OnPropertyChanged();
        }
    }

有人知道我该怎么做吗?

【问题讨论】:

    标签: c# xamarin.forms binding xamarin.uwp


    【解决方案1】:

    在 Xamarin BindingBase.EnableCollectionSynchronization 中不起作用

    问题是你在Timer 中调用了Addtext。并且计时器在 un-uithread 中触发。如果不想用BeginInvokeOnMainThread,可以用Device.StartTimer代替Timer

    Device.StartTimer(TimeSpan.FromSeconds(1),()=> {
        Addtext(this);
        return true;
    } );
    

    请查看support 列表,EnableCollectionSynchronization 不支持 UWP 平台。

    【讨论】:

    • 计时器是非 UI 线程的一个简单示例。真正的代码是复杂的。我需要一个解决方案,为什么“Xamarin.Forms.BindingBase.EnableCollectionSynchronization”不起作用。
    • 恐怕不能supportuwp平台。
    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多