XTab's Blog

Ged Mead's Blog at vbCity

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

JanFebruary 2010Mar
SMTWTFS
31123456
78910111213
14151617181920
21222324252627
28123456
78910111213

Archives

Topics

Ramblings

VB.NET

Tuesday, October 27, 2009 #

 XAML is brilliant for creating user interfaces at design time, but if you need to make changes dynamically at runtime, this can sometimes be a problem. To take an example, let's say that you need to allow an Image to move to a different location on screen in response to some user action.

To demonstrate this, we can use an Image which is housed in a Canvas. So the first step is to create a Canvas in a WPF Window, place the Image inside the Canvas and assign a value to the Source property of the Image:  

<Window x:Class="Window2"

   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   Title="Image In A Canvas" Height="300" Width="300">

  <Canvas x:Name="MainCanvas">

    <Image x:Name="MoveableImage" Width="55" Source="questionmark2.jpg" />

  </Canvas>

</Window>

 We can then have the Image move a few units to the right each time it receives a mouse click. The WPF Image doesn't support the Click event, but MouseDown is available for the same purpose. So the next step is to wire up an event handler for this:

    <Image x:Name="MoveableImage" Width="55" Source="questionmark2.jpg"

        MouseDown="Image_MouseDown" />

Here's the first pass at the Image_MouseDown event in the code-behind to move the Image 10 units to the right on each mouse down:

    Private Sub Image_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)

        Dim LeftPos As Double = MoveableImage.GetValue(Canvas.LeftProperty)

 

        MoveableImage.SetValue(Canvas.LeftProperty, LeftPos + 10)

 

    End Sub

This seems straightforward enough, doesn't it? The variable named LeftPos reads the value that is currently stored as the attached Canvas.Left property of the Image, then it increments that value by 10. If you were to run this project, you would expect that the Image would jump 10 units to the right when the mouse is clicked on it. But if you try this code, you will find that nothing happens when the Image is clicked.

There's a little WPF Gotcha lurking in the canvas, just waiting to confuse you. When you create this layout, as you can see from the screenshot below, the Image appears in the top left hand corner of the Canvas by default:

 

      

You would be forgiven for assuming that the attached Canvas.Left and Canvas.Top values of the Image are set to zero. It's a reasonable assumption to make, especially as you can see the Image in exactly that location. However, it doesn't actually work like that. By default the Left and Top attached properties are in fact set to Double.NaN - Not A Number. This is effectively a null value that is assigned in order to allow the Canvas to make use of its own built-in layout intelligence for more complex scenarios.

The fix is simple - you just have to assign values to the Canvas.Left and Canvas.Top properties in the XAML when you create the Image element, but it's something that isn't obvious. Not only does it mean that the expected movement of the Image doesn't happen, but it will actually cause your application to crash if you try and reset the value in code to move the Image back to the start position (which we will do later).

So, here's the amended XAML for the Image: 

    <Image x:Name="MoveableImage" Width="55" Source="questionmark2.jpg"

        MouseDown="Image_MouseDown"

        Canvas.Left="0" Canvas.Top="0" /> 

With that change in place, the Image will now move when it is clicked.

In this kind of situation, you probably won't want the Image to either get stuck at the right hand side of the Canvas or, possibly even worse, move out of sight. A simple If/Then statement will fix this: 

        If LeftPos < (MainCanvas.ActualWidth - MoveableImage.Width) Then

            MoveableImage.SetValue(Canvas.LeftProperty, LeftPos + 10)

        Else

            MoveableImage.SetValue(Canvas.LeftProperty, CDbl(0))

        End If 

As you can see, the first line tests if there is still enough width remaining for the Image to be moved 10 elements to the right and still be visible. If there is, then the 10 unit jump takes place. If not, then the Image is shunted back to far left of the Canvas. Note that this will fail if you haven't set the initial value of the Canvas.Left property as described earlier.

It will also fail if you don't cast the value (in this example, zero) to a Double. This is because the second parameter of the SetValue method is a generic Object Type and the Canvas.Left property requires a Double.

Moving the Image downwards follows the same kind of logic. You set an initial value on the Canvas.Top property then increment this when the MouseDown event fires. Perhaps you want to build in a feature where the left mouse button causes the Image to move left and the right mouse button to move it down.

If you are moving from Windows Forms to WPF, you may expect to find the Button property of the MouseEventArgs. You would then use code along the lines of:

        If e.Button = Windows.Forms.MouseButtons.Left Then

            ' Do Something

        End If

WPF is (again) slightly different. It uses the System.Windows.Input.MouseButtonEventArgs class in place of the Windows Forms version and it has a ChangedButton property, not a Button property. So the WPF version of the previous snippet will start with: 

 If e.ChangedButton = MouseButton.Left Then 

The following code snippet combines the use of either the left or right mouse button to move the Image left or down respectively:

    Private Sub Image_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)

 

        If e.ChangedButton = MouseButton.Left Then

 

            Dim LeftPos As Double = MoveableImage.GetValue(Canvas.LeftProperty)

 

            If LeftPos < (MainCanvas.ActualWidth - MoveableImage.Width) Then

                MoveableImage.SetValue(Canvas.LeftProperty, LeftPos + 10)

            Else

                MoveableImage.SetValue(Canvas.LeftProperty, CDbl(0))

            End If

 

 

        ElseIf e.ChangedButton = MouseButton.Right Then

            Dim TopPos As Double = MoveableImage.GetValue(Canvas.TopProperty)

 

            If TopPos < (MainCanvas.ActualHeight - MoveableImage.Width) Then

                MoveableImage.SetValue(Canvas.TopProperty, TopPos + 10)

            Else

                MoveableImage.SetValue(Canvas.TopProperty, CDbl(0))

            End If

        End If

 

    End Sub

Finally, of course, you can combine the horizontal and vertical movement of the Image - maybe by using the Middle mouse button:

        ElseIf e.ChangedButton = MouseButton.Middle Then

            MoveableImage.SetValue(Canvas.LeftProperty, MoveableImage.GetValue(Canvas.LeftProperty) + 10)

            MoveableImage.SetValue(Canvas.TopProperty, MoveableImage.GetValue(Canvas.TopProperty) + 10)

        End If

The above snippet can be expanded to have the tests for reaching the outer edges built in also.

The main issues I particularly wanted to cover in this blog item were the GetValue and SetValue methods, which are a very useful tool in these kind of situations. I also wanted to flag up the various WPF Gotchas that might trip up the unwary WinForms developer. In a follow-up blog, I plan to take this task a step further and look at ways of giving the user several ways of achieving the Image movement - all of which loop back to a single piece of code

posted @ 12:23 PM

Monday, October 26, 2009 #

 The Windows Forms ListView is designed to display data. You can use a simple text file as the data source of a Windows Forms ListView. Let's start with a scenario where you have a txt file that contains the data. Each line of the text file represents one row of data to be displayed in the ListView. The content for each column item (or cell) is delimited by the use of a TAB character.

A simple text file along these lines might contain the following entries:

Ged Mead UK
Serge Baranovsky    USA
Larry Blake USA
Scott Waletzko      USA
Mark Dryden UK
Dave Jeavons UK
Chris Manning USA

(The uneven layout is caused by the use of the TAB as the delimiter)

Reading data from a file
An easy way of transferring this data from the file to the ListView is to:

  • Use a StreamReader which accesses the text file and then reads it line by line.
  • As each new line is read, it is split by means of the TAB character and temporarily stored in a String array.
  • Next, the first element is pulled out of the String array and used as the item for the first column of the ListView (the ListViewItem).
  • Then the remaining two elements are pulled out of the String array in turn and assigned as the SubItems of the ListViewItem.

 

Here's the code that carries out those steps:

  ' Variable for file to hold data

    Dim TextFile As String = "F:\MVPs.txt"

 

    Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click

 

        Try

            ' Declare StreamReader and pass the Path of the text file to be read as a Parameter

            Dim SR As New StreamReader(TextFile)

            '  Variable to hold data as it is read line by line

            Dim strTemp() As String

 

            Do While SR.Peek <> -1 ' Use Peek to read the file until there are no more lines

                '  Create a variable for the ListViewItems

                Dim LVItem As New ListViewItem

                '  Read the next line in file and Split it using the TAB.

                strTemp = SR.ReadLine.Split(Chr(9))

                '  Pull out the first element in the line and assign it as

                '  the data for the first column.

                LVItem.Text = strTemp(0).ToString

                '  Add the item to the ListView

                LVMVPs.Items.Add(LVItem)

                '  Assign elements 2 & 3 as the subitems.

                LVItem.SubItems.Add(strTemp(1).ToString)

                LVItem.SubItems.Add(strTemp(2).ToString)

            Loop

 

            SR.Close() ' Close the StreamReader

 

        Catch ex As Exception

 

            MsgBox("Error reading file." & ex.Message)

 

        End Try

 

    End Sub

You'll see that I've used a variable to hold the path to the file that contains the data. You will also need to include an Imports statement for System.IO at the top of the Class file.

Although the above code will successfully access the file, read and split the data and then populate the ListView, the result you will see may not be what you expect or want:

  

The first problem is that the View Property of the ListView needs to be set to Details. By default it is set to LargeIcon, with the result you see in the screenshot. You can make this change via the Properties Window or in code. 

        LVMVPs.View = View.Details 

Make that change, run the project, hit the 'Get From File' button and you will see:

  

Again, definitely not what you want! The problem here is that the ListView won't automatically create columns for you, even though you might expect that it would based on the data you are feeding in. As it is traditional to have some header text at the top of each column, you can create this at the same time as you create the column itself .  

        LVMVPs.Columns.Add("First Name", 76)

        LVMVPs.Columns.Add("Surname", 96)

        LVMVPs.Columns.Add("Location", 56) 

 

Now, when you run the project again you will see the data neatly tabulated in the ListView.

  

I have also set the width property of each column in the code above, because the default width would result in some of the longer strings being truncated otherwise.

If you don't want to hard code those column headers, you can change the text file structure and have the column headers written to the first line of the file. You would then pull these out first and assign them to the columns, before using the Do While loop to read and display the rest of the file.

