Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for May, 2011

Print dynamically generated controls in WPF

Posted by Viral Sarvaiya on May 19, 2011


From my previous post we see how to print page with wpf and with fit to printing page,

But what if we want to print dynamically generated control?

Because printdialog’s PrintVisual method print only visual controls.

Here I demonstrate that how to print controls that dynamically generated.

void PrintOnClick(object sender, RoutedEventArgs args)
PrintDialog dlg = new PrintDialog();
if ((bool)dlg.ShowDialog().GetValueOrDefault())
// Create Grid panel.
Grid grid = new Grid();
// Define 5 auto-sized rows and columns.
for (int i = 0; i < 5; i++)
ColumnDefinition coldef = new ColumnDefinition();
coldef.Width = GridLength.Auto;

RowDefinition rowdef = new RowDefinition();
rowdef.Height = GridLength.Auto;

// Give the Grid a gradient brush.
grid.Background = new LinearGradientBrush(Colors.Black, Colors.White, new Point(0, 0), new Point(1, 1));
// Every program needs some randomness.
Random rand = new Random();

// Fill the Grid with 25 buttons.
for (int i = 0; i < 25; i++)
Button btn = new Button();
btn.FontSize = 12 + rand.Next(8);
btn.Content = "Button No. " + (i + 1);
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.VerticalAlignment = VerticalAlignment.Center;
btn.Margin = new Thickness(6);
Grid.SetRow(btn, i % 5);
Grid.SetColumn(btn, i / 5);

// Size the Grid.
grid.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));

Size sizeGrid = grid.DesiredSize;

// Determine point for centering Grid on page.
Point ptGrid =  new Point((dlg.PrintableAreaWidth - sizeGrid.Width) / 2, (dlg.PrintableAreaHeight - sizeGrid.Height) / 2);

// Layout pass.
grid.Arrange(new Rect(ptGrid, sizeGrid));
// Now print it.
dlg.PrintVisual(grid, Title);

thanks and enjoy coding…


Posted in .Net, WPF | Tagged: , , , , | Leave a Comment »

Printing in WPF with fit to printing page.

Posted by Viral Sarvaiya on May 17, 2011

Here is the code for the print in WPF.

It is very simple to print a page in comparison with normal window application. Just make a object of the PrintDialog Class and just call function PrintVisual as below

PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
if (printDlg.ShowDialog() == true)
printDlg.PrintVisual(this, "First WPF Print");

This code will print the page. That will take automatically margin to the printing page

What if you want to print page with fit to the printing page?

Here are the steps to print page with fit to printing page.

Step 1: Add the reference of the ReachFramework.dll
Step 2: Add the reference of the System.Printing.dll
Step 3: Get selected Printer’s capability
Step 4: calculate scale of the printer
Step 5: Get printable area of Paper.
Step 6: Update visual layout
Step 7: Print Visual
Here is the code for the above procedure

private void btnPrint_Click(object sender, RoutedEventArgs e)
PrintDialog Objprint = new System.Windows.Controls.PrintDialog();
if (Objprint.ShowDialog() == true)
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities = Objprint.PrintQueue.GetPrintCapabilities(Objprint.PrintTicket);

//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / this.ActualWidth, capabilities.PageImageableArea.ExtentHeight / this.ActualHeight);

//Transform the Visual to scale
this.LayoutTransform = new ScaleTransform(scale, scale);

//get the size of the printer page
Size size = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);

//update the layout of the visual to the printer page size.
this.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), size));

//now print the visual to printer to fit on the one page.
Objprint.PrintVisual(this, "Print in WPF with fit to printing page");


Posted in .Net, WPF | Tagged: , , , | 2 Comments »

Calling a WCF service from Javascript

Posted by Viral Sarvaiya on May 16, 2011


we know how to use WCF service in silverlight and that shows in my some previous posts

but i face another problem in it, it can possible to call WCF service from javascipt?

Answer is yes  and i find interesting post.

for more detail click here.

thanks and enjoy…

Posted in .Net, ASP.NET, RIA WCF, Silverlight, WCF Services | Tagged: , , , , , , , | Leave a Comment »

Linkbutton in WPF

Posted by Viral Sarvaiya on May 13, 2011


Today i learn new thing from my current project,

i have to use the linkbutton in wpf, there are no control like linkbutton as like control in wpf

we can use the button and set style as like link button…

here is the xaml code for set button as a linkbutton.

<Button Margin="5" Content="Test" Cursor="Hand" Name="BtnTest" Click="BtnTest_Click">
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline">
<ContentPresenter />
<Style TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Red" />

now u can see the button is look like a link button

Enjoy coding…

Posted in .Net, ASP.NET, WPF | Tagged: , , , | 2 Comments »

Multilanguage Application in WPF

