Color a WPF ListBox item based on a property

后端 未结 2 1724
-上瘾入骨i
-上瘾入骨i 2020-12-12 04:50

I have an observable collection of Song objects. These song objects have a property called \"Playing\" that is a bool (bad naming, I know). The songs display in a ListBox in

2条回答
  •  伪装坚强ぢ
    2020-12-12 04:51

    Does your object with the Playing property implement INotifyPropertyChanged ? If it does, then your UI should auto-update based on the DataTrigger approach you are using.

    Another approach is to use ViewModels instead of Triggers (easier to understand and work with - when things don't go as expected) An example

    Update: Just looked at your code snippets. One thing I found - you need to trigger the event after you've applied the new value.

    public Color BackgroundColor
            {
                get { return _backgroundColor; }
    
                set
                {
                    _backgroundColor = value;
                    NotifyPropertyChanged("BackgroundColor"); // must be after so that new value is readable by the GUI
                }
            }
    

    Also the dataTemplate must be applied to the ItemTemplate property of the listbox

     
                    
    

    I basically changed the snippet from the example that I posted to use your song class and then modified the button click to toggle between 2 colors. (Also turned ListView into ListBox)

    private bool _isGreen = false;
            private void Button_Click(object sender, RoutedEventArgs e)
            {
    
                foreach (var item in Items)
                    item.BackgroundColor = (_isGreen ? Colors.Cyan : Colors.PaleGreen );
                _isGreen = !_isGreen;
            }
    

    My listboxes change color on every click! :)

提交回复
热议问题