Writing data to a file
Although a ListView's key purpose is to display existing data, there may be times when you have edited the content and want to save it back to a text file. The steps involved in doing this are as follows:

  • Use a FileStream to set up the file you are going to write to.
  • Use a StreamWriter to access the chosen file.
  • Loop through each row of the ListView, pull the text data from each column in turn and write it to the text file, adding a TAB character after each item.
  • Add a new line at the end of each loop.  

The code for this process is:

   Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        '  Create FileStream and StreamWriter to access and write to file

        Dim FS As New FileStream(TextFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)

        Dim SW As New StreamWriter(FS)

 

        Try

            '  Loop through all rows

            For Index As Integer = 0 To LVMVPs.Items.Count - 1

                '  Internally loop through all columns, gathering items

                For SubIndex As Integer = 0 To LVMVPs.Items(Index).SubItems.Count - 1

                    SW.Write(LVMVPs.Items(Index).SubItems(SubIndex).Text & Chr(9))

                Next

                '  Create new line ready for next row

                SW.Write(Environment.NewLine)

 

            Next

        Catch ex As Exception

 

            MsgBox("Error saving to file." & ex.Message)

 

        Finally

 

            SW.Close()

            FS.Close()

 

        End Try

 

    End Sub

For many simple scenarios where you want to display tabulated text in a ListView (and optionally save it back to a file), the above approaches will work just fine. There will of course be times when you need something more sophisticated and I will look at some of those in later blogs.

posted @ 12:41 PM | Feedback (1)

Sunday, October 25, 2009 #

Introduction
In the first part, I outlined the sample application and said that it:

  • will create a collection of Person objects and databind them to a ListBox.
  • will use very simple DataTemplates to format two properties of the Person class - FullName and Status.
  • will use a GroupStyle HeaderTemplate to display a third property of the Person class - Category.
  • groups the Person objects by their Category property.
  • sorts the Categories and displays them in alphabetical order.
  • sorts the Persons by name inside the Category groups and displays them in alphabetical order.  

The first five tasks are all covered in that previous part. You can download the project up to this point from here.

Sorting the Categories
In the same way that I used a Group Description to group items together, WPF offers the SortDescription to allow data inside the CollectionView to be sorted. The following code in the Window Loaded event is all that's needed:

        currentView.SortDescriptions.Add(New SortDescription("Category", ListSortDirection.Ascending))

The SortDescription takes two parameters. The first is the name of the property that you want to sort on. The second is one of two choices for the sort direction.

For completeness, this is the full code so far in the Window Loaded event (which creates the DataContext, the View, the GroupDescription and the SortDescription):

    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Contacts = Person.GetPersons

        Me.DataContext = Contacts

 

        Dim currentView As ICollectionView

        currentView = CollectionViewSource.GetDefaultView(Contacts)

 

        '  Group

        currentView.GroupDescriptions.Add(New PropertyGroupDescription("Category"))

 

        '   Sort Categories

        currentView.SortDescriptions.Add(New SortDescription("Category", ListSortDirection.Ascending))

 

    End Sub

The sorted Categories will look like this:

 

Sorting the ListItems
As you can see, the Categories are now in alphabetical order. The names of the Person objects however are still shown in the relative order in which they were created. To create this secondary sort, the same kind of code is used:

        currentView.SortDescriptions.Add(New SortDescription("FullName", ListSortDirection.Ascending))

The resulting display is:

  

The clearest example is where you can see the three items in the 'Work Colleagues' Category. They are now sorted alphabetically.

Note that the order that you list the sorting tasks is important. If you were to reverse the order:

       '   Sort individual names

        currentView.SortDescriptions.Add(New SortDescription("FullName", ListSortDirection.Ascending))

 

        '   Sort Categories

        currentView.SortDescriptions.Add(New SortDescription("Category", ListSortDirection.Ascending))

 

You would effectively lose the Category sort.

  

It is possible to create and apply the grouping and sorting in XAML, but I always try as far as possible to handle these kind of tasks in code-behind. Equally, I try and use XAML for the actual graphical display. There isn't a clear line between the two sometimes, of course, and you have to allow for individual preferences, but I try and keep to this approach as a general rule.

posted @ 1:26 PM

Introduction
I was going to title this blog "What's in a name?" because William Shakespeare's famous question smacked me on the head recently after what seemed like several hours of frustration. The answer in this particular case is "Quite a lot!". As you'll see when I cover the syntax used to group items, you can very easily fall into a trap when it comes to names.

But first, I'll need to set the scene. This small application:

  • will create a collection of Person objects and databind them to a ListBox.
  • will use very simple DataTemplates to format two properties of the Person class - FullName and Status.
  • will use a GroupStyle HeaderTemplate to display a third property of the Person class - Category.
  • groups the Person objects by their Category property.
  • sorts the Categories and displays them in alphabetical order.
  • sorts the Persons by name inside the Category groups and displays them in alphabetical order.

 The Person Class
First, the Person Class - which I have chosen to implement INotifyPropertyChanged, although I don't actually take advantage of the change notification in this simple example:

Imports System.ComponentModel

Imports System.Collections.ObjectModel

 

Public Class Person

    Implements INotifyPropertyChanged

 

    Sub New(ByVal personname As String, ByVal personstatus As String, ByVal personsgroup As String)

        Me.FullName = personname

        Me.Status = personstatus

        Me.Category = personsgroup

    End Sub

 

    Private _name As String

    Public Property FullName() As String

        Get

            Return _name

        End Get

        Set(ByVal value As String)

            _name = value

            OnPropertyChanged(New PropertyChangedEventArgs("FullName"))

        End Set

    End Property

 

    Private _status As String

    Public Property Status() As String

        Get

            Return _status

        End Get

        Set(ByVal value As String)

            _status = value

            OnPropertyChanged(New PropertyChangedEventArgs("Status"))

        End Set

    End Property

 

    Private _Category As String

    Public Property Category() As String

        Get

            Return _Category

        End Get

        Set(ByVal value As String)

            _Category = value

            OnPropertyChanged(New PropertyChangedEventArgs("Category"))

        End Set

    End Property

 

    Public Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs)

        If Not PropertyChangedEvent Is Nothing Then

            RaiseEvent PropertyChanged(Me, e)

        End If

    End Sub 

 

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

 

 

    Public Shared Function GetPersons() As List(Of Person)

        Dim GP As New List(Of Person)

        GP.Add(New Person("Neil Birch", "Available", "My Friends"))

        GP.Add(New Person("Joe Brown", "On Site", "Work Colleagues"))

        GP.Add(New Person("Larry Blake", "Available", "VB City"))

        GP.Add(New Person("Fran Mead", "At Work", "Family"))

        GP.Add(New Person("Elaine Javan", "On Vacation", "Work Colleagues"))

        GP.Add(New Person("Matt Higginbotham", "On Line", "VB City"))

        GP.Add(New Person("Zoe Flint", "On Site", "Work Colleagues"))

        Return GP

    End Function

 

End Class

Essentially, all you need to note for the purpose of this article is that the GetPersons function creates a List (of Person) and each Person instance has values assigned to all three of the properties of the class - FullName, Status, and Category.

The WPF Window
The WPF Application contains just one Window. A List of Persons is created by using the GetPersons function and this List is used as the DataContext for the Window. This will allow the ListBox to access that List. The initial code-behind is as follows:

Class Window1

    Dim Contacts As New List(Of Person)

    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Contacts = Person.GetPersons

        Me.DataContext = Contacts

    End Sub

 

End Class

The ListBox
In the XAML for Window1, there is a ListBox. To begin with, this ListBox simply shows the Person's FullName, followed by their Status. There is a minimal amount of formatting in the two TextBlocks that are used for this.

      <ListBox Name="lstContacts"

        ItemsSource="{Binding}"

        Margin="6,6,3,3" >

 

 

        <ListBox.ItemTemplate>

        <DataTemplate >

          <StackPanel >

            <TextBlock Text="{Binding Path=FullName}"

              Margin="0,2,0,0"/>

            <TextBlock Text="{Binding Path=Status}"

              Margin="6,0,0,0" FontSize="11" Foreground="Navy" />

 

          StackPanel>

        DataTemplate>

      ListBox.ItemTemplate>

    ListBox>

The result so far is this:

Obviously, there is no sorting or grouping going on there yet.

CollectionView
When you set up the Binding between the data source (the List of Persons) and the target control (the ListBox), a CollectionView is created automatically. This is a wrapper for the binding and allows you to sort, filter, group or navigate through the collection without affecting the underlying collection itself. Think of it as an editable snapshot of the data and you won't be far off the mark

You can access the current view by using the GetDefaultView method and passing in the name of the data source - in this case, the Contacts List created in the code-behind of Window1. In our example, we will access the CollectionView and then group and sort the items as they are displayed in the ListBox. To try and keep things as straightforward as possible I'll tackle each of these one at a time.

Creation of an instance of the view by means of the GetDefaultView method is simple.  

Imports System.ComponentModel

 

    Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        Contacts = Person.GetPersons

        Me.DataContext = Contacts

 

        Dim currentView As ICollectionView

        currentView = CollectionViewSource.GetDefaultView(Contacts)

    End Sub

 

End Class

Note the inclusion of the Imports statement for System.ComponentModel, the class which houses ICollectionView.   

It's the final two lines of the Window_Loaded event that create the View:

   

Grouping

The following line of code, placed in the Window_Loaded event, will group the individual items based on the Category property:

        currentView.GroupDescriptions.Add(New PropertyGroupDescription("Category"))

The result is shown below:

  

So I don't have to be much of a mind reader to know that you're not too impressed at this point. In fact, you probably don't even believe that the items are now grouped. And even if they are, it's not very obvious to the user.

Let's start with the question of whether they are really grouped.   If you look carefully at the order of the names you will see that they have changed from the way they were originally listed - as seen in the earlier screenshot. And if you take a peek at the code which created the Person instances you will be able to see the value of the Category property for each instance.

    Public Shared Function GetPersons() As List(Of Person)

        Dim GP As New List(Of Person)

        GP.Add(New Person("Neil Birch", "Available", "My Friends"))

        GP.Add(New Person("Joe Brown", "On Site", "Work Colleagues"))

        GP.Add(New Person("Larry Blake", "Available", "VB City"))

        GP.Add(New Person("Fran Mead", "At Work", "Family"))

        GP.Add(New Person("Elaine Javan", "On Vacation", "Work Colleagues"))

        GP.Add(New Person("Matt Higginbotham", "On Line", "VB City"))

        GP.Add(New Person("Zoe Flint", "On Site", "Work Colleagues"))

        Return GP

    End Function

