在MVVM中使用SaveFileDialog的WPF

在MVVM中使用SaveFileDialog的WPF,wpf,file,mvvm,dialog,save,Wpf,File,Mvvm,Dialog,Save,我正在努力在MVVM中使用SaveFileDialog 我正在使用RelayCommand类并启动SaveAsFileCommand。在SaveAsFileCommand中,使用lambda表达式,我将两个参数拆分为: RichTextBox控件和目标路径(filePath)的实例 然后我使用上述参数调用DataIO.SaveAsFile(参数[0],参数[1]) 要在视图层中创建保存对话框,我将使用3个类: 对话框,文件对话框和保存文件对话框 在XAML中,我创建了SaveDialogBox,

我正在努力在MVVM中使用SaveFileDialog

我正在使用RelayCommand类并启动SaveAsFileCommand。在SaveAsFileCommand中,使用lambda表达式,我将两个参数拆分为:

RichTextBox控件和目标路径(filePath)的实例

然后我使用上述参数调用DataIO.SaveAsFile(参数[0],参数[1])

要在视图层中创建保存对话框,我将使用3个类: 对话框文件对话框保存文件对话框

在XAML中,我创建了SaveDialogBox,并尝试使用多绑定调用SaveAsFileCommand来传递这两个命令参数

要显示保存对话框,我使用绑定到保存对话框的按钮

问题是:在这里,编译器抱怨它无法为我的SaveDialogBox执行多重绑定,因为它是非DependencyObject和非DependencyProperty。
在我的情况下,如何使用符合MVVM的
对话框
解决该问题并正确保存文件

XAML部分代码:

<Button Command="{Binding ElementName=SaveFileDB, Path=Show}" > 
    <Button.ToolTip>
        <ToolTip Style="{StaticResource styleToolTip}" >
            <TextBlock Text="Save" Style="{StaticResource styleTextBlockTP}" />
        </ToolTip>
    </Button.ToolTip>
    <Image Source="Icon\Save.png"/>
</Button>


<local:SaveFileDialogBox x:Name="SaveFileDB" Caption="Save content to file..."
                             Filter="Text files (*.txt)|*.txt|All files(*.*)|*.*"
                             FilterIndex="0" DefaultExt="txt"
                             CommandFileOK="{Binding SaveAsFileCommand}" >
        <local:SaveFileDialogBox.CommandParemeter>
            <MultiBinding Converter="{StaticResource parametersConverter}">
                <Binding ElementName="MainRichTextBox" />
                <Binding ElementName="SaveFileDB" Path="Show" />
            </MultiBinding>
        </local:SaveFileDialogBox.CommandParemeter>
    </local:SaveFileDialogBox>
DataIO.SaveAsFile方法:

    public static void SaveAsFile(object argument0, object argument1)
    {
        System.Windows.Controls.RichTextBox richTB = argument0 as System.Windows.Controls.RichTextBox;
        string path = (string)argument1;


        using (FileStream fileStream = new FileStream(path, FileMode.Create))
        {
            TextRange textRange = new TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd);
            textRange.Save(fileStream, DataFormats.Text);

        }
    }
中继命令类:

class RelayCommand : ICommand
{
    private readonly Action<object> _Execute;
    private readonly Func<object, bool> _CanExecute;

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
    {
        if (execute == null) throw new ArgumentNullException("execute");
        _Execute = execute;
        _CanExecute = canExecute;
    }

    public RelayCommand(Action<object> execute)
    {
        if (execute == null) throw new ArgumentNullException("execute");
        _Execute = execute;
    }

    public bool CanExecute(object parameter)
    {
        return _CanExecute == null ? true : _CanExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add
        {
            if (_CanExecute != null) CommandManager.RequerySuggested += value;
        }
        remove
        {
            if (_CanExecute != null) CommandManager.RequerySuggested -= value;
        }
    }

    public void Execute(object parameter)
    {
        _Execute(parameter);
    }
}
SaveFileDialogBox类:

public abstract class DialogBox : FrameworkElement, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string parameter)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(parameter));
    }

    protected Action<object> execute = null;

    public string Caption { get; set; }

    protected ICommand show;
    public virtual ICommand Show
    {
        get
        {
            if (show == null)
                show = new RelayCommand(execute);
            return show;
        }
    }
}
public abstract class FileDialogBox : CommandDialogBox
{
    public bool? FileDialogResult { get; protected set; }
    public string FilePath { get; set; }
    public string Filter { get; set; }
    public int FilterIndex { get; set; }
    public string DefaultExt { get; set; }

    protected Microsoft.Win32.FileDialog fileDialog = null;

