我正在使用 MVVM 模式将一个简单的 WinForm 应用程序转换为 WPF。我的偏爱实现的视图模型代码如下。我被困住了showPath(string path)
,addFile(string file)
因为他们正在使用 WPF 控件。我怎样才能克服这个问题?
class DirectorySearchModel
{
/*-- invoke on UI thread --------------------------------*/
void showPath(string path)
{
//textBlock1.Text = path;
//return path;
}
/*-- invoke on UI thread --------------------------------*/
void addFile(string file)
{
//listBox1.Items.Add(file);
}
/*-- recursive search for files matching pattern --------*/
void Search(string path, string pattern)
{
/* called on asynch delegate's thread */
if (System.Windows.Application.Current.Dispatcher.CheckAccess())
showPath(path);
else
System.Windows.Application.Current.Dispatcher.Invoke(
new Action<string>(showPath), DispatcherPriority.Background, new string[] { path }
);
string[] files = Directory.GetFiles(path, pattern);
foreach (string file in files)
{
if (System.Windows.Application.Current.Dispatcher.CheckAccess())
addFile(file);
else
System.Windows.Application.Current.Dispatcher.Invoke(new Action<string>(addFile), DispatcherPriority.Background,
new string[] { file }
);
}
string[] dirs = System.IO.Directory.GetDirectories(path);
foreach (string dir in dirs)
Search(dir, pattern);
}
}