Now, you can see that the first Category is "My Friends" and Neil Birch is the sole member of that Category. More usefully, the next three instances - Joe Brown, Elaine Javan and Zoe Flint all have "Work Colleagues" as their Category. They are now all listed consecutively - and both Elaine Javan and Zoe Flint have been moved from their original positions.

The next two names - Larry Blake and Matt Higginbotham are both in the "VB City" Category. Fran Mead is the sole member of the "Family" Category.

So, the grouping has actually taken place. The order of the Categories is based on the order in which they first appear in the GetPersons function.

Clearly, we need something to make the grouping of Categories more obvious. And that 'something' is a GroupStyle. GroupStyle has a HeaderTemplate property which can be used to format the text and/or graphics that are displayed at the start of each group - in this case at the start of each Category.

The XAML is a little bit verbose, but - apart from one potential Gotcha - is straightforward.

      <ListBox.GroupStyle>

        <GroupStyle>

          <GroupStyle.HeaderTemplate>

            <DataTemplate>

              <TextBlock Text="{Binding Path=Name}" FontWeight="Bold"/>

            DataTemplate>

          GroupStyle.HeaderTemplate>

        GroupStyle>

      ListBox.GroupStyle>

The GroupStyle has a HeaderTemplate. The HeaderTemplate contains a DataTemplate. In this case I have chosen to include only a basic TextBlock in the DataTemplate. The Text property of the TextBlock needs to show the Category name.

This is where I managed to get myself quite confused.

  <TextBlock Text="{Binding Path=Name}" FontWeight="Bold"/>

I initially had a property in the Person class called Name. (I've since changed it to FullName for clarity.) I couldn't understand why the Path of a TextBlock that showed the Category value would be pointing to the Name property of Person class. And of course it doesn't. But, while I was getting to grips with this I set the path to what I thought was the most logical item - the Category property. In other words, I had it like this:

 <TextBlock Text="{Binding Path=Category}" FontWeight="Bold"/>

Now, WPF is so forgiving when it comes to this kind of data binding that it doesn't throw an exception (quite rightly, because it is a valid path to an existing field). Sadly it doesn't show the Categories either. The result at this point is:

  

You can see that they are grouped, but there's no header.   The key lesson to take away from this is that the Path in that particular binding points to the name that is assigned to the PropertyGroupDescription in the code-behind:

   currentView.GroupDescriptions.Add(New PropertyGroupDescription("Category"))

Confused yet? Put simply, you always use the syntax of:

              <TextBlock Text="{Binding Path=Name}" FontWeight="Bold"/>

regardless of what the actual name of the grouping property is. You're probably thinking that we're well into the "Too much information" stage now, but - apart from wanting to share my pain - I really think that this is Gotcha that is just waiting to bite the unwary and so it was worth spending a couple of extra minutes looking at it.

OK, so getting back on track, the correct version of the GroupStyle markup will bring you the result you want. I have included all the ListBox XAML so you can see the finished product:

   <ListBox Name="lstContacts"

        ItemsSource="{Binding}"

        Margin="6,6,3,3" >

 

      <ListBox.GroupStyle>

        <GroupStyle>

          <GroupStyle.HeaderTemplate>

            <DataTemplate>

              <TextBlock Text="{Binding Path=Name}" FontWeight="Bold"/>

            DataTemplate>

          GroupStyle.HeaderTemplate>

        GroupStyle>

      ListBox.GroupStyle>

 

      <ListBox.ItemTemplate>

        <DataTemplate >

          <StackPanel >

            <TextBlock Text="{Binding Path=FullName}"

              Margin="0,2,0,0"/>

            <TextBlock Text="{Binding Path=Status}"

              Margin="6,0,0,0" FontSize="11" Foreground="Navy" />

 

          StackPanel>

        DataTemplate>

      ListBox.ItemTemplate>

    ListBox>

Here it is:

The grouping is clear, has a useful header and - more to the point - is accurate. The Categories are not yet in alphabetical order. The individual Person instances are also not sorted within their Categories, as you can see from the order in the Work Colleagues group.

As this blog has become a bit longer than I expected, I will continue with a Part 2, which will cover the Sorting methods.

I have posted a copy of this project which you can download from here.

posted @ 1:25 PM

 

 

In the previous blogs on ValueConverters - here and here - the conversion was from Integer type to Brush. In this blog I will cover the situation where you want to include a small image or icon in the ListView.

There are various alternatives here. You could hard code the image path into the collection, but the problem may be that you don't know the exact image paths at the time the collection is created. The approach I want to use is where you parse the data as it feeds through the binding and you select a stored image from the hard drive, the selection being based on the value of a specific field. This decouples the details of the image from the collection itself, which may be useful in many situations.

The DrinkProduct class looks like this: 

Public Class DrinkProduct

    Enum MaterialType

        Granules

        Leaf

        Liquid

        Paste

        Powder

        Other

    End Enum

    Sub New(ByVal ID As String, ByVal Name As String, ByVal PackType As String, _

           ByVal BaseMaterial As MaterialType, ByVal Sales As Integer, ByVal Qty As Integer)

        Me.ProductID = ID

        Me.ProductName = Name

        Me.PackageType = PackType

        Me.Material = BaseMaterial

        Me.AnnualSales = Sales

        Me.Quantity = Qty

    End Sub

 

    Private _ProductID As String

    Public Property ProductID() As String

        Get

            Return _ProductID

        End Get

        Set(ByVal value As String)

            _ProductID = value

        End Set

    End Property

 

    Private _ProductName As String

    Public Property ProductName() As String

        Get

            Return _ProductName

        End Get

        Set(ByVal value As String)

            _ProductName = value

        End Set

    End Property

 

    Private _PackageType As String

    Public Property PackageType() As String

        Get

            Return _PackageType

        End Get

        Set(ByVal value As String)

            _PackageType = value

        End Set

    End Property

 

 

    Private _Material As MaterialType

    Public Property Material() As MaterialType

        Get

            Return _Material

        End Get

        Set(ByVal value As MaterialType)

            _Material = value

        End Set

    End Property

 

    Private _quantity As Integer

    Public Property Quantity() As Integer

        Get

            Return _quantity

        End Get

        Set(ByVal value As Integer)

            _quantity = value

        End Set

    End Property

 

 

    Private _annualsales As Integer

    Public Property AnnualSales() As Integer

        Get

            Return _annualsales

        End Get

        Set(ByVal value As Integer)

            _annualsales = value

        End Set

    End Property

 

    Public Shared Function StockCheck() As List(Of DrinkProduct)

        Dim CurrentProducts As New List(Of DrinkProduct)

        With CurrentProducts

            .Add(New DrinkProduct("CF1kg", "Coffee Powder", "1 Kg", MaterialType.Powder, 15684, 1276))

            .Add(New DrinkProduct("CFB500", "Ground Coffee", "500 g", MaterialType.Powder, 22785, 12856))

            .Add(New DrinkProduct("CFG500", "Coffee Granules", "500 g", MaterialType.Granules, 19233, 5907))

            .Add(New DrinkProduct("Te500", "Tea", "500 g", MaterialType.Leaf, 8544, 235))

            .Add(New DrinkProduct("TeInst500", "Instant Tea", "500 g", MaterialType.Powder, 1009, 22))

            .Add(New DrinkProduct("SMlk1lt", "Skimmed Milk", "1 Litre", MaterialType.Liquid, 28012, 2650))

            .Add(New DrinkProduct("HiJ300", "HiJuice Drink Mix", "300 g", MaterialType.Other, 578, 179))

            .Add(New DrinkProduct("Sm400", "Smoothie", "400ml", MaterialType.Paste, 9346, 3284))

            .Add(New DrinkProduct("Beef300", "Beef Drink", "300 g", MaterialType.Granules, 8316, 1965))

            .Add(New DrinkProduct("Beef750", "Beef Drink", "750 g", MaterialType.Granules, 7612, 359))

 

        End With

 

        Return CurrentProducts

    End Function

 

End Class 

The Enumeration named 'MaterialType' identifies whether the product is powder, liquid, granule, etc and this is what I will use as the key for selecting the appropriate image.

The ValueConverter class is similar to those used in the previous blogs - IValueConverter requires the two methods named Convert and ConvertBack. ConvertBack serves no purpose is this scenario, so only throws a not implemented exception. 

Public Class MaterialToImagePathConverter

    Implements IValueConverter

 

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert

        Select Case value.ToString

            Case "Powder"

                Return "Images/powderbrown.jpg"

            Case "Liquid"

                Return "Images/liquiddrop4.jpg"

            Case "Leaf"

                Return "Images/leaf.jpg"

            Case "Granules"

                Return "Images/granules.jpg"

            Case "Paste"

                Return "Images/Paste2.jpg"

            Case Else

                Return "Images/questionmark.jpg"

        End Select

 

    End Function

 

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack

        Throw New NotImplementedException()

    End Function

End Class 

As before, the parameter named 'value' is an Object type which is the key element in the conversion process. It contains the value that is to be converted. The conversion is simple in this case because all we need is to find the string value of the enumeration that is being passed in. So the basic ToString method will work fine.

Once we have a String value, this is compared against the various possibilities. A string which represents the file path to an appropriate image is returned by the converter. I've chosen to include the image files in the project, but of course they could be stored externally and still be accessed in the same way.

The next steps are the same as for the previous examples in the earlier blogs. First, map the current assembly to an XML namespace in Application.xaml:  

  xmlns:local="clr-namespace:WPFListView2"  

Then create an instance of the converter class in Application.xaml and give it a key: 

    <local:MaterialToImagePathConverter x:Key="IconConverter" /> 

Next, create a DataTemplate for the new column of the ListView:  

    <DataTemplate x:Key="IconCellTemplate">

            <Image Margin="0,0,1,3" Height="18" Width="25"

          Stretch="Fill"     

        Source="{Binding Path=Material, Converter={StaticResource IconConverter}}" />

    DataTemplate> 

In the above markup, the Binding Path is the Material field, the converter is the MaterialToImagePathConverter instance created above.

Finally, the ListView in the Window needs to have a new column added in which the images can be displayed: 

          <GridViewColumn

           CellTemplate="{StaticResource IconCellTemplate}">

          GridViewColumn> 

And now you are all set. The finished Window displays as shown below:

 

   

 

For completeness, the full markup for the Window which contains the ListView is shown here: 

<Window x:Class="Window2"

   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   Title="Image Path Converter Demo" Height="360" Width="450">

  <Grid>

 

    <ListView Name="ProductsListView"

         ItemsSource="{Binding}"

           Margin="5" >

 

      <ListView.ItemContainerStyle>

        <Style TargetType="ListViewItem">

          <Setter Property="HorizontalContentAlignment" Value="Stretch" />

        Style>

      ListView.ItemContainerStyle>

 

      <ListView.View>

        <GridView>

         

          <GridViewColumn

           CellTemplate="{StaticResource IconCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource IDColHeader}"

          CellTemplate="{StaticResource IDCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource NameColHeader}"

           CellTemplate="{StaticResource NameCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource PackageColHeader}"

           CellTemplate="{StaticResource PackCellTemplate}">

          GridViewColumn>

        GridView>

      ListView.View>

    ListView>

 

  Grid>

Window> 

Of course you are not forced to use the ValueConverter approach for this task. You could rewrite the class and give it an ImagePath property. Then in the code-behind run a function with a similar Select Case block to the one used above, passing back the appropriate path to the ImagePath property. The collection would be amended on the fly to include this data and finally the amended collection would be used as the DataContext. The Binding Path for the Image Source property would be that field. Personally, I think the ValueConverter is neater. And if the data comes from an external source, perhaps in the form of an XML file, then using the ValueConverter is almost certainly a better way.

posted @ 1:22 PM

If you have read any of my previous ListView blogs, you will know that formatting the ListView is mostly a matter of creating templates and styles for the various sub-elements. The same applies if you want to do something to differentiate one row from another. For instance, you might to have horizontal divider lines between each row.

This is the look we are going for in this blog:

        

The column headers were described in this blog, so I won't repeat the markup for those here.

In my last ListView blog, the ItemContainerStyle was used and we looked at the HorizontalContentAlignment property of the ListViewItem. By setting it to Stretch, the width of the items in each column was stretched so that their start and finish points all lined up vertically.

Here is the markup: 

      <ListView.ItemContainerStyle>

        <Style TargetType="ListViewItem">

            <Setter Property="HorizontalContentAlignment" Value="Stretch" />

        Style>

      ListView.ItemContainerStyle> 

And the result was this:

        

The problem with this obviously is those little gaps between the columns. The ListView inserts a margin of 6 units to the left and right of each column by default. So that is the cause of the gaps you can see there.

Each cell used a DataTemplate. Here is the DataTemplate for the cells in the first column shown above: 

    <DataTemplate x:Key="IDCellTemplate2">

      <Border Background="LightGreen" >

      <TextBlock Foreground="MediumBlue"

                FontFamily="Calibri"

         Text="{Binding Path=ProductID}" />

      Border>

    DataTemplate> 

What we need to do is to continue to make use the Border element in the DataTemplate for the cell, but remove the Light Green Background color. Then we can set a BorderBrush of Black and give it a Thickness of 1 unit.

Here's a first pass at it. This is the DataTemplate for the cells in the first column: 

    <DataTemplate x:Key="IDBorderedCellTemplate">

      <Border BorderBrush="Black"

             BorderThickness="1" >

        <TextBlock Foreground="MediumBlue"

                FontFamily="Calibri"

           Text="{Binding Path=ProductID}" />

      Border>

    DataTemplate> 

The other two templates are very similar so I won't clog up the screen with them just yet. Here's the result so far:

 

       

We ended up with boxes when we really wanted lines, but it's a good start. The first trick is to set the individual values on the BorderThickness - that is left, top, right and bottom. By setting a value of 0 on the left and right we will remove the vertical lines.

We also want to remove the top border, otherwise there will be a double line between the rows (the bottom border of one row, followed by the top border of the next). So, here's an improved version: 

    <DataTemplate x:Key="IDBorderedCellTemplate">

      <Border BorderBrush="Black"

              BorderThickness="0,0,0,1" >

        <TextBlock Foreground="MediumBlue"

                FontFamily="Calibri"

           Text="{Binding Path=ProductID}" />

      Border>

    DataTemplate> 

       

Getting closer. If we offset the start positions of the Borders in the DataTemplates and shunt them to the left to span the default gap of 6 units either side, we should be able to create a continuous line.

The following code snippet is the DataTemplate for the second column's cells. I'll explain why in a moment:

      <DataTemplate x:Key="NameBorderedCellTemplate">

      <Border BorderBrush="Black" Margin="-12,5,0,1"

             BorderThickness="0,0,0,1"  >

         <TextBlock Foreground="MediumBlue"

           FontFamily="Calibri" FontWeight="Bold"

           Text="{Binding Path=ProductName}" />

      Border>

    DataTemplate> 

The result:

       

What has happened here is that the Border in the second cell's template has been moved 12 units to the left. This has the effect of joining the end of first cell's bottom border to the start of the second cell's bottom border. This is achieved by setting the value of -12 for the left margin in the second line of markup above. So, to come back to why I have shown you the second cell's template, the reason is of course that the first cell doesn't need to be shunted to the left.

It's almost perfect, but there is just one minor adjustment still needed which I'll deal with next.

Moving the Border to the left means that its child TextBlock is also moved. It would look much better if the text content was displayed more in line with the column headers. You can see this in the second two columns in the screenshot above. This can be fixed by setting Margins on the TextBlocks. This time, I will shunt the TextBlocks back to the right.

Here is the markup for the second cell again: 

      <DataTemplate x:Key="NameBorderedCellTemplate">

      <Border BorderBrush="Black" Margin="-12,5,0,1"

             BorderThickness="0,0,0,1"  >

         <TextBlock Foreground="MediumBlue"

           FontFamily="Calibri" FontWeight="Bold"

           Margin="14,0,0,2"

           Text="{Binding Path=ProductName}" />

      Border>

    DataTemplate> 

This time it is the Margin property on Line 6 that's of interest. As you can see, it pushes the start of the text back to where we want it.

       

For completeness, here is the markup for all three DataTemplates: 

    <DataTemplate x:Key="IDBorderedCellTemplate">

      <Border BorderBrush="Black" Margin="0,5,0,1"

            BorderThickness="0,0,0,1" >

        <TextBlock Foreground="MediumBlue"

            FontFamily="Calibri"

            Margin="3,0,0,2"

            Text="{Binding Path=ProductID}" />

      Border>

    DataTemplate>

 

      <DataTemplate x:Key="NameBorderedCellTemplate">

       <Border BorderBrush="Black" Margin="-12,5,0,1"

           BorderThickness="0,0,0,1"  >

         <TextBlock Foreground="MediumBlue"

           FontFamily="Calibri" FontWeight="Bold"

           Margin="14,0,0,2"

           Text="{Binding Path=ProductName}" />

       Border>

    DataTemplate>

 

    <DataTemplate x:Key="PackBorderedCellTemplate">

      <Border BorderBrush="Black" Margin="-12,5,0,1"

             BorderThickness="0,0,0,1" >

         <TextBlock Foreground="MediumBlue"

            FontFamily="Calibri"

            Margin="15,0,0,2"

            Text="{Binding Path=PackageType}" />

      Border>

    DataTemplate> 

As it has been a couple of blogs since you saw the markup for the actual ListView, I'll list that too: 

    <ListView Name="ProductsListView"

         ItemsSource="{Binding}"

           Margin="5,25" >

      <ListView.ItemContainerStyle>

        <Style TargetType="ListViewItem">

            <Setter Property="HorizontalContentAlignment" Value="Stretch" />

        Style>

      ListView.ItemContainerStyle>

 

      <ListView.View>

        <GridView>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource IDColHeader}"

          CellTemplate="{StaticResource IDBorderedCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource NameColHeader}"

           CellTemplate="{StaticResource NameBorderedCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource PackageColHeader}"

           CellTemplate="{StaticResource PackBorderedCellTemplate}">

          GridViewColumn>

        GridView>

      ListView.View>

    ListView> 

