我的WPf应用程序中有这个类,现在我想为xamarin.forms应用程序添加这个,当我在Dispatcher.CheckAccess
添加这个时显示error.on谷歌搜索了解到,而不是Dispatcher我必须使用Device.BeginInvokeOnMainThread()。但是不明白如何应用它。
public static void HandleInvokeRequired<T>(this T control, Action<T> action) where T : Control
{
//Check to see is the control is not null
if (control == null)
throw new ArgumentNullException(string.Format("Cannot execute {0} on {1}. {1} is null.", action, control));
if (control.Dispatcher.CheckAccess())
{
try
{
//Perform the action
action(control);
}
catch (Exception ex)
{
throw new Exception(string.Format("Cannot execute {0} on {1}. {2}.", action, control, ex.Message));
}
}
else
{
try
{
//Use Invoke() to invoke your action
control.Dispatcher.Invoke(action, new object[] { control });
}
catch (Exception ex)
{
throw new Exception(string.Format("Cannot execute {0} on {1}. {2}.", action, control, ex.Message));
}
}
}
答案 0 :(得分:0)
我在CheckAccess
中找不到关于Xamarin.forms
的任何文档。
也许它在桌面应用程序中可用,但通常需要在主线程上而不是在其他线程中操作UI。所以下面的代码就足够了。
if (control == null)
throw new ArgumentNullException(string.Format("Cannot execute {0} on {1}. {1} is null.", action, control));
try
{
Device.BeginInvokeOnMainThread(action);
}
catch (Exception ex)
{
throw new Exception(string.Format("Cannot execute {0} on {1}. {2}.", action, control, ex.Message));
}
行动 - &gt;动作:
尝试:
Action newAction = () => { action(control); };
或者
Action newAction = new Action(() => { action(control); });