我的ViewModel有一个PrintCommand执行一个名为PrintCalendar()的方法。但Calendar aka datagrid在View中,那么如何将我的datagrid放入ViewModel?
弄脏我的手并在代码隐藏中做所有这些事情?哦不...
PrintDialog printDlg = new PrintDialog();
printDlg.PrintVisual(datagrid, "Grid Printing.");
答案 0 :(得分:7)
你可以试试这个。我已经设置了一个带有datagrid,buttom和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." );
} );
}
}
}
}