The DataBinding to the very basic data source was covered in this blog.

So I know I've plodded through this in minute detail and you might think that it would have been better to have shown you the final versions of those DataTemplates and cut out all the intermediate steps. The reason I haven't is that you might want to take the basic idea and tweak it further - change colors, alter the vertical space between lines, change the distance that the text is shunted and so on. Now that you fully understand what each of those individual tweaks does, you can go ahead and make those kind of changes without having to pull my XAML apart to work out how its done.

posted @ 1:21 PM

 The Story So Far
Each of my previous blog items on WPF ListViews has mostly used a collection of DrinkProduct objects as the data source. This collection is bound to the Window via a DataContext and the individual columns are bound to fields in the collection. (As an alternative, this blog looked at the XML data source alternative.)

As the route from that first ListView blog to this one has become a bit murky, I'm going to start off by recreating the DrinkProduct class and creating the collection. I've taken the opportunity to add a few new properties which will be used in this and the upcoming ListView blogs.

You can view the revised DrinkProducts class code here.

The XAML markup for the start state of the ListView is in two locations. The ListView itself is in a WPF Window: 

<Window x:Class="Window1"

   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   Title="WPF ListView" Height="300" Width="450">

    <Grid>

    <ListView Name="ProductsListView"

         ItemsSource="{Binding}"

           Margin="5" >

 

      <ListView.View>

        <GridView>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource IDColHeader}"

          CellTemplate="{StaticResource IDCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource NameColHeader}"

           CellTemplate="{StaticResource NameCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource PackageColHeader}"

           CellTemplate="{StaticResource PackCellTemplate}">

          GridViewColumn>

        GridView>

      ListView.View>

    ListView>

  Grid>

Window> 

All the Resources - GradientBrush, Styles, DataTemplates for ColumnHeaders and Cells - are in the Application.xaml file. You can see the markup for these here.

If the Resources looks like a lot of markup, it breaks down into much less if you analyze it. There's a GradientBrush, a couple of Styles, then the DataTemplates, which are really only slightly tweaked versions of two simple templates.

