使用MVVM模式打印WPF视觉 [英] Print WPF Visuals with MVVM pattern
问题描述
我的ViewModel有一个PrintCommand执行一个名为PrintCalendar()的方法。但是日历又名datagrid在View中,那么如何让我的datagrid进入ViewModel?
My ViewModel has a PrintCommand executing a Method called PrintCalendar(). But the Calendar aka datagrid is in the View, so how do I get my datagrid into the ViewModel?
让我的手变脏,做代码隐藏的所有东西?哦不...
Getting my hands dirty and do all that stuff in code-behind? oh no...
PrintDialog printDlg = new PrintDialog();
printDlg.PrintVisual(datagrid, "Grid Printing.");
推荐答案
你可以尝试这个。我已经设置了一个简单的演示窗口,包含一个datagrid,一个buttom和一个ViewModel。 ViewModel包含PrintCommand(来自 MVVM Light Toolkit 的RelayCommand),它接受Visual( datagrid)作为命令参数。代码背后没有代码,所有的工作都是通过绑定完成的。
You could try this. I have set up a simple demo window with a datagrid, a buttom and a ViewModel. The ViewModel contains the PrintCommand (a RelayCommand from the MVVM Light Toolkit) which accepts a Visual (the datagrid) as the command parameter. There is no code in the code behind all the work is done via binding.
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:
and the 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模式打印WPF视觉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!