WPF: Custom ListBoxItem with DataTrigger
I have a WPF ListBox
containing CheckBox
es. I would like the text colour of the TextBox
to change to red when the ViewModel notices that the bound value is now updated. I have the below XAML but it is not working. I can see the IsUpdated
property being queried but when the value is True
the colour is not changing. I'm sure I'm missing something obvious but can't quite figure it out.
<ListBox MinHeight="100" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Padding="2" SnapsToDevicePixels="true">
<CheckBox x:Name="_checkBox" IsChecked="{Binding Path=IsAllowed}" Content="{Binding Item}"/>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsUpdated}" Value="True">
<Setter TargetName="_checkBox" Property="Foreground" Value="Red"/>
</DataTrigger>
</DataTemplate.Trigger开发者_运维技巧s>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Are you implementing INotifyPropertyChanged (as mentioned by Matt Hamilton) in your Item class and raising the PropertyChanged event when you set IsUpdated from false to true and vice-versa.
public class Item : INotifyPropertyChanged
{
// ...
private bool _isUpdated;
public bool IsUpdated
{
get{ return _isUpdated; }
set {
_isUpdated= value;
RaisePropertyChanged("IsUpdated");
}
}
// ...
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if(PopertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
// ...
}
精彩评论