At this stage the ListView looks like this:

ValueConverters
In this blog I want to demonstrate a simple example of the creation and use of a ValueConverter in WPF. ValueConverters are particularly useful in situations where you are using data binding to directly populate elements in the UI. By definition, this means that the data from the fields of the data source are passed untested from the source to the display.

This data will often be in a raw state, e.g. primitive types such as integer, double, boolean, etc.   In the first example I will use integer values that represent the quantity of stock remaining of the various drink products. These will be displayed in a new column of the ListView.

Although the DataTemplates created earlier can alter the core properties of all the values in the column - Foreground, Bold font, etc,- they don't offer any mechanism for analyzing these values and changing the look of the display of an individual value based on some criteria. For instance, changing the color of the text if the value is negative.

The way to achieve this kind of fine tuning is to use a ValueConverter. This automatically intercepts the data as it is being fed in from the DataContext, analyzes the value and makes any appropriate settings or changes to the display of this piece of data.

A Simple ValueConverter
Let's start with something simple, a ValueConverter that analyzes the quantity held in stock and if that value is less than a particular threshold, the figure is displayed in red in the ListView. This will give an easy introduction to the steps involved.

Before getting round to the ValueConverter I need to add a new column to the ListView, the column that will display the quantities held in stock. First a couple of DataTemplates - one for the column header and for the cell:  

     

    <DataTemplate x:Key="QtyColHeader">

      <Border Style="{StaticResource BlueBorder}">

        <TextBlock Text="Quantity " Style="{StaticResource ColHeaderText}" />

      Border>

    DataTemplate>

 

     

    <DataTemplate x:Key="QtyCellTemplate">

      <TextBlock Foreground="MediumBlue"

         Text="{Binding Path=Quantity}" />

    DataTemplate> 

Followed by the additional column in the ListView itself: 

         

          <GridViewColumn

           HeaderTemplate="{StaticResource QtyColHeader}"

           CellTemplate="{StaticResource QtyCellTemplate}">

          GridViewColumn> 

With just the raw quantity values showing in the new column, the ListView now looks like this:

 

For the sake of example, let's say that we want to highlight in red all values that are less than 200. First we create a class that implements IValueConverter. This implementation requires two methods - Convert and ConvertBack - each with a standard signature. Here is the code, which can be placed in a file of its own or - as I have chosen to do - appended to the end of (but not inside!) the Application.xaml.vb file:  

