Posts tagged Basic of WPF

howto

Dock Fill a control in parent control

0

In Win form , we used to have a Dock.Fill option for controls to stretch it with in parent control.But in WPF it is quite different.So this quick post will demonstrate ,how to fill a control inside a parent control.Suppose we want to dock fill a Button inside a layout.Lets create a button inside the layout. (more…)

WPF

Layout and Controls in WPF

0

Half of the battle can be won through UI and Control placement in software paradigm .All of us know the a good UI leaves extraordinary impact on user so this post is all about control placing and control layout in WPF.In this post we will cover following topics.

  1. Layout
  2. Classic Controls
Layout

Layout in WPF are versatile than win form controls.In Win form most of the frequently used layouts used the coordinate based control placement while in WPF it is slot based depending on the screen space.the most common used layouts in wpf are as follows :

  • Canvas
  • Used Coordinate based Control Layout (Same as panel in normal Win Form)
  • Stack Layout
  • Control are placed horizontally / Vertically one above the other
  • Wrap Layout
  • Controls are  placed sequentially horizontally / vertically
  • Grid Layout
  • Creates column,Row based grid and each cell allows controls to be placed
  • Dock Panel
  • Docks the control on specified area

    A collected sample of all can be seen bellow

     image

    More details can be found http://msdn.microsoft.com/en-us/library/ms745058.aspx.

    Classic Controls

    The control set in WPF is rich with wide support for data binding .A full comparison of WPF and winform control can be found from here.

    image

    Additional Link for Controls

    http://www.simple-talk.com/content/file.ashx?file=3354

    http://www.simple-talk.com/dotnet/.net-framework/from-winform-to-wpf-a-quick-reference-guide/

    WPF

    Routed Event in WPF – Introduction

    7

    Till date we were acquainted with normal event which are basics of Win Form Applications.WPF introduces a new concept called as Routed Event .So here we will have a brief intro for this new feature and comparison between CLR Events and Routed Events.We will not start with definition , instead we will go back to old methods of CLR event and try to achieve something funny but logically meaningful.

    Track Mouse Challenge (My niece 6 yrs old was tester , Still i failed  )

    So a very simple logic , Whenever the mouse moves with in the panel the Status Label should display as “With in Panel” or else “Outside Panel”.So what we need to do is ,track it with Mouse Move and Mouse Leave events .The logic and code follows as bellow.

    SNAGHTML1cffb48

    Code Snippet
    1. private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
    2. {
    3. pnlContainer.BackColor = Color.Red;
    4. lblMouseLocation.Text= “With in Panel”;
    5. }
    6. private void pnlContainer_MouseLeave(object sender, EventArgs e)
    7. {
    8. pnlContainer.BackColor = Color.Cyan;
    9. lblMouseLocation.Text = “Ouside Panel”;
    10. }

    Very Simple .Lets Run.But the results are not as of requirement .So

    My Niece’s Bug Report

    When Ever the Mouse moves over the Black Board (Image Control) , status (Label Control) shows Outside Panel “ and that too logged on High Priority mode :) .image Logically it should not happen .To patch it up in the end i attached event handler to the Image control .But suppose the panel contains more than one image or controls then how pathetic it will be to attach event to all .

    Year 2010 , I tried to implement same logic with WPF and it surprised me.

    Track Mouse Challenge  , in WPF

    Now with WPF i emulate the same logic as in my previous WinForm application and it worked .
    image and the code followed exactly same as above.

    Code Snippet
    1. private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
    2. {
    3. pnlContainer.Background = Brushes.Red;
    4. lblMouseLocation.Content = “With in Panel”;
    5. }
    6. private void pnlContainer_MouseLeave(object sender, MouseEventArgs e)
    7. {
    8. pnlContainer.Background = Brushes.Cyan;
    9. lblMouseLocation.Content  = “With in Panel”;
    10. }

    e

    Download the compiled programs and Check it.

    Track Mouse Program (Simple WithOut WPF) Download
    Track Mouse Program (Simple in WPF) Download

    This is exactly where WPF introduces you to Routed Event.

    What Is Routed Events

    Routed events are the events that travel through the parent/ Child container of a control with raising  their events .The movement logic known as Routing Strategy (We will Digg into it in my next posts).

    So events can also be captured at parent or child container instead of the particular control which invokes it.

    Scenario Of Use

    I know you will not agree with the scenario as mentioned above .

    So some practical usage ,Consider a case of a normal calculator which contains 10 Numeric Button and Logical Operations .It is normal to write behind each control event , but what about code readability and scattered logic.Why should not we write a common logic part behind the parent container.

    Another simple usage is YEs,No,Cancel button used in all our form.image I can handle events of buttons in the container Boarder.

    Technical Difference From CLR Events

    WPF UI is a composite architecture based  , means a control can be consists of several other controls or resource .Lets have a look at the document outline of the TrackMouse application.The Border (Resembles to Panel in Winform) contains the image control element. image The events are also followed as of the VisualTree above .The events of Image Element can be handled at its parent element Border.In Mouse Track program , Mouse Move of Image is a Routed event which invokes the parent Border Mouse move event also.Try to debug the code .

    image I know the Technical details are not sufficient and the scope of the particular post doesn’t allow it .In my next posts i will cover the Routing Events and Routing Strategy in depth.

    Code for this Article -Routed Event Intro Download

    That’s it for now , i hope you liked my niece’s intelligence :) .

    WPF

    Event Handling in WPF

    0

    Events in WPF works same as in Win Form application except some new concept such as  Routed Event  ( I will blog it in next post).So directly we can jump to the code to add simple events to application as well as Window(Forms in WPF are called as Window ,for XBAP it called as Page).

    There are 2 ways of adding events

    1. Declarative Way ( XAML Approach )
    2. Code Way (Conventional as in Win form / Code Approach)

    So consider  the scenario bellow and the way to do it in both ways

    Scenario 1 –: On Start of our Application we will show the application details.

    Through XAML

    As we should on load of application the event must be declared in the app.XAML or app.xaml.cs.Write the the event name we want to invoke , the intellisense will prompt as follows

    www.manaspatnaik.com/blog Once you click image , it will add a handler to the app.xaml.cs .And there we will have the application information.

    Basics What is  Event Handler ?
    Code Snippet
    1. /// Interaction logic for App.xaml
    2. /// </summary>
    3. public partial class App : Application
    4. {
    5. private void Application_Startup(object sender, StartupEventArgs e)
    6. {
    7. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
    8. ,“My First WPF Application”);
    9. }
    10. }

    Through CODE –:

    As the OnStartup is application related event we will override in the app.xaml.cs.

    image

    Code Snippet
    1. protected override void OnStartup(StartupEventArgs e)
    2. {
    3. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
    4. , “My First WPF Application”);
    5. }

    Scenario 2 –: On Button Click display application information (Attaching a event to a method)

    Through XAML –:

    First we will create a EventHandaler in the the window , as bellow .

    Code Snippet
    1. public partial class MyFirstWindow : Window
    2. {
    3. public MyFirstWindow()
    4. {
    5. InitializeComponent();
    6. }
    7. private void ShowApplicationInfo(object sender,RoutedEventArgs e)
    8. {
    9. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
    10. ,“My First WPF Application”);
    11. }
    12. }

    Now we will attach the event to the button click in through xaml .

    image So the final Xaml code will look like this.

    Code Snippet
    1. <Grid>
    2. <Label>My First WPF Application</Label>
    3. <Button Content=”Show About” Height=”50″ HorizontalAlignment=”Left” Margin=”71,78,0,0″
    4. Name=”btnShowAbout” VerticalAlignment=”Top” Width=”143″
    5. Click=”ShowApplicationInfo”
    6. />
    7. </Grid>

    Through CODE–:

    Code way is same as previous we need to attach the event to the handler on load.

    image and the final code will be

    Code Snippet
    1. private void ShowApplicationInfo(object sender,RoutedEventArgs e)
    2. {
    3. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
    4. ,“My First WPF Application”);
    5. }
    6. private void Window_Loaded(object sender, RoutedEventArgs e)
    7. {
    8. btnShowAbout.Click += new RoutedEventHandler(ShowApplicationInfo);
    9. }

    That’s it .

    1285599500_package_edutainment_thumb.png

    Getting Into WPF

    1

    Learning a new programming platform is never easy until unless somebody is really inspired.WPF (Windows Presentation Foundation ) is  quite convincing if you look at its prospective and the capability it gives to user.This new graphical subsystem from Microsoft relies on Direct X for rendering instead of GDI.So the advantage this  declarative programming model is Resolution Independent provides extensive integration with independent technology (Text to speech , 3d animation ,video etc),Hardware acceleration with Direct 3d and most useful complete customization of controls.

    Wpf applications development  can be of two type

    • Windows Based Application
    • Browser Based Application (XBAP)
    1285599500_package_edutainment What is Declarative Programming ?

    This Blog post is about my experience with first WPF application , a simple application with basic understanding.

    Create a WPF Project :

    Open Visual Studio and Select WPF Application .Provide a Name “StartWithWpf” and click Ok .

    Create a WPF Project

    Have a look at the source folder , It contains a default MainWindows.xaml and App.xaml.So the XAML Markup drives WPF application with similar syntax of XML (Read More about XAML and Syntax) .A complied form of XAML is known as BAML.

    r.2625741350 App.Xaml
    • App.xaml is a class(Singleton Pattern) which encapsulate the application specific functionality and resource handling such as
      • Application Lifetime
      • Application Windows,property
      • Resource Management
      • Command Line Parameter
      • Navigation
    Digging Into APP.Xaml:

    The App.Xaml (Application class )is the entry point for the application .We can write as code behind application class or in the mark-up.The declarative Mark-up is must for XBAP.

    Code Snippet

    1. <Application
    2. xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    3. xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    4. x:Class=”StartWithWpf.App”
    5. StartupUri=”MainWindow.xaml”>
    6. </Application>

    So the app.xaml need above lines to run a project.These are the Attributes of Application .

    xmlns –:Defines the Namespace for the Application

    xmlns : x-:Defines the additional namespace for the application

    Basics of XAML Syntax

    Above both attributes direct to the specification required to be referenced for xaml.You can find out some additional references as you add your some custom namespaces.

    Custom Namespace in WPF

    Adding a Form:

    Now lets add a Form , here it is Windows (instead of Form as in WinApp).So adding a Window named “MyFirstWindow”.Add new WPF Window

    Now the look at the Window , we have added.

    Wpf Window

    I will change the Title property and add a label to the Grid Layout.(Layouts are very important in WPF ).

    Code Snippet
    1. <Window x:Class=”StartWithWpf.MyFirstWindow”
    2. xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    3. xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    4. Title=”Home” Height=”300″ Width=”300″
    5. >
    6. <Grid>
    7. <Label> My First WPF Application </Label>
    8. </Grid>
    9. </Window>

    Now to Run the application i will go to App.xaml and Change the StartUpUri attribute to “MyFirstWindow.xaml”.Lets run it and you are ready with your first WPF application.A simple but fair start  :) .

    Go to Top