mvvm - 使用 MVVM 模式打印 WPF 视觉效果

标签 mvvm printing datagrid

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

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

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

最佳答案

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

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." );
                } );
            }
        }
    }
}

关于mvvm - 使用 MVVM 模式打印 WPF 视觉效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3875789/

相关文章:

database - 数据未插入数据库室 Android

extjs - 来自另一个 View 模型的链式存储源

android - 房间持久化库(依赖问题),MVVM设计模式

javascript - 如何在 AngularJS 中启用数据网格?

xml - 在 Silverlight 中将 XML 动态绑定(bind)到 DataGrid

c# - WPF 数据网格在不应该刷新时自行刷新

validation - 如何使用kendo验证器验证多封电子邮件?

html - 横向打印网页

javascript - 如何一键多次打印某内容?

java - LineBreakMeasurer 中没有堆栈跟踪的 ClassCastException