Public Class IntegerToBrushConverter

    Implements IValueConverter

 

    Public Function Convert(ByVal value As Object, ByVal targetType As Type, _

        ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _

        As Object Implements IValueConverter.Convert

 

        ' Only allow conversion if the correct TargetType is passed in.

        '  (This is optional)

        If targetType IsNot GetType(Brush) Then

            Return Nothing

        End If

 

        '  If less than 200 in stock, display in Red, otherwise use

        '  the default of MediumBlue

        Dim Result As Integer = Integer.Parse(value.ToString())

        Return (If(Result < 200, Brushes.Red, Brushes.MediumBlue))

    End Function

 

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, _

ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _

As Object Implements IValueConverter.ConvertBack

 

        ' Not used, so throw exception if this method is called.

        Throw New NotImplementedException()

    End Function

End Class

As you can see from the comments, I have chosen to test that a Brush object is passed in to the method. This isn't mandatory but is often worth including.   The second test in the Convert method checks the value of the current field and if it finds the value to be less than 200, Returns a Red Brush, otherwise it Returns a MediumBlue Brush.

Clearly, what is needed next is some mechanism that is watching for those returned values and making use of the particular brush that is returned. This is handled in the markup in the Application.xaml file.  If you are wondering why the markup is in Application.xaml and not the Window that contains the ListView, the reason is that we need to set the conversion on the DataTemplate that formats the Quantity column. And that DataTemplate is in Application.xaml.

As things stand, the XAML markup is unable to access the code above directly. So the first requirement is to map the current project into an XML namespace, making it possible to create a direct link between the two. The syntax for this is as follows:  

  xmlns:local="clr-namespace:WPFListview" 

which is placed in the Application.xaml file, just below the default XML namespaces which are placed there automatically. This now gives the ability to refer to the IntegerToBrushConverter in the XAML markup. (You may find that you have to Rebuild the solution to remove the wavy blue error mark after you first enter this. )

Now that the mapping is in place, I can create an instance of the IntegerToBrushConverter class and assign it a key so that it can be referred to in the XAML. 

  <local:IntegerToBrushConverter x:Key="QtyConverter" /> 

The final step is to use this instance of the converter inside the DataTemplate for the Quantity column. This markup is in the Application.xaml file: 

   

    <DataTemplate x:Key="QtyCellTemplate">

      <TextBlock

         Text="{Binding Path=Quantity}"

          Foreground="{Binding Path=Quantity, Converter={StaticResource QtyConverter}}"/>

    DataTemplate> 

The only change is to the Foreground property in the markup,which I have changed from the original hard-coded value of MediumBlue to the Binding you can see there. The syntax is reasonably straightforward:

  • The Path has to be an Integer type because that is what the IntegerToBrushConverter expects.
  • The relevant Path points to the field that the column is being databound to - Quantity.
  • The Converter in the Binding refers to that instance of the IntegerToBrushConverter created a few moments ago and given the key of 'QtyConverter'.

 The resulting display when the project runs is now:

Just to briefly cover the ConvertBack method, you can see from the commenting that this method isn't of use to us in this scenario. However, IValueConverter requires that it is included, so we simply throw an Exception if this method should be accessed at any point.

This has been a very simple example of using a ValueConverter, but it includes all the key steps. I plan to cover some more complex scenarios in later blogs.

posted @ 1:20 PM

In the previous blog, I created a simple ValueConverter that analyzed the data bound values and set the Foreground color of a TextBlock based on whether the value was less or more than a cut off value of 200 units. In reality, these preset values (such as the 200 in that demonstration) are rarely that rigid and you often need some flexibility in the analysis. To continue the example of a collection of drink products, it might be more realistic to compute a cut off value on the fly. For instance, if you know your annual sales for an individual item and you know the quantity you have in stock, you might want to highlight those items that need to be re-ordered. If it's a big selling item, the value of 200 may be far too low as a cut off; conversely an item with low annual sales might only need to be re-ordered when the stock is down to a handful.

So, how do we include this kind of calculation in a process where the value is data bound, but we need to apply some arithmetic to more than one field? The answer is to use MultiBinding and a MultiValueConverter.

You create a class that implements IMultiValueConverter. The core difference between this class and the one created in the previous blog is that the 'value' parameter of the Convert method is renamed to 'values' and is an array, not a single object. Armed with that array, you can pass in the values of two or more of the fields of your data source, run the calculations and Return a result.

Take a look at this class:

Public Class StockLevelConverter

    Implements IMultiValueConverter

 

    Public Function Convert(ByVal values() As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IMultiValueConverter.Convert

 

        If targetType IsNot GetType(Brush) Then Return Nothing

 

        '  Variables for the arithmetic operations

        Dim QtyHeld As Integer = CInt(values(0))

        Dim AnnualSales As Integer = CInt(values(1))

 

        '  Avoid divide by zero errors by not proceeding to the calculation

        '  and returning a different brush

        If QtyHeld = 0 Or AnnualSales = 0 Then Return Brushes.DarkGray

 

        Dim RestockLevel As Integer = AnnualSales / 12

 

        Return (If(QtyHeld < RestockLevel, Brushes.Red, Brushes.MediumBlue))

 

    End Function

 

    Public Function ConvertBack(ByVal value As Object, ByVal targetTypes() As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object() Implements System.Windows.Data.IMultiValueConverter.ConvertBack

        Throw New NotImplementedException()

    End Function

End Class

It is similar to the converter class created in the previous blog, having the same two methods, Convert and ConvertBack.    Note that this class implements IMultiValueConverter and the first parameter being an array as mentioned earlier.

In the Convert method, I have included the test that confirms that the correct Target Type has been passed in. Two variables, QtyHeld and AnnualSales are created and you will see that their respective values are taken from the two elements of the array named 'values' passed in as a parameter. We will need to look at how those array elements are notified to the converter in a moment.

Continuing with the Convert method, a test is included to avoid any divide by zero errors. I have chosen to Return a different colored Brush, but it could have been left to the default of MediumBlue if preferred.

The 'RestockLevel' variable could have been left out and the calculation that it uses could have been placed inside the If statement in the final line. But I felt that it is easier to read in the more verbose approach. The gist of these two lines is to divide the annual sales figure by 12 in order to find the average monthly sales. If the Stock held is less than one month's worth, then a Red Brush is returned, otherwise a MediumBlue one.

So, how do the values in the array get passed in to the Convert method? The answer is that a MultiBinding is used in the XAML. This is a similar approach to the single ValueConverter example seen previously, except that this time two Paths are required - one for the Quantity field and one for the AnnualSales field of the data source.

Assuming you are using the same project as in the previous blog, there is already a namespace mapping named 'local'. You then need to create an instance of this new converter class:

    <local:StockLevelConverter x:Key="StockChecker" />

The DataTemplate for the Quantity column cells will contain the MultiBinding. Here is the markup for this: 

    <DataTemplate x:Key="QtyCellTemplate">

      <TextBlock

          Text="{Binding Path=Quantity}" >

        <TextBlock.Foreground>

          <MultiBinding Converter="{StaticResource StockChecker}">

            <Binding Path="Quantity" />

            <Binding Path="AnnualSales" />

          MultiBinding>

        TextBlock.Foreground>

      TextBlock>

    DataTemplate> 

The Element.Property syntax is used to allow for the multiple sub elements. The MultiBinding is created and set to point to that instance of the StockLevelConverter class, which has been keyed as 'StockChecker'. The two paths which are passed in to the StockLevelConverter are listed next. Note that the array is filled in the order in which these paths are listed - that is values(0) will take the Quantity field values and values(1) will take the AnnualSales field values.

That's all there is to it. If I create some arbitrary dummy data for all the properties of the DrinkProduct class collection (i.e. including the Quantity and AnnualSales figures) and run the project, the resulting ListView will look like this:

 

If you're interested in trying this out, using the class code from the previous blog but can't be bothered to create your own dummy data, here is the collection I created:

 

  Public Shared Function StockCheck() As List(Of DrinkProduct)

        Dim CurrentProducts As New List(Of DrinkProduct)

        With CurrentProducts

            .Add(New DrinkProduct("CF1kg", "Coffee Powder", "1 Kg", MaterialType.Powder, 15684, 1276))

            .Add(New DrinkProduct("CFB500", "Ground Coffee", "500 g", MaterialType.Powder, 22785, 12856))

            .Add(New DrinkProduct("CFG500", "Coffee Granules", "500 g", MaterialType.Granules, 19233, 5907))

            .Add(New DrinkProduct("Te500", "Tea", "500 g", MaterialType.Leaf, 8544, 235))

            .Add(New DrinkProduct("TeInst500", "Instant Tea", "500 g", MaterialType.Powder, 1009, 22))

            .Add(New DrinkProduct("SMlk1lt", "Skimmed Milk", "1 Litre", MaterialType.Liquid, 28012, 2650))

            .Add(New DrinkProduct("HiJ300", "HiJuice Drink Mix", "300 g", MaterialType.Other, 578, 179))

            .Add(New DrinkProduct("Sm400", "Smoothie", "400ml", MaterialType.Paste, 9346, 3284))

            .Add(New DrinkProduct("Beef300", "Beef Drink", "300 g", MaterialType.Granules, 8316, 1965))

            .Add(New DrinkProduct("Beef750", "Beef Drink", "750 g", MaterialType.Granules, 7612, 359))

 

        End With

 

        Return CurrentProducts

    End Function

 

Don't forget to include the DataContext in the code-behind of Window1, the Window that holds the actual ListView:

Class Window1

    Dim CurrentProducts As New List(Of DrinkProduct)

 

 

    Private Sub Me_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        CurrentProducts = DrinkProduct.StockCheck()

        Me.DataContext = CurrentProducts

    End Sub

End Class

posted @ 1:18 PM

 By the end of the previous blog item on the topic of the WPF ListView, the ListView looked like this:

In this blog I want to look at ways of changing the look of the rows. You may, for example, want to assign a background color to the rows. And based on what we have done so far, you might be tempted to edit the DataTemplates used for the cells. Maybe you would think about adding a Border with a Background fill and placing this around the TextBlock for each cell:  

  <DataTemplate x:Key="IDCellTemplate2">

      <Border Background="LightGreen">

      <TextBlock Foreground="MediumBlue"

                FontFamily="Calibri"

         Text="{Binding Path=ProductID}" />

      Border>

    DataTemplate> 

I won't waste the space showing the markup for all three templates here, but if you did try this you will get a disappointing result:

Pretty ugly, I think you'll agree. Playing around with the Margin or Padding won't get you any further either.

The answer is to use the ItemContainerStyle property of the ListView. This opens up a number of choices for you. Firstly, if you would like to still have a gap between each of the columns - but an even gap - then you can take the following approach:  

      <ListView.ItemContainerStyle>

        <Style TargetType="ListViewItem">

          <Setter Property="HorizontalContentAlignment" Value="Stretch" />

        Style>

      ListView.ItemContainerStyle> 

This will produce the following output, which is an improvement:

If you want the light green to spread across the whole row, then you still use the ItemContainerStyle, but this time you set the Background property of the ListViewItem:  

      <ListView.ItemContainerStyle>

        <Style TargetType="ListViewItem">

            <Setter Property="Background" Value="LightGreen" />

        Style>

      ListView.ItemContainerStyle> 

Now you get the result you are probably looking for.

 

If all that whiteness in the background is a bit too much for you, then of course you can blend another shade of green into the mix by setting the ListView's Background property. Using SeaGreen, for example, will produce this:

 

 

The final markup for the ListView looks like this:  

    <ListView Name="ProductsListView"

         ItemsSource="{Binding}"

           Margin="5,25"

              Background="SeaGreen">

      <ListView.ItemContainerStyle>

        <Style TargetType="ListViewItem">

            <Setter Property="Background" Value="LightGreen" />

        Style>

      ListView.ItemContainerStyle>

 

      <ListView.View>

        <GridView>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource IDColHeader}"

          CellTemplate="{StaticResource IDCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource NameColHeader}"

           CellTemplate="{StaticResource NameCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource PackageColHeader}"

           CellTemplate="{StaticResource PackCellTemplate}">

          GridViewColumn>

        GridView>

      ListView.View>

    ListView> 

The markup for the DataTemplates and Styles is the same as that shown in the previous blog, all of which I placed in the Application.xaml file (App.xaml for C# projects).

There are some other row formatting options I want to cover, but I will leave those for another day.

posted @ 1:17 PM

 

Sometimes it's the tiniest little changes that make you happy out of all proportion to the size of the change. While testing the WPF features in VS2010 I was totally thrilled to discover that at last when you type in the opening curly brace in the XAML Pane, you get an Intellisense list of useful choices. The top one, of course, is StaticResource. If I had a penny for every time I've laboriously typed out that name, I'd be a rich man!

The same feature also offers other commonly used properties such as Binding. And once you have entered 'Binding' and a space, you also get Path, again courtesy of Intellisense.

On the subject of DataBinding, which is a key feature in WPF of course, the Properties Pane has been improved. Now if you select a control such as a ListView, the ItemsSource property is available in the Properties Pane and you can select the Binding from the available choices:

 

 

Maybe I've missed a trick, though, because when I tried to drill deeper into the ListView components and looked at the binding for a GridViewColumn, there didn't seem to be a way to select a value for the DisplayMemberBinding. If in the XAML Pane I manually typed in a valid Path, i.e. a field from the data source behind the DataContext, then that would be shown in the Properties Pane. But I couldn't find an option to switch the Path to a different field within that dialog.

 

 

I quite liked the way you can now view and choose from all the Resources in scope. This example shows where I am building a ListView and using a CellTemplate, for instance:

 

 

I noticed that when using the Properties Pane in this way, it can have an annoying habit. You close the dialog window by clicking anywhere outside it (i.e. it doesn't have a close/x button). If you are careless about where you click, you will deselect the current element in the XAML Pane. Often, if you click in the Design Pane to deselect, you will be taken back to the root element. It would be nice if a close button is added to the dialog windows at some point.

You can also pick and assign a saved Style for the Style property of any element. In this example I am offered all the previously created styles which can be assigned to a TextBlock element:

Another super improvement in the Properties pane is the color picker feature. If you select a property which can be assigned a color (well, to be more accurate, a brush), then you can click on the little down arrow at the right hand side of the property in the Properties pane and a color picker dialog will appear:

 

 

This example shows the Background property of a TextBlock. You can play with the color picker until you have the exact look you want. if you've used Expression Blend you'll recognize this layout.

You can still select a named color if you want. The drop down list is at the bottom left of the color picker:

 

 

Overall, I like the new look of the VS2010 editor and the new features I've found so far.

posted @ 1:12 PM

Saturday, September 05, 2009 #

I've often thought that dealing with dates and times can sometimes be much more difficult than it should be. There is a bewildering range of choices, many of which seem to do pretty much the same thing and you can sometimes wonder which is the 'right' way. One good example of the multiple choices is identifying a time. I don't mean a TimeSpan - which is a period of time - but a single specific moment in time, such as 8 o'clock, that you want to isolate and maybe compare, manipulate or filter in some way.

You can of course take any DateTime instance and display only the time element by using ToShortTimeString or ToLongTimeString.

        TimeCheck = New DateTime

        TimeCheck = Now

        Console.WriteLine("TimeCheck =  " & TimeCheck.ToShortTimeString)

You can also drill down and pull out the hour, minute, second or any combination of those.

        TimeCheck = New DateTime

        TimeCheck = Now

        Console.WriteLine("TimeCheck Hour and Minute = {0}:{1}  ", _

           TimeCheck.Hour, TimeCheck.Minute)

Also available is the TimeOfDay property of the DateTime class, which - as you would expect - will return the time element. However this is a TimeSpan which in some cases can make it very fiddly to manipulate. It is also a ReadOnly property, so you can't use it to set a new time.

And by coincidence, only today I learned of yet another one - the TimeString property, which returns the current time in HH:mm:ss format.  But that is fixed to the current time, not some time point of your choice.

The TimeValue function offers a different approach. Although it gives the appearance of being just a time - e.g. 14:22:30 or 3:15 PM and so on - it is basically a full standard DateTime, but the date is always constrained to be 1st January in the year 0001. For most purposes when you use TimeValue it conveniently ignores that date, anyway.

You can extract the time value of any particular date and time by passing in a DateTime instance to the TimeValue function:

       Dim DT As DateTime = TimeValue(Now)

TimeValue returns a String, so there is no need to cast to any of the String formats to read it as text:

Console.WriteLine(DT)

If you run those last two lines of code, you may be surprised/disappointed to see that it still includes a date. However, remember that the original DateTime we passed in was the DateTime value Now. As you will see in the Console printout, the real value of today's date has been dropped and is replaced by the 01/01/0001 date.

TimeValue also allows you to manufacture a time. In the next example, a time of 1400 hours or 2pm is created:

        Dim TVTime As DateTime

        TVTime = TimeValue("14:00")

Note that unlike the overloaded constructors of the DateTime class, you don't have to include year, month and day - for the obvious reason that they would be ignored anyway.

Although I haven't done so, you can also include a value for Seconds to the time you create.

You can add or subtract elements of time from the currently stored time by using AddHours, AddMinutes, AddSeconds, etc

Finally, you can compare times. If you wanted, for example, to check if a particular deadline had passed you can compare the times extracted with TimeValue:

        Dim TVTime As DateTime

        TVTime = TimeValue("14:00")

        If TimeValue(Now) > TVTime Then

            Console.WriteLine("Passed deadline")

        Else

            Console.WriteLine("Not yet reached")

        End If

There is really nothing in TimeValue that can't be achieved by manipulating other properties and methods of the DateTime class, but in many situations it's a neat function that will make for easier, cleaner code.

posted @ 11:18 AM | Feedback (1)

In the first WPF ListView blog of this set, I used XML data binding and added some basic formatting to the Column Headers of the ListView. In the previous blog, a collection of objects was used as the data source. The formatting in that second example was a bit plain. So, in this blog I will look at some ways of breaking away from the standard monochrome ListView.

First, let's revisit those Column Headers. Instead of the plain block Yellow I used in the first example, we can use a Gradient Brush for the TextBlock background and place a matching color Border round the outside. The finished headers will look like this:

 

 

As before, it is best to try and centralize as much of the XAML for the GUI as possible. To do this we use DataTemplates and Styles.

First, there is a Style for the blue border which surrounds each column header TextBlock, which I have chosen to store in the Application.xaml file as an application wide Resource: 

    <Style x:Key="BlueBorder" TargetType="Border">

      <Setter Property="BorderBrush" Value="#FF6B93CC" />

      <Setter Property="BorderThickness" Value="4"/>

      <Setter Property="CornerRadius" Value="2"/>

      <Setter Property="Padding" Value="2"/>

   Style> 

There is a LinearGradientBrush which is used to give the TextBlock background the blue and white gradient look. Again I have put this in Application.xaml: 

    <LinearGradientBrush x:Key="SubtleBlue" EndPoint="0.476,-0.09" StartPoint="0.476,1.363">

      <GradientStop Color="#FF7A8EEC" Offset="0.013"/>

      <GradientStop Color="#FF6B93CC" Offset="1"/>

      <GradientStop Color="#FFF7F6F7" Offset="0.54"/>

      <GradientStop Color="#FFEDEEF4" Offset="0.46"/>

    LinearGradientBrush> 

The TextBlocks in the column headers also use a Style. This Style, as you can see, incorporates that LinearGradientBrush: 

    <Style x:Key="ColHeaderText" TargetType="TextBlock">

      <Setter Property="FontSize" Value="14" />

      <Setter Property="FontWeight" Value="Bold" />

      <Setter Property="Background" Value="{StaticResource SubtleBlue}" />

      <Setter Property="Foreground" Value="Black" />

      <Setter Property="Padding" Value="2" />

   Style> 

So far, we have Styles for the Border and the TextBlock. The next step is to use these styles in a DataTemplate for the Column Headers.  

    <DataTemplate x:Key="IDColHeader">

      <Border Style="{StaticResource BlueBorder}">

             <TextBlock Text="Product ID " Style="{StaticResource ColHeaderText}"/>

    Border>  

    DataTemplate>

 

    <DataTemplate x:Key="NameColHeader">

      <Border Style="{StaticResource BlueBorder}">

        <TextBlock Text="Product Name " Style="{StaticResource ColHeaderText}" />

      Border>

    DataTemplate>

 

    <DataTemplate x:Key="PackageColHeader">

      <Border Style="{StaticResource BlueBorder}">

        <TextBlock Text="Pack Size " Style="{StaticResource ColHeaderText}" />

      Border>

    DataTemplate> 

These three DataTemplates are essentially the same, the only difference being the text content. It would be possible to have only one DataTemplate for all the TextBlocks and use TemplateBinding to pass in the required text from the ListView markup, but I thought I would try and keep things as simple as possible for you at this stage.

We now have everything we need in the way of resources to build the GUI of the ListView. Taking things one step at a time, here is the first pass at the ListView markup: 

    <ListView Name="ProductsListView"

         ItemsSource="{Binding}"

           Margin="5,25"  >

      <ListView.View>

        <GridView>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource IDColHeader}">

 

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource NameColHeader}">

 

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource PackageColHeader}">

 

          GridViewColumn>

        GridView>

      ListView.View>

    ListView> 

The data to be displayed comes from the bound DataSource. (This is covered in the previous blog item).

Each GridViewColumn uses its own HeaderTemplate to create the gradient TextBlock with blue border and appropriate text.

If you were to run this now, you will see that the headers have the right look, but the data isn't what you want:

This is because I haven't yet set the DataTemplates for each of the cells - that is, each item in each row. More specifically, I haven't set the appropriate Binding that will link the correct field in the data source to the column.

I will do this by means of another DataTemplate. As well as fixing up the Binding, I'll play with the text settings, so you can see how easy it is to create a different look for each column, if you need to. In this case, I've decided that I'll make all the data text Blue, but will make the detail of the Product Names stand out.

Here are the three DataTemplates: 

    <DataTemplate x:Key="IDCellTemplate">

      <TextBlock Foreground="MediumBlue"

                FontFamily="Calibri"

         Text="{Binding Path=ProductID}" />

    DataTemplate>

 

    <DataTemplate x:Key="NameCellTemplate">

      <TextBlock Foreground="DarkBlue" FontWeight="Bold"

         Text="{Binding Path=ProductName}" />

    DataTemplate>

 

      <DataTemplate x:Key="PackCellTemplate">

      <TextBlock Foreground="MediumBlue"

         Text="{Binding Path=PackageType}" />

    DataTemplate> 

So, the final step is simply to point to these DataTemplates from the GridViewColumn's CellTemplate property. The ProductID column, for example:  

 CellTemplate="{StaticResource IDCellTemplate}" 

The final complete markup for the ListView is as follows: 

    <ListView Name="ProductsListView"

         ItemsSource="{Binding}"

           Margin="5,25"  >

      <ListView.View>

        <GridView>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource IDColHeader}"

           CellTemplate="{StaticResource IDCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource NameColHeader}"

           CellTemplate="{StaticResource NameCellTemplate}">

          GridViewColumn>

         

          <GridViewColumn

           HeaderTemplate="{StaticResource PackageColHeader}"

           CellTemplate="{StaticResource PackCellTemplate}">

          GridViewColumn>

        GridView>

      ListView.View>

    ListView> 

