Code Simplified – Viral Sarvaiya

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

Posts Tagged ‘Windows Presentation Foundation’

Print dynamically generated controls in WPF

Posted by Viral Sarvaiya on May 19, 2011


Hi

From my previous post https://viralsarvaiya.wordpress.com/2011/05/17/printing-in-wpf-with-fit-to-printing-page 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;
grid.ColumnDefinitions.Add(coldef);

RowDefinition rowdef = new RowDefinition();
rowdef.Height = GridLength.Auto;
grid.RowDefinitions.Add(rowdef);
}

// 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.Children.Add(btn);
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


Hi,
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.Measure(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");
}
}

thanks
Enjoy….

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

Linkbutton in WPF

Posted by Viral Sarvaiya on May 13, 2011


hello,

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 asp.net 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">
<Button.Template>
<ControlTemplate TargetType="Button">
<TextBlock TextDecorations="Underline">
<ContentPresenter />
</TextBlock>
</ControlTemplate>
</Button.Template>
<Button.Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>

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,

http://msdn.microsoft.com/en-us/library/ms752337.aspx

http://msdn.microsoft.com/en-us/library/ms788718.aspx

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="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

</ResourceDictionary>

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="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">

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

</ResourceDictionary>

Now add another resource directory for French language named “StringResource.fr-CA.xaml”

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

so StringResource.fr-CA.xaml as below.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">

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

</ResourceDictionary>

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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Beige" >
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>

<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" />
</Grid>
</Window>

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()
{
InitializeComponent();
SetLanguageDictionary();
}

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

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()
return;
}
if (txtpass.Password.Trim() == "")
{
MessageBox.Show("Please Enter Password");
return;
}
if (txtuser.Text.Trim() == txtpass.Password.Trim())
{
MessageBox.Show("Sucess");
}

}

private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}

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

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

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.

Enjoy…..

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

Introduction to Windows Presentation Foundation

Posted by Viral Sarvaiya on July 27, 2009


Overview

The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

The following illustration gives you an overview of the main new features of WPF

Separation of Appearance and Behavior

WPF separates the appearance of an user interface from its behavior. The appearance is generally specified in the Extensible Application Markup Language (XAML), the behavior is implemented in a managed programming language like C# or Visual Basic. The two parts are tied together by databinding, events and commands. The separation of appearance and behavior brings the following benefits:

  • Appearance and behaviour are loosely coupled
  • Designers and developers can work on separate models.
  • Graphical design tools can work on simple XML documents instead of parsing code.

Rich composition

Controls in WPF are extremely composable. You can define almost any type of controls as content of another. Although these flexibility sounds horrible to designers, its a very powerful feature if you use it appropriate. Put an image into a button to create an image button, or put a list of videos into a combobox to choose a video file.

 
<Button>
    <StackPanel Orientation="Horizontal">
        <Image Source="speaker.png" Stretch="Uniform"/>
        <TextBlock Text="Play Sound" />
    </StackPanel>
</Button>

Highly customizable

Because of the strict separation of appearance and behavior you can easily change the look of a control. The concept of styles let you skin controls almost like CSS in HTML. Templates let you replace the entire appearance of a control.

The following example shows an default WPF button and a customized button.

Resolution independence

All measures in WPF are logical units – not pixels. A logical unit is a 1/96 of an inch. If you increase the resolution of your screen, the user interface stays the same size – if just gets crispier. Since WPF builds on a vector based rendering engine its incredibly easy to build scaleable user interfaces.

How to create a simple WPF application

In Visual Studio 2008

Open Visual Studio 2008 and choose “File”, “New”, “Project…” in the main menu. Choose “WPF Application” as project type.

Choose a folder for your project and give it a name. Then press “OK”

Visual Studio creates the project and automatically adds some files to the solution. A Window1.xaml and an App.xaml. The structure looks quite similar to WinForms, except that the Window1.designer.cs file is no longer code but it’s now declared in XAML as Window1.xaml

Open the Window1.xaml file in the WPF designer and drag a Button and a TextBox from the toolbox to the Window

Select the Button and switch to the event view in the properties window (click on the little yellow lightning icon). Doubleclick on the “Click” event to create a method in the codebehind that is called, when the user clicks on the button.

Note: If you do not find a yellow lightning icon, you need to install the Service Pack 1 for VisualStudio on your machine. Alternatively you can doubleclick on the button in the designer to achieve the same result.

Visual Studio automatically creates a method in the code-behind file that gets called when the button is clicked.

 
private void button1_Click(object sender, RoutedEventArgs e)
{
    textBox1.Text = "Hello WPF!";
}

The textbox has automatically become assigned the name textBox1 by the WPF designer. Set text Text to “Hello WPF!” when the button gets clicked and we are done!. Start the application by hit [F5] on your keyboard.

Isn’t this cool!

Learn PWF click here

Posted in ASP.NET | Tagged: , | Leave a Comment »

 
%d bloggers like this: