Sunday, May 30, 2010

WPF Tutorial : Beginning to Layout, Content, Transformation

Hi guys,

As expected, I have to write the next part of the WPF tutorial Series. The article is all about Window, NavigationWindow, Controls, Panels, Canvas, InkCanvas, RenderTransformation and many more. I hope you all would like the article.

A Look on Window


While building your application, the first thing you notice is a Window. Window is the main class that interact with the user and produces the lifetime of windows and dialog boxes. Like in normal windows application, it produces the object windows using the normal API. A window has two sections.

  1. Non-Client Area : which displays the outer boundary of the window, that we normally see with any windows. The main parts of them are Icon, System Menu, a title Bar and Border.
  2. Client part : This is the main part where the WPF controls will appear. You can customize this area using WPF.

Types of Window


WPF window is of 3 types.
  1. Window : This is basically a normal windowed application, where every controls are placed within the same window. The window appears normally as I told you earlier. The Client area are fully customizable using XAML.
  2. NavigationWindow : This is a special type of window which is inherited from Windows but with a Navigation panel top of it. So if you want to create an application that makes sense when used as Wizards, you might better go with NavigationWindow.  You can also customize the navigation panel yourself so that it goes with your own look and feel.
  3. Page : Almost similar to NavigationWindow, the main difference is that, Page can be opened in Web Browser as XBAP applications. 




Read the whole Article

Download the Sample Application

Saturday, May 29, 2010

Strange UserControl Issue (Struck with the easiest)

Hi Guys,

Today I am going to discuss about one of the most silly issue that I faced very recently. Its all about building a Composite UserControl using WPF. Let me discuss how I build the control.

Introduction

TextCalc is a control that takes numeric input from the user. Traditionally, we use TextBox to do this, but here I have implemented one control that allows you to choose numeric digits to input into the control. I will not discuss on the actual implementation of the control; which is fairly simple;  rather I emphasis here only on the problem I have faced while creating the control.

The Implementation

The TxtCalc control has few components :

  1. Border : This element wraps around all the controls inside it. I have created this just to ensure that the control has a firm border around the controls inside it. 
  2. TextBox : This is the main textbox, where the contents will be put and the data bound to this control will primarily be displayed over this TextBox. 
  3. ToggleButton : The ToggleButton is used to display the calculator. Just like what ComboBox has, it opens up a Popup below it and displays the Calculator UI.
  4. Popup : This control holds the UI for the calculator. Calculator holds a number of buttons from 0 to 9 and few calculation buttons etc.
Let us see how the code looks like (I intentionally removed the code of all the buttons, you will find in the demo application )  :

<usercontrol loaded="UserControl_Loaded" 
x:class="TextCalc.txtCalc" x:name="txtCalculator" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <border horizontalalignment="Stretch" x:name="brdCalculator">
        <grid>
            <grid.columndefinitions>
                <columndefinition width="*">
                <columndefinition width="Auto">
            </columndefinition>
            <textbox borderthickness="0" 
horizontalalignment="Stretch" 
text="{Binding ElementName=txtCalculator, Path=Message, Mode=TwoWay}" textalignment="Right" x:name="txtObj">
            <togglebutton click="ToggleButton_Click" 
grid.column="1" 
ischecked="{Binding ElementName=pupCalculator,Path=IsOpen}" name="btnDropdown" template="{Binding ElementName=txtCalculator, Path=CalculatorComboButton}"></togglebutton>
            <popup allowstransparency="True" horizontaloffset="-5" placement="Bottom" 
PlacementTarget="{Binding ElementName=txtObj}" staysopen="False" verticaloffset="10" x:name="pupCalculator">
                <border>
                    <grid background="Transparent" cliptobounds="True" margin="1">
</grid>
                </border>
            </popup>
        </textbox>
    </columndefinition>
</grid.columndefinitions>
</grid></border></usercontrol>

From the above code you can see I have created a textbox, which is bound to a property Message. There is a popup which displays the calendar, which is opened whenever the Toggle Button is opened.  All these is wrapped around using a Border.

In the code Behind I have created a Dependancy property MessageProperty and associated with my control txtCalc. A wrapper property is also created which allows you to call the property whenever Source value is modified. The code page looks like :