    protected FileDialogBox()
    {
        execute =
            o =>
            {
                var values = (object[])o;
                RelayCommand relCom1 = (RelayCommand)values[1];

                fileDialog.Title = Caption;
                fileDialog.Filter = Filter;
                fileDialog.FilterIndex = FilterIndex;
                fileDialog.DefaultExt = DefaultExt;

                string filePath = "";

                if (FilePath != null) filePath = FilePath; else FilePath = "";
                //if (o != null) filePath = (string)o;
                //if (o != null) filePath = (string)values[1];
                if (o != null) filePath = relCom1.ToString();
                if (!String.IsNullOrWhiteSpace(filePath))
                {
                    fileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(filePath);
                    fileDialog.FileName = System.IO.Path.GetFileName(filePath);
                }

                FileDialogResult = fileDialog.ShowDialog();
                OnPropertyChanged("FileDialogResult");
                if (FileDialogResult.HasValue && FileDialogResult != null)
                {
                    FilePath = fileDialog.FileName;
                    OnPropertyChanged("FilePath");
                    ExecuteCommand(CommandFileOK, FilePath);
                };
            };
    }

    public static DependencyProperty CommandFileOKProperty =
        DependencyProperty.Register("CommandFileOK", typeof(ICommand), typeof(FileDialogBox));

    public ICommand CommandFileOK
    {
        get { return (ICommand)GetValue(CommandFileOKProperty); }
        set { SetValue(CommandFileOKProperty, value); }
    }
}
public class SaveFileDialogBox : FileDialogBox
{
    public SaveFileDialogBox()
    {
        fileDialog = new SaveFileDialog();
    }
}

我在对话框中处理用户输入需求的方法是使用一个进入视图但没有UI的控件。
我将要执行的命令分为两部分。
基本上,它们是显示对话框并在完成时调用命令。
控件显示一个对话框,该对话框获取数据,然后调用通过绑定给它的命令。
由于这是一个控件,您可以很好地绑定它,并且它位于可视化树中,因此它可以获取对窗口的引用

请参见以下内容中的确认请求者:

这是为了确认删除记录,但同样的原则也可以扩展到文件选择器,只需稍加修改

因此,用户单击并关闭对话框后调用的命令可以捕获所需的任何变量。如果您绑定它们:

private RelayCommand _confirmCommand;
public RelayCommand ConfirmCommand
{
    get
    {
        return _confirmCommand
          ?? (_confirmCommand = new RelayCommand(
               () =>
               {
                   confirmer.Caption = "Please Confirm";
                   confirmer.Message = "Are you SURE you want to delete this record?";
                   confirmer.MsgBoxButton = MessageBoxButton.YesNo;
                   confirmer.MsgBoxImage = MessageBoxImage.Warning;
                   OkCommand = new RelayCommand(
                       () =>
                       {
                           // You would do some actual deletion or something here
                           UserNotificationMessage msg = new UserNotificationMessage { Message = "OK.\rDeleted it.\rYour data is consigned to oblivion.", SecondsToShow = 5 };
                           Messenger.Default.Send<UserNotificationMessage>(msg);
                       });
                   RaisePropertyChanged("OkCommand");
                   ShowConfirmation = true;
               }));
    }
}

我假设您希望自己实现这些对话框?因为如果您对内置系统对话框感到满意,并且仍然对MVVM友好,那么总会有MVVM对话框供您使用。在这种情况下,我需要实现内置对话框(完全是来自Microsoft.Win32命名空间的对话框),但我想从视图层调用它们,而不是从ViewModel或Model调用它们-这会导致问题
private RelayCommand _confirmCommand;
public RelayCommand ConfirmCommand
{
    get
    {
        return _confirmCommand
          ?? (_confirmCommand = new RelayCommand(
               () =>
               {
                   confirmer.Caption = "Please Confirm";
                   confirmer.Message = "Are you SURE you want to delete this record?";
                   confirmer.MsgBoxButton = MessageBoxButton.YesNo;
                   confirmer.MsgBoxImage = MessageBoxImage.Warning;
                   OkCommand = new RelayCommand(
                       () =>
                       {
                           // You would do some actual deletion or something here
                           UserNotificationMessage msg = new UserNotificationMessage { Message = "OK.\rDeleted it.\rYour data is consigned to oblivion.", SecondsToShow = 5 };
                           Messenger.Default.Send<UserNotificationMessage>(msg);
                       });
                   RaisePropertyChanged("OkCommand");
                   ShowConfirmation = true;
               }));
    }
}
    public static readonly DependencyProperty ShowConfirmDialogProperty =
        DependencyProperty.Register("ShowConfirmDialog",
                    typeof(bool?),
                    typeof(ConfirmationRequestor),
                    new FrameworkPropertyMetadata(null
                        , new PropertyChangedCallback(ConfirmDialogChanged)
                        )
                    { BindsTwoWayByDefault = true }
                    );
    private static void ConfirmDialogChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if ((bool?)e.NewValue != true)
        {
            return;
        }
        ConfirmationRequestor cr = (ConfirmationRequestor)d;
        Window parent = Window.GetWindow(cr) as Window;
        MessageBoxResult result = MessageBox.Show(parent, cr.Message, cr.Caption, cr.MsgBoxButton, cr.MsgBoxImage);
        if (result == MessageBoxResult.OK || result == MessageBoxResult.Yes)
        {
            if (cr.Command != null)
            {
                cr.Command.Execute(cr.CommandParameter);
            }
        }
        cr.SetValue(ShowConfirmDialogProperty, false);
    }