Posted by Viral Sarvaiya on May 7, 2011

From this 2 link we can get batter idea of Globalization and Localization,

Here i demostrate very simple way for multiple language application in WPF.

here i make a simple login form in wpf with 2 language English and French Button.
Step 1:  Open Visual studion, Create New Project of WPF give name “WPFMultiLanguage”.

so now you have 2 .xaml file App.xaml and MainWindow.xaml,

Step 2: New we add new folder named “Resources” for Multiple Language.

Step 3: Add resource files

To add resource file named “StringResources.xaml”, right click to Resource folder => Add => Resource Directory (See Image below)

So your file is as like

<ResourceDictionary xmlns=""
xmlns:x="" >


I have added one namespace which points to mscorlib, and named it as system and now add resource string to StringResources.xaml

so StringResources.xaml as below

<ResourceDictionary xmlns=""

<system:String x:Key="Username">Username</system:String>
<system:String x:Key="Password">Password</system:String>
<system:String x:Key="close">close</system:String>
<system:String x:Key="login">login</system:String>
<system:String x:Key="French">French</system:String>
<system:String x:Key="English">English</system:String>


Now add another resource directory for French language named “”

put there French string resuouce and give same key name as per above file,

so as below.

<ResourceDictionary xmlns=""

<system:String x:Key="Username">Nom d'utilisateur</system:String>
<system:String x:Key="Password">Mot de passe</system:String>
<system:String x:Key="close">Fermer</system:String>
<system:String x:Key="login">connexion</system:String>
<system:String x:Key="French">Française</system:String>
<system:String x:Key="English">En anglais</system:String>


Step 4: Add Resource file to window.

Now its time to add resource file to Mainwindow page.

for that in the MainWindow.xaml file design the login page and put 2 button for the language transfer.

For display content and text from resource file, use DynamicResource.

for that i have made 1 function that add dictionaries directly to window resources and in click event of the button for language transfer i set culture for that.

so MainWindow.xaml as below.

<Window x:Class="WPFMultiLanguage.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Beige" >

<TextBlock Name="Username" Text="{DynamicResource Username}" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,24,18,38"></TextBlock>
<TextBox Name="txtuser" Width="100" Height="30" Grid.Column="1" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Left"></TextBox>
<TextBlock Name="Password" Text="{DynamicResource Password}" Grid.Column="0" Margin="0,24,18,38" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right"></TextBlock>
<PasswordBox Name="txtpass" Width="100" Height="30" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Center" />

<Button x:Name="btnLogin" Width="100" Height="40" VerticalAlignment="Top" HorizontalAlignment="Right"
Click="btnLogin_Click" Content="{DynamicResource login}" Grid.Row="2" Grid.Column="0" Padding="10" />
<Button x:Name="btnClose" Width="100" Height="40" VerticalAlignment="Top" HorizontalAlignment="Left"
Click="btnClose_Click" Content="{DynamicResource close}" Grid.Row="2" Grid.Column="1" Padding="10" />

<Button x:Name="btnEnglish" Width="100" Height="40" VerticalAlignment="Bottom" HorizontalAlignment="Right"
Click="btnEnglish_Click" Content="{DynamicResource English}" Grid.Row="3" Grid.Column="0" Padding="10" />

<Button x:Name="btnFrench" Width="100" Height="40" VerticalAlignment="Bottom" HorizontalAlignment="Left"
Click="btnFrench_Click" Content="{DynamicResource French}" Grid.Row="3" Grid.Column="1" Padding="10" />

and MainWindow.xaml.cs as below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Threading;
namespace WPFMultiLanguage
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
public MainWindow()

private void SetLanguageDictionary()
ResourceDictionary dict = new ResourceDictionary();
switch (Thread.CurrentThread.CurrentCulture.ToString())
case "en-US":
dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);
case "fr-CA":
dict.Source = new Uri("..\\Resources\\", UriKind.Relative);
dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);

private void btnLogin_Click(object sender, RoutedEventArgs e)
if (txtuser.Text.Trim() == "")
MessageBox.Show("Please Enter Username");
//If u want to set resource from code behind then use below code
//FindResource("<Resource Key Name>").ToString()
if (txtpass.Password.Trim() == "")
MessageBox.Show("Please Enter Password");
if (txtuser.Text.Trim() == txtpass.Password.Trim())


private void btnClose_Click(object sender, RoutedEventArgs e)

private void btnEnglish_Click(object sender, RoutedEventArgs e)
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = cultureInfo;

private void btnFrench_Click(object sender, RoutedEventArgs e)
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture = cultureInfo;

Now run the solution

english is by default so first time when you run code it display in english language
and then click to French button it display in French.


Posted in .Net, Silverlight, Visual Studio, WPF | Tagged: , , , , , | 4 Comments »

%d bloggers like this: