【问题标题】:Print WPF Visuals with MVVM pattern使用 MVVM 模式打印 WPF 视觉效果
【发布时间】:2011-04-22 00:08:52
【问题描述】:

我的 ViewModel 有一个执行名为 PrintCalendar() 的方法的 PrintCommand。但是日历又名数据网格在视图中,那么如何将我的数据网格放入 ViewModel 中?

弄脏我的手并在代码隐藏中做所有这些事情?哦不...

PrintDialog printDlg = new PrintDialog();
printDlg.PrintVisual(datagrid, "Grid Printing.");

【问题讨论】:

    标签: mvvm printing datagrid


    【解决方案1】:

    你可以试试这个。我已经设置了一个简单的演示窗口,其中包含一个数据网格、一个按钮和一个 ViewModel。 ViewModel 包含 PrintCommand(来自MVVM Light Toolkit 的 RelayCommand),它接受 Visual(数据网格)作为命令参数。代码背后没有代码,所有工作都是通过绑定完成的。

    Xaml:

    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:WpfTestApplication.ViewModel"
        x:Class="WpfTestApplication.MainWindow"
        x:Name="Window"
        Title="MainWindow"
        Width="640" Height="480">
        <Window.Resources>
            <ResourceDictionary>
                <vm:WindowViewModel x:Key="WindowViewModel"/>
            </ResourceDictionary>
        </Window.Resources>
    
        <Grid x:Name="LayoutRoot" DataContext="{DynamicResource WindowViewModel}">
            <DockPanel>
                <Button Content="Print" Width="70" DockPanel.Dock="Bottom" HorizontalAlignment="Right"
                        Command="{Binding PrintCommand, Mode=OneWay}" CommandParameter="{Binding ElementName=dataGrid, Mode=OneWay}" />
                <DataGrid x:Name="dataGrid" DataContext="{DynamicResource SampleDataSource}" ItemsSource="{Binding Collection}"/>
            </DockPanel>
        </Grid>
    </Window>
    

    和 ViewModel:

    using System.Windows.Controls;
    using System.Windows.Media;
    using GalaSoft.MvvmLight.Command;
    
    namespace WpfTestApplication.ViewModel
    {
        public class WindowViewModel
        {
            /// <summary>
            /// Command executed to print an visual component. The component is passed in as a parameter.
            /// </summary>
            public RelayCommand<Visual> PrintCommand
            {
                get
                {
                    return new RelayCommand<Visual>( v =>
                    {
                        PrintDialog printDlg = new PrintDialog();
                        printDlg.PrintVisual( v, "Grid Printing." );
                    } );
                }
            }
        }
    }
    

    【讨论】:

    • 你在跟踪我吧? ;-) 当然你说的是对的。您只需将对象传递给 ViewModel。我的要求发生了变化,所以我必须在代码隐藏中做很多技术工作才能打印带有 datagrid + 富文本的页面。你知道如何打印一个由许多控件组成的页面吗?
    • 不是没有跟踪你,只是看到你有一个未回答的问题 :) 在一页上是什么意思?您的意思是使用来自 UI 不同部分的多个控件来组合打印输出吗?
    • 从技术上讲,这个例子打破了 MVVM 模式。通常,您希望避免在视图模型中使用 WPF 对象,例如 PrintDialog。但是,像这种需要使用 WPF 对话框控件并在其上调用方法的情况根本不适合 MVVM 模式,因此您必须在视图模型中选择线条之外的颜色或者只是在代码隐藏中使用这种东西
    猜你喜欢
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多