Solved

How do you conditionally format the items in a WPF Listbox

Posted on 2011-03-20
6
2,023 Views
Last Modified: 2013-11-12
Hi

I am starting to learn WPF and want to know how can you format the items in a Listbox conditionally based on content.  For instance, I have a procedure that adds items to the listbox.  Each item added will contain somewhere in the string either the substring Male or Female.  How can I dynamically change the font and the background of the listbox item based on the text string's contents?

Thanks
0
Comment
Question by:Vyyk_Drago
  • 3
  • 3
6 Comments
 
LVL 4

Expert Comment

by:grishav
ID: 35174511
Hi,
You can do it with DataTriggers in xaml.
You need to define a property in your code - say, named Gender (in its getter you can return your substring, for example)
Then in XAML you can write something like this:


<ListBox ....> 
	<ListBox.ItemContainerStyle> 
		<Style TargetType="{x:Type ListBoxItem}">
			<Style.Triggers>
				<DataTrigger Binding="{Binding Path=Gender}" Value="Male">
					<Setter Property="Background" Value="Red" />
				</DataTrigger>
				<DataTrigger Binding="{Binding Path=Gender}" Value="Female">
					<Setter Property="Background" Value="Green" />
				</DataTrigger>
			</Style.Triggers>
		</Style>
	</ListBox.ItemContainerStyle> 
</ListBox>

Open in new window

0
 

Author Comment

by:Vyyk_Drago
ID: 35175190
Hi grishav

Thanks - just one question since I am totally a n00b and also still vinding my way in VB .NET - after adding the XAML code as you suggest, where do I define the Gender property?  I suppose this property has to be related to my ListBox somehow?

Thanks
Vyyk
0
 
LVL 4

Expert Comment

by:grishav
ID: 35175264
I suppose that each item in your list box is instance of some class which you defined in a code-behind.
If it is so, than you need to add the property to that class.
If not, probably you should post the code where you give the content to your listbox.
How do you define what to show in it?
Is it
<ListBox ItemsSource=some_collection_of_your_objects ... ?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:Vyyk_Drago
ID: 35175507
Hi

The class looks like this:

Public Class RecitalReaderWriter

    Public ReadOnly Property Recital(ByVal strPerformancePath As String) As Collection
        Get
            Dim srPerformanceReader As System.IO.StreamReader
            Dim colRecitalLines As New Collection

            srPerformanceReader = File.OpenText(strPerformancePath)

            While srPerformanceReader.Peek <> -1
                colRecitalLines.Add(srPerformanceReader.ReadLine())
            End While

            Return colRecitalLines
        End Get
    End Property

Open in new window


The Property is called like this:

 
Private Sub btnOpenPerformance_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnOpenPerformance.Click

        Dim ofdlg As New Microsoft.Win32.OpenFileDialog

        With ofdlg
            .Multiselect = False
            .DefaultExt = ".txt"
            .Filter = "Text Documents (.txt)|*.txt"
            If .ShowDialog = True Then
                colRecitalLines = rctlrdwr.Recital(.FileName)
                lbPerformance.ItemsSource = colRecitalLines
            End If
        End With

    End Sub

Open in new window


I have added the xaml below to my Listbox definition:

 
<ListBox Name="lbPerformance">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Recital}" Value="female">
                                <Setter Property="Background" Value="Orange" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding Path=Recital}" Value="male">
                                <Setter Property="Background" Value="Green" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                 </ListBox.ItemContainerStyle>
            </ListBox>

Open in new window


However, even though the items are added successfully added to the lisbow, the formatting is not applied to relevant items.  I cannot figure out what I am doing wrong :(

Thanks
V
0
 
LVL 4

Accepted Solution

by:
grishav earned 500 total points
ID: 35175594
I think you need to understand more how data binding works in WPF.
Here is good page to start with:
http://msdn.microsoft.com/en-us/library/ms750612.aspx

Basically, you read from file one line at a time and add each string you get to the collection "as is".
Instead, you must define some data class (called RecitalLine, for example).
In this class you can also define properties (such as Gender).
You can also override toString method if all you want in ListBox is a textual representation  of RecitalLine.
Than you will define new instance for this class based on each line you read from the file.
Than you'll add all instances of  RecitalLine (and not the plain strings) to the collection.
Now, in ItemContainerStyle in Xaml you need to style each item according to properties of this specific item - for example, Gender. So you need to write {Binding Path=Gender}. Not {Binding Path=Recital}
(unless, of course, you will define property named Recital in each RecitalLine - which is not what you meant I think)

It is hard to understand what code to write, when you don't understand what is bound to what.
I really recommend that you start with the article I mentioned in the beginning (or just google for 'WPF data binding') - before you write the code.
Good luck.
0
 

Author Closing Comment

by:Vyyk_Drago
ID: 35176167
Thanks for the awesome help!  Never could have worked this out without your help!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now