在我的WPF MVVM应用程序的视图模型和数据模型下面。我在执行调用时遇到问题(见下文),抛出异常参数计数不匹配。方法“getDataFromDatabase”返回“UserData”的集合。那么如何解决这个问题?
查看模型:
public class MyViewModel : BaseViewModel
{
private static Dispatcher _dispatcher;
public ObservableCollection<UserData> lstUsers
public ObservableCollection<UserData> LstUsers
{
get
{
return this.lstUsers;
}
private set
{
this.lstUsers= value;
OnPropertyChanged("LstUsers");
}
}
// LoadData is called from the constructor of the view code-behind (xaml.cs) once DataContext is correctly set.
public void LoadData()
{
ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
{
var result = getDataFromDatabase();
UIThread((p) => LstUsers = result);
}));
}
ObservableCollection<UserData> getDataFromDatabase()
{
return this.RequestDataToDatabase();
}
static void UIThread(Action<object> a)
{
if(_dispatcher == null)
{
_dispatcher = Dispatcher.CurrentDispatcher;
}
_dispatcher.Invoke(a); <---- HERE EXCEPTION IS THROWN
}
}
数据模型:
public class UserData
{
public string ID{ get; set; }
public string Name { get; set; }
public string Surname { get; set; }
// Other properties
}
答案 0 :(得分:1)
Action<object>
是一个参数类型为对象的Action。它必须通过Invoke(Delegate method, params object[] args)
重载使用单个参数调用:
Application.Current.Dispatcher.Invoke(a, someObject);
所以将Action<object>
更改为Action
:
static void UIThread(Action a)
{
Application.Current.Dispatcher.Invoke(a);
}
并将其称为:
UIThread(() => LstUsers = result);
您可能还想让LoadData方法异步并按如下方式编写:
public async Task LoadData()
{
await Task.Run(() =>
{
var result = getDataFromDatabase();
Application.Current.Dispatcher.Invoke(() => LstUsers = result);
});
}