And the finished look is:

This example only scratches the surface of the changes you can make to the look of the ListView. Some of them will take quite a lot more work (more than it should, you may think) and I will look at those in future blogs.

You may have noticed in the examples that by default the column widths are set to a size that allows the widest item to be displayed. Of course, the user can resize the column widths at run time and a useful trick to know is this: If the column width is too small for all the data to be read, double-clicking on the divider between the two columns will cause the column to the left to resize. All its data will then be visible again. It's a little weird that you have to click on the divider, not the column header, but it works just fine.

NB. Another thing to note: If you don't want to re-run the project after each change, sometimes you will need to Rebuild the solution to get the new look to appear in the Design Pane.

posted @ 11:03 AM | Feedback (1)

Friday, August 28, 2009 #

In a previous Blog, I showed how to databind an XML file to a WPF ListView. As some people are more comfortable with collections of objects than they are with XML, in this blog item I thought we could look at binding to a collection.

One difference to note is that if you use XML data and XPath, you have the benefit of seeing all the data in the Design Pane at design time. With this collection of objects approach, the data is being created on the fly, so of course it can't be seen at design time because it doesn't exist. It isn't usually a problem, but if you have become used to seeing the data at design time, this can be disconcerting at first.

Creating a Collection of Objects
Constructing a class that you can use to create objects is exactly the same as with Windows Forms. Here is a simple class named DrinkProduct:

Public Class DrinkProduct

 

    Sub New(ByVal ProductID As String, ByVal ProductName As String, ByVal PackageType As String)

        Me.ProductID = ProductID

        Me.ProductName = ProductName

        Me.PackageType = PackageType

    End Sub

 

    Private _ProductID As String

    Public Property ProductID() As String

        Get

            Return _ProductID

        End Get

        Set(ByVal value As String)

            _ProductID = value

        End Set

    End Property

 

    Private _ProductName As String

    Public Property ProductName() As String

        Get

            Return _ProductName

        End Get

        Set(ByVal value As String)

            _ProductName = value

        End Set

    End Property

 

    Private _PackageType As String

    Public Property PackageType() As String

        Get

            Return _PackageType

        End Get

        Set(ByVal value As String)

            _PackageType = value

        End Set

    End Property

 

End Class

The next step is to create a collection of DrinkProduct objects. Again, there is nothing new here:

    Public Function StockCheck() As List(Of DrinkProduct)

        Dim CurrentProducts As New List(Of DrinkProduct)

        With CurrentProducts

            .Add(New DrinkProduct("CF1kg", "Instant Coffee", "1 Kg"))

            .Add(New DrinkProduct("CFG500g", "Ground Coffee", "500 g"))

            .Add(New DrinkProduct("Te500g", "Tea", "500 g"))

            .Add(New DrinkProduct("SMlk1lt", "Skimmed Milk", "1 Litre"))

            .Add(New DrinkProduct("HiJ300g", "HiJuice Drink Mix", "300 g"))

        End With

 

        Return CurrentProducts

    End Function

Where you place the above function is a matter of choice, depending on what kind of scope you want it to have within the application. I've chosen to place it in a helper module named modStockControl so that it is available application wide.

The next step includes a small change. The link between that collection of objects and the ListView that will display them in will be a DataContext. This is very much like the DataSource object that you will be familiar with from Windows Forms. In the code-behind for the Window, insert the following code:

    Dim CurrentProducts As New List(Of DrinkProduct)

 

    Private Sub Part2_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        CurrentProducts = StockCheck()

        ProductsListView.DataContext = CurrentProducts

    End Sub

Clearly, all this does is create an empty List, then generates some data to populate the List. The final line sets the DataContext of the ListView specifically to be the that List. At the risk of confusing the issue at this early stage, it isn't necessary to bind directly to the ListView. I could have set the DataContext on the Window or the Grid, for example and it may still be accessible by the ListView. This is something I will cover in a future blog.

Let's turn our attention to the ListView markup. A skeleton version is:

    <ListView Name="ProductsListView"

         ItemsSource="{Binding}">

      <ListView.View>

        <GridView>

          <!-- Product ID -->

          <GridViewColumn

         Header="ProductID" >

            <GridViewColumn.CellTemplate>

              <DataTemplate>

              <TextBlock Text="{Binding Path=ProductID}" />

              </DataTemplate>

            </GridViewColumn.CellTemplate>

          </GridViewColumn>

 

        <!-- Remaining two columns removed for brevity -->

 

        </GridView>

      </ListView.View>

    </ListView>

As you can see in the markup, the ListView is named and this name is the one we used in the code-behind to link to the DataContext. Even more crucially, the ItemsSource property is set to point to that same DataContext. Even though it only contains the word "Binding", WPF is smart enough to work out which particular binding is the appropriate one. So those two properties are the glue that enables the ListView to be populated with DrinkProduct objects.

