WPF


6
Jun 09

StackPanel (Layout) in WPF

Like .Net 2.0, WPF provides a set of layouts that allows the users to easily place the controls in to it. Lets look in to it, one by one comparing with the net 2.0 version of it.

StackLayout

This was called as FlowLayout in .net 2. Controls that are added in to this layout will be automatically aligned either in a vertical or in a horizontal fashion. This alignment depends on the value of Orientaion property. The value can either be Vertical or Horizontal.

Vertical Orientation

    <StackPanel Orientation="Vertical">
        <Button Content="Button1" />
        <Button  Content="Button2" />
    </StackPanel>

Horizontal Orientation

    <StackPanel Orientation="Horizontal">
        <Button Content="Button1" />
        <Button  Content="Button2" />
    </StackPanel>

If you notice the screenshots, you will find that the width of the button is automatically controlled by the WPF framework. Thats why the buttons are stretched. But if you wanna control the width, you can play with the HorizontalAlignment property of the control. The default alignment is Stretched. Specifying a width for the control along with the HorizontalAlignment property allows you to have total control on the size and location of the control.

<StackPanel Orientation="Vertical">
  <Button Content="Button1" />
  <Button Content="Button2" HorizontalAlignment="Left" />
  <Button  Content="Button3" HorizontalAlignment="Right" />
  <Button  Content="Button4" HorizontalAlignment="Center" />
  <Button  Content="Button5" HorizontalAlignment="Stretch" />
</StackPanel>

We can see this layout in action in loads of places. For example, the search tool that comes with windows has employed this layout.

Although this layout lets the us relax on alignments, we cannot place two controls parallel to each other (this layout is not intented to do so. we have another layout for this, GridLayout). Also this layout cannot wrap controls when the controls overflow (again this layout is not intented to do so. we have another layout for this, WrapPanel).


24
May 09

Creating a single instance application in C#, WPF

Some time you might want the user to run only one instance of the application. Its pretty easy to do so in C#. This is acheived using a Mutex. A mutex is used to restrict the usage of common resources in concurrent proragmming. C# provides a class called System.Threading.Mutex with which we can control the number of instances of an application that should be running. Just add the following snippet to the App.xaml.cs file (code behind file of App.xaml)

class App : Application
{
private Mutex myMutex;
...
protected override void OnStartup(StartupEventArgs theArgs)
{
bool aIsNewInstance = false;
myMutex = new Mutex(true, "Foo.SingletonApp", out aIsNewInstance);  //Creates a mutex for the application
if(!aIsNewInstance)
{
App.Current.Shutdow();  //Shutdown when a new mutex with the same name is created
}
}
}

How this works

The creation of a mutex in here takes three parameters. First one is to give the ownership of this mutex to the calling thread. Second one is the unique name given for this mutex (remember this is a unique name). Third one is an out parameter that returns
true — if there are no mutex with this name and if the new mutex is successfully created
fase — if there is already a mutex with this name.
That why we check for !aIsNewInstance in the snippet. Here we override the Startup event of the Application class (refer to my previous post on Application Events) so that we can validate the mutex during the start of the application.


24
May 09

WPF Application creation, an insight — part2

Before I can start with part2, a small highlights from part1.

  • All the WPF applications are an object of System.Windows.Application running as a process
  • Visual Studio allows the users to relax from the creation and running of the System.Windows.Application object if you specify the BuildAction as Application Definition
  • Specifying the StartupUri attribute in the App.xaml with a window class allows the developer not to write snippets that will show the top level window

Accessing Application object from window classes

As soon as the Application object is created, it would be set to the Current property of itself. As this property is a static property, any window classes can access the instance of app that is running. Also the application object, as mentioned earlier, shall hold the instances of all the top level windows. So we can even access these top level window object from any class thru’ the Current.Windows property.

class Window1
{
public Window1()  //constructor
{
foreach(Window aTopLevelWindow in App.Current.Windows as Window)
{
MessageBox.Show(aTopLevelWindow.Title);
}
}
}

Shutting down the Application object

While running an Application object is done thru’ Run(), we can shut down the app thru’ Shutdown(). For example, if you want to provider a custom close button in your window, you can close the application (terminate the entire process) using the following snippet,

class Window1
{
...
public void ExplicitShutDown()  //Some method which will explicity shutdown the Application object
{
App.Current.Shutdown();  //Where App is the name of the Application class
}
}

