2
我正在使用MVVM模式將簡單的WinForm應用程序轉換爲WPF。我偏好實施的視圖模型代碼如下。我卡在showPath(string path)
和addFile(string file)
方法中,因爲它們使用的是WPF控件。我如何克服這個問題?將WinForm應用程序轉換爲WPF ViewModel
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);
}
}
我做了更改,按您的建議,但我在這行System.Windows.Application.Current.Dispatcher.Invoke( 新動作(ShowPath),DispatcherPriority.Background,新的String [] {}路徑越來越 –
錯誤我寫它:'Application.Current.Dispatcher.Invoke(新的行動(()=> this.addFile(文件)),DispatcherPriority.Background);' –
得到它感謝:) –