简体   繁体   中英

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.Triggers>
        </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));
    }

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM