Sunday, 2 October 2011

WPF: Binding example (Part 3)


Continuing on the binding series, we achieved this in the last blog post:

image_thumb8

But there is something not right here. The column headers – ProcessName, WorkingSet etc. appear in each item. So how do we fix it. One of the option (we look at the other option in next post) is to use ListView control. This control offers a grid-like UI with columns – so let us see how it works out.

We change the XAML code (due to wonders of binding we do not need to change the code file):

<Window x:Class="Processes.ListViewTaskMgr"
        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="50"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Grid.Column="0" Background="Orange" Orientation="Horizontal">
            <TextBlock Text="No. of processes:" Margin="10,10"/>
            <TextBlock Text="{Binding Path=ProcList.Count}" Margin="10,10"/>
        </StackPanel>
        <ListView Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Path=ProcList}" Background="Gray" Foreground="Black" Name="lst" HorizontalContentAlignment="Stretch">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=ProcessName}" />
                    <GridViewColumn Header="Working Set" DisplayMemberBinding="{Binding Path=WorkingSet}"/>
                    <GridViewColumn Header="Private Memory" DisplayMemberBinding="{Binding Path=PrivateMemorySize}"/>
                    <GridViewColumn Header="Virtual Memory" DisplayMemberBinding="{Binding Path=VirtualMemorySize}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

image


Isn’t this fascinating? We just changed the UI layer and without touching code everything works well!


So how is ListView different from ListBox? In ListView each process object is bound to a single row. We do not need to use the ItemTemplate – we can use “DisplayMemberBinding” in ListView column to get the Process property.

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...