【发布时间】: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