public readonly static DependencyProperty MessageProperty = 
DependencyProperty.Register("Message", typeof(string), typeof(txtCalc), new UIPropertyMetadata("0"));
  public string Message
        {
            get { return this.GetValue(MessageProperty) as string; }
            set
            {
                string oldValue = this.Message;
                this.SetValue(MessageProperty, value);
                this.OnPropertyChanged(new 
DependencyPropertyChangedEventArgs(MessageProperty, oldValue, value));
            }
        }
private static void PropertyChangedCallback(DependencyObject obj, 
DependencyPropertyChangedEventArgs args)
        {
            txtCalc tcalc = obj as txtCalc;
            tcalc.txtObj.Text = tcalc.Message;
            if (tcalc != null)
                tcalc.OnPropertyChanged("Message");
        }


Conclusion

Everything looks fairly simple but as I said, it was not working for me. The problem here is Binding generally defaults to TwoWay for any control. But in case of UserControl when I use the my custom binding statements, it is essential to explicitely define the Binding Mode to TwoWay, otherwise, it defaults to OneTime.

So the Culprit here with my implementation is :
Text="{Binding ElementName=txtCalculator, Path=Message, Mode=TwoWay}"

Here if you forget to mention the Mode=TwoWay, the binding will not be proper. And hence any changes will not be notified to the Observer when used with collection.

So I have solved the issue just by mentioning {Binding Mode=TwoWay}. Pity on me. :)

You can try out the sample application from :
TextCalc.zip (80 KB)

Thank you for reading.

Thursday, May 27, 2010

Article Selected @WindowsClient.net

Guys,

I am very happy to see another article being selected as Article of the Day in www.windowsclient.net the official website of Microsoft.

Please take a look at the article, I hope you will like it.

http://www.dotnetfunda.com/articles/article882-wpf-tutorial--a-beginning--1-.aspx

This is the beginning series of the article. I am writing the 2nd part, will be published soon.

Thanks to DotNetFunda.com and all my readers.

Saturday, May 22, 2010

Creating Splash Screen (Without Code)

Creating splash screen is very important for every good windows application. We work so hard while creating a beautiful splash screen. WPF introduces a very simple and easy approach to create a splash screen with lightening speed. Lets see how you can create one.

Why you need Splash Screen (Cold Start & Warm Start)?

This is very important to know why you need splash screen. Basically when WPF window loads for the first time, which is basically called as Cold Start; the WPF framework needs to load pages required such as code, static data, registry etc. Those are not present in memory whenever the application framework loads after reboot. So, user will find at least 4 seconds are required to load the window for the first time. This is very annoying on the part of the user. User might double click on the window for more than once just after seeing the delay of load. This delay will not occur for the next time onwards when all the necessary framework elements are already loaded into memory, popularly known as Warm start.

So it is very essential to load a splash screen, so that user will see that the application has already started loading.

How to create Splash Screen ?

Splash screen should be created using Unmanaged Code. This is very important. We create splash screen to give the user an indication that the application has started loading.  So if we do this using WPF code, there will be a delay in loading the splash screen as well, which is not what we needed.

Steps to create SPLASH SCREEN : 


  1. Create your own WPF application. 
  2. Create an image which you want to display when the application loads up.
    You must remember, creating splash screen this way will make the splash screen static. That means you cannot interact with the splash screen in this way. I will discuss a better way to create splash screen later.
  3. Add a the image in to your application. 
  4. Select the Image and from properties window choose Build action as Splash Screen as shown in the figure.


  5. You are done. You can now run your application, and you will see the splash screen to appear before the application loads up.

This is the easiest approach of creating a splash screen. The image will be loaded using GDI unmanaged code before the WPF framework modules are fully loaded.  So you can see this only when the application is loading. Once the Application is successfully run, the Splash screen will automatically disposed.

Download the source code from here.

