使用 MVVM 模式打印 WPF 视觉效果 [英] Print WPF Visuals with MVVM pattern
问题描述
我的 ViewModel 有一个 PrintCommand 执行一个名为 PrintCalendar() 的方法.但是日历又名数据网格在视图中,那么如何将我的数据网格放入 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.");
推荐答案
你可以试试这个.我已经设置了一个简单的演示窗口,其中包含一个数据网格、一个按钮和一个 ViewModel.ViewModel 包含 PrintCommand(来自 MVVM Light Toolkit 的 RelayCommand),它接受视觉(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>
和视图模型:
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屋!