z33k
z33k

Reputation: 3636

How to trigger a ListBoxItem's style change on the underlying object state change?

I have a basic setup of a ListBox with its ItemSource property set to ObservableCollection<Human>.

<ListBox ItemsSource="{Humans}" DisplayMemberPath="Name">
  <ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <!-- Some setters -->
    </Style>
</ListBox>

Human is defined like this:

public class Human 
{
  public string Name { get; set; }
  public bool IsAnswered { get; set; }

  public override string ToString() => this.Name;
}

So we have a Human object living as a source of each of the list box's items and the default behavior of its string representation (Name property in this case) displayed.

Now, I'd like the displayed Human.Name value to be formatted bold when IsAnswered changes to true. How to achieve this?

Upvotes: 1

Views: 471

Answers (1)

BionicCode
BionicCode

Reputation: 28948

The DataContext of the item container is always the data model, in your case the Human instance. Therefore simply bind to the DataContext:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsAnswered}" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>           
</ListBox>

As already noted in the comments, you must let Human implement INotifyPropertyChanged. The property IsAnswered must raise the INotifyPropertyChanged.PropertyChanged event. Otherwise the changes of the property will not be propagated.

Upvotes: 2

Related Questions