我只是想知道这是在MVVM中显示对话的方式吗?

public ICommand OpenFileCommand
{
    get
    {
        if (_openFileCommand == null) {
            _openFileCommand = new RelayCommand(delegate
            {
                var strArr = DialogsViewModel.GetOpenFileDialog("Open a file ...", "Text files|*.txt | All Files|*.*");
                foreach (string s in strArr) {
                    // do something with file
                }
            });
        }
        return _openFileCommand;
    }
}

public class DialogsViewModel {
    public static string[] GetOpenFileDialog(string title, string filter)
    {
        var dialog = new OpenFileDialog();
        dialog.Title = title;
        dialog.Filter = filter;
        dialog.CheckFileExists = true;
        dialog.CheckPathExists = true;
        dialog.Multiselect = true;
        if ((bool)dialog.ShowDialog()) {
            return dialog.SafeFileNames;
        }
        return new string[0];
    }
}

如果是这样,我应该如何让自己说修改我正在显示的对话框中的选项。例如,我希望另一个对话框具有不同的对话框选项 dialog.something = something_else 没有在我的方法中添加很多论点

有帮助吗?

解决方案

显示对话框本身不应在ViewModel中发生。我通常提供对话框界面idiaialogservices,并使用适当的对话方法调用。然后,我有一个视图类(通常是MainWindow)实现此接口并执行实际的Show Logic。这将您的ViewModel逻辑从特定视图中隔离,例如,您可以将要打开对话框的测试代码单元。

然后,主要任务是将服务接口注入需要它的视图模型。如果您有一个依赖项注入框架,这是最简单的,但是您也可以使用服务位置器(可以在其中可以注册接口实现的静态类)或通过其构造函数将接口传递到ViewModel(取决于ViewModels的方式)被构造。)

其他提示

我认为使用DialogService是一种重量级方法。我喜欢使用Action/Lambdas来解决此问题。

您的视图模型可能将其作为声明:

public Func<string, string, dynamic> OpenFileDialog { get; set; }

然后,呼叫者会这样创建您的视图模型:

var myViewModel = new MyViewModel();
myViewModel.OpenFileDialog = (title, filter) =>
{
    var dialog = new OpenFileDialog();
    dialog.Filter = filter;
    dialog.Title = title;

    dynamic result = new ExpandoObject();
    if (dialog.ShowDialog() == DialogResult.Ok) {
        result.Success = true;
        result.Files = dialog.SafeFileNames;
    }
    else {
        result.Success = false;
        result.Files = new string[0];
    }

    return result;
};

然后,您可以称其为:

dynamic res = myViewModel.OpenFileDialog("Select a file", "All files (*.*)|*.*");
var wasSuccess = res.Success;

这种类型的方法确实可以进行测试。因为您的测试可以将视图模型的返回定义为他们喜欢的任何内容:

 myViewModelToTest.OpenFileDialog = (title, filter) =>
{
    dynamic result = new ExpandoObject();
    result.Success = true;
    result.Files = new string[1];
    result.Files[0] = "myexpectedfile.txt";

    return result;
};

就个人而言,我发现这种方法是最简单的。我会喜欢别人的想法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top