Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print WPF Visuals with MVVM pattern

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.");
like image 411
Elisabeth Avatar asked Apr 14 '26 05:04

Elisabeth


1 Answers

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.

The 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>

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." );
                } );
            }
        }
    }
}
like image 124
bstoney Avatar answered Apr 19 '26 10:04

bstoney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!