Click here to Skip to main content
15,068,929 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:

I have been programming in winForms for a few years and I have recently started to learn WPF.

Previously I could do this:

if (lv.Items[1].Text == "High")
     lv.Items[1].SubItems[1].Forecolor = Color.Red;

There does not appear to be a Subitem option in WPF, how do i achieve this?
Updated 3-Jan-14 4:23am

1 solution

WPF requires a paradigm shift in thinking. I started using WPF back in August (and I still have a lot to learn). However there is a lot of power in databinding and using viewmodels.

Here's some code I found to give you an idea of how to do it. At first it seems like a lot of extra work but once you get used to it, it's pretty great.

public class ItemVM : INotifyPropertyChanged // if you want runtime changes to be reflected in the UI
  public string Text {... raise property change in setter }
  public Color BackgroundColor {... ditto... }

Next create a list of such objects as a property in your DataContext so that your ListView can bind to it.

// e.g. MainWindow
    public IEnumerable<ItemVM> Items { get; set; }

Now all you need to do is bind your ListView to this collection and wire up the
DataContext of the UI properly
       <ListView x:Name="MyListView" ItemsSource="{Binding Items}" HorizontalContentAlignment="Stretch">
                    <TextBlock Text="{Binding Text}">
                        <SolidColorBrush Color="{Binding BackgroundColor}"/>
        <Button Click="Button_Click" Content="Go PaleGreen"/>

Now changing the background color is easy. Just set the property of the corresponding ItemVM object to the Color you want. e.g. to set all items to go PaleGreen

private void Button_Click(object sender, RoutedEventArgs e)
        foreach (var item in Items)
            item.BackgroundColor = Colors.PaleGreen;
Leung Yat Chun (Fainx) 5-Jan-14 3:32am
You can also setup a binding to the text (Low,Medium,High) and add a trigger in the style of ListViewItem...instead of color.
Replace Trigger with DataTrigger to bind to the ViewModel.

<Style TargetType="ListViewItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Trigger Property="Content" Value="Low">
<Setter Property="Foreground" Value="Green" />
<Trigger Property="Content" Value="Medium">
<Setter Property="Foreground" Value="Blue" />
<Trigger Property="Content" Value="High">
<Setter Property="Foreground" Value="Red" />


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900