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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Task Manager" Height="350" Width="525" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="80"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Grid.Column="0" Background="Orange" Orientation="Horizontal">
            <TextBlock  Text="Count:" Margin="10,10"/>
            <TextBlock  Text="" Margin="10,10"/>
        </StackPanel>
        <StackPanel Grid.Row="1" Grid.Column="0" Background="Gray">
        </StackPanel>
    </Grid>
</Window>
Untitled

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

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


Untitled

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


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

No comments:

Post a Comment

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

Shorts - week 3, 2022

Post with links to what I am reading: 1. A very good post on different aspects of system architecture: https://lethain.com/introduction-to-a...