This is called as an explicit shutdown.

Application Events

Here are some of the events of the Application object that can be of great use when you program.

  • Startup — Invoked after the Application object is created and run. You can show your top level windows in here
  • Activated and Deactivated — Invoked when one of the top level windows of the Application object is activated and deactivated will be called when another Application object’s top level window gets activated
  • Session Ending — Invoked when windows session ends either by a shutdown call or a restart call
  • Exit — Invoked when the Application.Shutdown() is called

Hope these two posts helped you in understanding how a WPF application gets instantiated. From my next post I will start writing about controls.


23
May 09

WPF Application creation, an insight — part 1

Creating a WPF application is really a piece of cake if you have Visual Studio with out. All you have to do is,

  • Start Visual Studio ( >= 2008)
  • Create New Project (project type, WPF Application)
  • Hurrah, we have a WPF application now. Go on, edit your Window1.xaml and press F5 to see your WPF application in action

WHERE ?

Simple isn’t it ?? But there are a series of where questions to be asked in here.

  1. Where is the main function (entry point for the WPF application) ?
  2. How did Visual Studio found out that Window1 is my top level window (parent window) ?
  3. From where did it create the instance of Window1 to show it on the screen ?
  4. *

Lets try to figure out the answers now.

1. Where is the main method ? Answer is fairly simple. Visual Studio has created the main function for the application during the run time. If you notice the solution explorer, there will be two xaml files. App.xaml and Window1.xaml (by default). If you open the properties of App.xaml, one of the settings would be Build Action. This would be set to Application Definition, meaning the WPF application’s start point is this class.

2 and 3. Where is the instance of Window1 ? For this, we need to explore the App.xaml file. As mentioned in the previous inference, App.xaml has been made as the start point thru’ properties, so we need to explore the this file for the startup windows. If you see the code (xaml code),

<Application x:Class="Foo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>


</Application.Resources>
</Application>

the application tag has an attribute called StartupUri whose value is Window1. This means that when the class App is getting instantiated and when the it is run, it should automatically create an instance of Window1.xaml class (as mentioned in the StartupUri attribute) and show it.

But WHY ?

So now that we have found answers for where, we still have a set of why questions to be answered

  1. Why do we need an App.xaml file, can I run my application without it ?
  2. Why did Visual Studio create the main method ? Why can’t I do it ?
  3. Can I show my Window1 myself ? I don’t want Visual Studio to do that
  4. *

Lets figure out the answers now,

1. Can I run my application without App.xaml file ? No. Its not possible.

2. Why did Visual Studio create the main method ? For this we need to understand how the WPF application works. Every WPF application is nothing but an instance of the System.Windows.Application class. To run a WPF application, first we need to create an instance of this class manually. This should be done inside the main method. As the App.xaml has the entry point, it should create an object of the System.Windows.Application and it needs to call Run in that code behind file (App.xaml.cs).

System.Windows.Application myApp = new System.Windows.Application();
myApp.Run(); //Will run the application

Doing so will run the applicaiton. But still we will not be able to see any windows on the screen.

If you notice, the App.xaml class will be of type Application and not Window unlike the Window1.xaml file. Check out the root tag of App.xaml file.

3. Can I show my Window1 myself ? After creating an instance of System.Windows.Application class, we can create an object of the window class (top level window) in the main method and then call Show on it.

Window1 myWindow = new Window1();
myWindow.Show(); //Will show the window on the screen

Atlast, your main method should look something like this,

class Program
[STAThread] //.net norms for com
static void Main()
{
System.Windows.Application myApp = new System.Windows.Application();
Window1 myWindow = new Window1();
myWindow.Show(); //Will show the window on the screen
myApp.Run(); //Will run the application
}

Visual Studio didn’t want its users to mess with all these things. So most of these are done automatically leaving the users just to bother about their application and its user interfaces. Anyways its nice to know about these when you write a WPF application.

In the next post, I will write about System.Windows.Application class


14
Mar 09

GDI+ to WPF

Long since I blogged. Reason being the title. I am trying to learn WPF (Windows Presentation Foundation) programming. From now, most of the posts will be WPF related. Meanwhile, if you want to know more about WPF and why WPF, check this out. Although the article is kind of old, its worth giving a look at it.