我的 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/