0

如何通过仅调用打印方法而不使用 RelayCommand 从 ViewModel 打印视觉对象或窗口,如本示例所示:使用 MVVM 模式打印 WPF 视觉对象?

var printDlg = new PrintDialog();
printDlg.PrintVisual(View, "JOB PRINTING")
4

1 回答 1

0

好的,这是一个快速而肮脏但可重用的附加行为类。免责声明:我只是在几分钟内破解了它,它有缺陷,应该很容易克服。

首先我们需要我们的服务类。

public class VisualPrinter
{
    private static RoutedUICommand PrintVisualCommand = new RoutedUICommand("PrintVisualCommand", "PrintVisualCommand", typeof(VisualPrinter));

    #region ab PrintCommand

    public static ICommand GetPrintCommand(DependencyObject aTarget)
    {
        return (ICommand)aTarget.GetValue(PrintCommandProperty);
    }

    public static void SetPrintCommand(DependencyObject aTarget, ICommand aValue)
    {
        aTarget.SetValue(PrintCommandProperty, aValue);
    }

    public static readonly DependencyProperty PrintCommandProperty =
        DependencyProperty.RegisterAttached("PrintCommand", typeof(ICommand), typeof(VisualPrinter), new FrameworkPropertyMetadata(PrintVisualCommand));

    #endregion

    #region ab EnablePrintCommand

    public static bool GetEnablePrintCommand(DependencyObject aTarget)
    {
        return (bool)aTarget.GetValue(EnablePrintCommandProperty);
    }
    public static void SetEnablePrintCommand(DependencyObject aTarget, bool aValue)
    {
        aTarget.SetValue(EnablePrintCommandProperty, aValue);
    }

    public static readonly DependencyProperty EnablePrintCommandProperty =
        DependencyProperty.RegisterAttached("EnablePrintCommand", typeof(bool), typeof(VisualPrinter), new FrameworkPropertyMetadata(false, OnEnablePrintCommandChanged));

    private static void OnEnablePrintCommandChanged(DependencyObject aDependencyObject, DependencyPropertyChangedEventArgs aArgs)
    {
        var newValue = (bool)aArgs.NewValue;
        var element = aDependencyObject as UIElement;
        if(newValue)
        {
            element.CommandBindings.Add(new CommandBinding(PrintVisualCommand, OnPrintVisual));
        }
    }

    private static void OnPrintVisual(object aSender, ExecutedRoutedEventArgs aE)
    {
        // the element is the one were you set the EnablePrintCommand
        var element = aSender as Visual;
        var printDlg = new PrintDialog();
        // do the printing
    }

    #endregion
}

这里我们定义了两个附加属性。PrintCommand用于将实际打印命令注入到视图模型中,这必须通过 OneWayToSource 完成。第二个EnablePrintCommand是启用打印,设置应该打印哪个元素并注册命令绑定。

我当前的版本有一个缺陷,你不能在同一个元素上设置两个属性,但这很容易克服。所以要打印一个按钮,它看起来像这样:

<Grid local:VisualPrinter.EnablePrintCommand="True">
    <Button Content="Test" local:VisualPrinter.PrintCommand="{Binding ViewModelPrint, Mode=OneWayToSource">
</Grid>

WhileViewModelPrint是视图模型中 ICommand 类型的属性,可以执行然后打印网格(因此是按钮)。

于 2013-04-08T11:15:14.193 回答