The remaining markup creates a View and in that View there are three GridViewColumns (although I have only shown the markup for the first one). Inside the GridViewColumn markup you see a CellTemplate and a DataTemplate, both of which are simply devices for packaging the look of the data. In this case, a basic TextBlock is used to house the text data.

The line of markup:

 <TextBlock Text="{Binding Path=ProductID}" />

is the final piece of the Binding puzzle. The pointer to the "Binding" ensures that WPF looks back up the tree to find the source of the data that has been set. (In this case, it looks no further than the ItemsSource which in turn knows that the data will come from that collection of DrinkProduct items.)

The Path identifies the exact field in the data source that is to be bound to this column. For this column it is the ProductID field.

So, as you can see from the few steps we have taken above, data binding the ListView to a data source is a trivial task.

At the moment, the GUI isn't too impressive, because I've stripped out everything but the basics:

   

I originally intended to look at several other tweaks that you can make to the look and layout of WPF ListViews. But to keep this blog to a reasonable length (and so as not to confuse the data binding technique with other peripheral stuff) I'll cover that in my next blog.

posted @ 3:22 PM

Tuesday, August 25, 2009 #

 A recent question here on VBCity came from a member who was searching for a way of changing the background color, font and border of the Column Headers in a ListView. This has always been a particularly tough call in Windows Forms. (A DataGridView, on the other hand, does have this feature, so that might often be an easy workaround.)

But, as usual when questions of difficult layout come up, my mind turns to WPF as a possible solution. Usually I would say 'an easy solution', but in this case honesty forces me to say that I've always found the WPF ListView to be one of its less user-friendly elements. Windows Forms certainly makes it easier to create data by hand, with the ability to add sub-items via the properties window. WPF effectively forces you to use data binding as the means of populating the ListView - although the data source can be a relatively simple collection of objects.   So I thought it might be useful to blog how to create a relatively uncomplicated ListView in WPF - one with a differently colored Column Headers,of course.

There is quite a lot of repetition of the graphical characteristics of the various sub-elements of a WPF ListView - the Column Headers and the content of the columns themselves, for example. So, it is always worth spending the time to create Styles or Templates which can be reused. Not only does this save time in the long run, it reduces the amount of markup used to create the actual ListView itself in the Window which usually makes it a little easier to read.

The first version isn't going to be too ambitious and will look like this:

  

Of course I could have added lots of other graphics junk in there, but I want to try and keep things as straightforward as possible. By the time we've worked our way through the Styles, Templates and XML Data Provider, I think that will be quite enough for one session. In a later blog, I plan to expand on this version.

The Basic ListView
The first step is to drag an empty ListView from the Toolbox and drop it on the XAML pane. Note that I say XAML pane, not the Design pane. As in this case, it is often easier to start with an empty element rather than have to edit the default property settings that you will see in the XAML if you drop it on to the Design pane.

In order to display the content, a WPF ListView requires the use of a View. This has the same role as the View property in the Windows Forms ListView, i.e. it controls the manner in which the data is laid out. The similarities end there, however. At the time of writing, the WPF ListView only has one choice of view - the GridView. In its basic form, this is similar to the WinForms ListView Details View, (except of course that WPF isn't limited in the way you can package and display the data).

As you can see from the following screenshot, even if you wanted to choose a value for the View property, this is something that has to be created in XAML. Future versions of WPF may perhaps increase this choice, but WPF already gives you the freedom to use the equivalent of Large Icon, Small Icon, List, etc, if that is the look you want, so maybe not.

  

The markup to create the View is simple: 

      <ListView >

         <ListView.View>

             <GridView>

 

             </GridView>

         </ListView.View>

       </ListView>

 There will be very little to see in the Design Pane yet. The next step is to add some columns. Add three columns to the GridView of the ListView:

                <GridView>

            <GridViewColumn Width="85">

            </GridViewColumn>

            <GridViewColumn></GridViewColumn>

            <GridViewColumn></GridViewColumn>

        </GridView>

 If you check the Design pane now, you will see a fine outline of the Column Headers. There is a divider after the first column, because I have set a Width value on it. The other two columns are not visible because they currently have a zero width.

  

Create a Reusable Style
Each of the three Column Headers will have some properties that are set to the same values as each other. Therefore it makes sense to set those property values in one place and assign them to each Column Header. The alternative approach would be to repeat virtually the same XAML three times, which clearly isn't a sensible way forward. WPF Styles is the technique which makes this very easy to implement.

In this simple example I am going to use a TextBlock to hold the text of the Column Header. The following markup, which is placed in the Application.xaml file (for VB) or App.xaml file (for C#) creates a Style for a TextBlock:  

    <Style x:Key="ColHeaderText" TargetType="TextBlock">

      <Setter Property="Width" Value="110" />

      <Setter Property="Height" Value="29" />

      <Setter Property="FontSize" Value="14" />

      <Setter Property="FontWeight" Value="Bold" />

      <Setter Property="Background" Value="Yellow" />

      <Setter Property="Foreground" Value="Navy" />

    </Style>

 If you're not familiar with the concept of Styles, all it does is set values on an assortment of TextBlock properties. The Style is assigned a key - in this case 'ColHeaderText'. This Style can now be applied to any TextBlock in the application.

The markup for the ListView can now be extended to include a Header that contains a TextBlock:  

 <GridViewColumn Width="85">

             <GridViewColumn.Header>

              <TextBlock Text=" Product ID"

              Style="{StaticResource ColHeaderText}"  />

            </GridViewColumn.Header>

          </GridViewColumn>

 The TextBlock created by this markup has Text content of 'Product ID' and its color, font, etc are all set by the values stored in the Style. You can see the result in the Design pane screenshot below.

 

  

In the final version, I have added similar markup for the remaining two columns. I have left them out of the snippet above for brevity.

Populating with Data
As I mentioned earlier, you need to use some form of data binding to populate the ListView. In this example I am using a simple XML file. You can view this file here. The markup that creates the link between the application and the XML file is straightforward:

    <XmlDataProvider x:Key="ProductList" Source="Products.xml" />

It uses an XMLDataProvider which I've keyed as 'ProductList' so that it can be referred to elsewhere in the project. The source data comes from the Products.xml file, which is located with the other project files in Solution Explorer.

Now that we have a data source, the ListView's ItemsSource property can be set to point to it. The markup is a bit tortuous, but not as complex as it might first appear. Essentially, the ItemsSource property is assigned a Binding and that Binding links to the ProductsList data provider. From the ProductsList, XPath syntax is used to point directly to the Product elements in the XML file. XPath isn't always the easiest syntax to use, but in the case of our simple XML file this is relatively straightforward.  

ItemsSource="{Binding Source={StaticResource ProductList}, XPath=Products/Product}" 

Next, the various columns can be bound to the appropriate fields. The GridViewColumn has a DisplayMemberBinding property which , as its name implies, sets the Binding to be used for the content of the column. Once again, XPath is used for this.  

   DisplayMemberBinding="{Binding XPath=ProductID}" 

In the above snippet, DisplayMemberPath is assigned a Binding which links back to the ProductID element of the Products.xml file. (Note: If the field in the data source is an XML Attribute, as opposed to an Element, it is necessary to add a leading @ symbol to the XPath name.)

For this basic ListView, that's all that is needed. You can view the Application.xaml file here, and the markup for the Window here. In a future blog, I'll improve this basic version and look at some other functionality, but if you haven't previously dealt with WPF ListViews I hope this will get you started.

posted @ 9:00 PM | Feedback (2)

One small but sometimes useful new feature that was bundled with Service Pack 1 (SP1) of Visual Studio 2008 is the Splash Screen feature of WPF. This enables you to create an image file which is then used as splash while the main application spins up and loads.

Probably the main selling point of this feature is its ease of use. Here are the steps involved:

 Create or select a suitable image file

  1. Add it to the project in the Solution Explorer.
  2. Left-click on the file name in Solution Explorer to select it
  3. Set its Build Action to Splash Screen.

 I chose to use a simple image with some text, but you can be as artistic as you like

At its simplest, that's really all there is to it. If you run the project now, you will see the splash screen appear, followed by the main startup form of the application. If you have a fast machine and a small project, the length of time the splash screen appears may be very short.

This isn't necessarily a problem. After all, the idea is usually to reassure the user that something is happening in the background. If the boot up time is short, then maybe you don't need a splash screen at all.

Of course, you may not know the speed of systems on which your application is going to be installed. Or you may have an opening message that you particularly want to display in any event. In that case, you need some way of controlling how long the splash screen stays on view. And as you probably guessed, this feature is also available.

Remembering that the splash screen is shown at the very start of the application life cycle, it makes sense for the code to be placed in the Application.xaml.vb file. Specifically, in the Application_Startup event.

There are three elements to the code required.

  • The first step is to create a variable for the required splash screen.
  • The second step is to turn off the AutoClose option of the splash screen (this being the option that you will have seen if you followed the steps first described above).
  • Finally, you use the Close method of the splash screen, but set a TimeSpan for the delay before the splash screen totally disappears.

 That expression 'totally disappears' bears a little more explanation. What actually happens is that the splash screen fades from an Opacity level of 1 (fully opaque) to a level of 0 (completely transparent) over the period set by the TimeSpan.

Here is the code:

     Private Sub Application_Startup(ByVal sender As Object, ByVal e As System.Windows.StartupEventArgs) Handles Me.Startup

        Dim splash As New System.Windows.SplashScreen("LoadingScreen.png")

        splash.Show(False)

        splash.Close(New TimeSpan(0, 0, 6))

  

  End Sub

 The above snippet displays the splash screen for 6 seconds.

In most cases, the splash screen works best if you just use it in those cases where you genuinely have, or expect, a delay in the startup. One problem otherwise is that you have to start fiddling with the timing and possibly the opacity of the display of the startup Window so that it synchs with the splash screen. If you don't, then the startup Window may appear (fully opaque) while the splash screen is still gently fading out. This generally doesn't look right. But for a straightforward "Don't worry, this application is working" message to users, the WPF Splash Screen is great.

If you haven't yet installed SP1, you can access it here.

posted @ 8:57 PM | Feedback (0)