Thank you for reading.

    Wednesday, May 19, 2010

    Design Patterns in C#

    As I am doing a lot of architecture stuffs, lets discuss the very basics of designing a good architecture. To begin with this, you must start with Design patterns.

    What is Design Patterns ?

    Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. In other words, Design patterns, say you have found a problem. Certainly, with the evolution of software industry, most of the others might have faced the same problem once. Design pattern shows you the best possible way to solve the recurring problem.

    Uses of Design Patterns

    While creating an application, we think a lot on how the software will behave in the long run. It is very hard to predict how the architecture will work for the application when the actual application is built completely. There might issues which you cant predict and may come while implementing the software. Design patterns helps you to find tested proven design paradigm. Following design pattern will prevent major issues to come in future and also helps the other architects to easily understand your code.

    History of Design Patterns

    When the word design pattern comes into mind, the first thing that one may think is the classical book on Design Pattern "Gangs of Four" which was published by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. In this book, it is first discussed capabilities and pitfalls of Object oriented programming, and later on it discusses about the classic Design Patterns on OOPS.

    Types of Design Pattern

    Design patterns can be divided into 3 categories.
    1. Creational Patterns : These patterns deals mainly with creation of objects and classes.
    2. Structural Patterns : These patterns deals with Class and Object Composition.
    3. Behavioural Patterns : These mainly deals with Class - Object communication. That means they are concerned with the communication between class and objects.
    In this article, I am going to discuss few examples of these patterns.

    You can Read the entire article from
    http://www.dotnetfunda.com/articles/article889-design-pattern-implementation-using-csharp-.aspx

    or

    Monday, May 17, 2010

    Object Notifiers using INotifyPropertyChanged, INotifyCollectionChanged

    Object Notifiers are very useful for any language. We declare classes which might be used by other processes. Now whenever any changes of the object needs to notify the external world, Microsoft introduced a new Technique in doing so. In this article I have discussed how you can implement your own class which would notify the external world whenever certain modification of the object is made.

    Observer Patter deals with the technique where the objects modified into the collection should notify the external entity.In this article I have also provided the basics on how you can implement your own Observer rather than using the already existing ObservableCollection, an MS implementation of Observer.

    Introduction


    Classes are the building blocks for any programming language. Even though we use class to define our custom business logic and apply them, but the most important utility of a class is to store data blocks within the object itself. C# classes are capable of storing data using fields, but they produced one step more abstraction level by introducing the Property System.  Properties are elements that are defined to wrap data members.  Thus anything that we need to expose through the object should be wrapped around using these properties. As a rule we don’t expose any fields as public for a class, rather we create a property and expose that to the outside world, so that the developers can easily impose one level of abstraction by not exposing the actual data.

    You can read the entire article from
    http://www.dotnetfunda.com/articles/article886-change-notification-for-objects-and-collections-.aspx


    Wednesday, May 12, 2010

    New WPF Learning Series

    Hi Guys,

    After writing so much about WPF, I have just began writing a very basic Beginners series of Articles that will help you out in learning WPF which is the future of Widnows programming as of now.

    The Articles published as of now are listed below:

    WPF Tutorial - A Beginning : 1
    WPF Tutorial - Layout-Panels-Containers & Layout Transformation 2
    WPF Tutorial : Fun with Border & Brush 3
    WPF Tutorial - TypeConverter & Markup Extension 4
    WPF Tutorial - Dependency Property 5
    WPF Tutoriall - Concept Binding 6
    WPF Tutorial - Styles, Triggers & Animation

    I am hoping you will like this series. Keep posting your feedback.

    Thank you.

    Saturday, May 8, 2010

    How to escape {} in XAML

    Escape sequences are very important part for any programming language. XAML which is been widely used nowadays in form of Silverlight and WPF, has some literals that are of special meaning. While working with XAML, you often need those special characters to be treated as literals.

    In case of XAML { --- } is treated as a markup extension. While parsing the XAML, the renderer finds { --- } and try to create an instance of an object just between the Curl braces. The object should be a markup extension. Thus if you want to use the braces like {Anything} as the content of a textbox, it will just strip the curl braces leaving only Anything.

    This is where you need Markup extension.

    <textblock text="this is {my} name">

    This will produce the output as "this is my name" (with no braces around my. To solve this issue, WPF has escape sequence.

    While WPF renders the output, it tries to find "{" (curl bracket) to declare the Markup extension. Now when the opening curl bracket is found, XAML checkes the very next character to see if this is an escape sequence or not. If the markup has "{}" (without anything inside curl braces), it will treat it as an escape sequence. Thus to escape the curl bracket you need to put "{}" just before putting the actual content. So the above textblock could be changed as :
    <textblock text="{}this is {my} name">

    and the output will be "this is {my} name".

    Author's new book

    Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
    Grab it now !!!