Saturday, 1 October 2011

WPF: Binding example (Part 1)

Let’s try to build a WPF application using all its binding features.

Goal: Build an application loosely based on the Window’s Task Manager. It will show all the running processes, with certain properties like CPU consumption, Working Set etc.

We start by creating a new WPF application project in VS 2010. In the MainWindow.xaml.cs we include the namespace “System.Diagnostics”. This namespace contains the classes/methods which we will use to get the details about running processes.

In code file, we initialize a List<Process> variable – and fill it with Process objects.

private List<Process> ProcList;
ProcList = Process.GetProcesses().ToList<Process>();

The ProcList variable will be the data source for all our binding operations. So we set this object as DataContext:

this.DataContext = ProcList;

Now let’s switch to XAML file. Here we want to show the list of processes, so the ideal UI control would be ListBox. The UI contains two sections (two rows), first row will show general things like count and the one below will show the list.

<Window x:Class="Processes.MainWindow"
        Title="WPF Task Manager" Height="350" Width="525" WindowStartupLocation="CenterScreen">
            <ColumnDefinition />
            <RowDefinition Height="80"/>
            <RowDefinition />
        <StackPanel Grid.Row="0" Grid.Column="0" Background="Orange" Orientation="Horizontal">
            <TextBlock  Text="Count:" Margin="10,10"/>
            <TextBlock  Text="" Margin="10,10"/>
        <StackPanel Grid.Row="1" Grid.Column="0" Background="Gray">

Now we bind the Count textblock to the no. of processes. This is done simply by:

<TextBlock  Text="{Binding Path=Count}" Margin="10,10"/>


(remember DataContext should be set for this binding to work)

In next post we will populate the list box with process list.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.