将WinForm应用程序转换为WPF ViewModel

时间:2013-04-16 17:24:57

标签: c# wpf mvvm

我正在使用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);
    }



}

1 个答案:

答案 0 :(得分:3)

  

我如何克服这个问题

您将为路径创建两个属性 - 文件名ObservableCollection<string>listBox1)和string(也会在集合上引发PropertyChanged)什么是textBlock1)。然后视图将绑定到这些属性。

这些方法只需要设置路径并添加到集合中,视图就会自动更新。

相关问题