WPF ListView 实现根据 ItemSource 中对象的属性设置控件 Foreground或者BackgroundColor

xaml:

   <ListView Grid.Row="0" Grid.Column="2" Grid.RowSpan="3" x:Name="listBoxIds" SelectionMode="Single">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Variety}">
                                <TextBlock.Foreground>
                                    <SolidColorBrush Color="{Binding ForegroundColor}"/>
                                </TextBlock.Foreground>
                            </TextBlock>
                        </DataTemplate>
                    </ListView.ItemTemplate>
    </ListView>

data:

    public class VarietyEx
        : INotifyPropertyChanged
    {
        public VarietyEx(Variety arg_v)
        {
            Variety = arg_v;
            Selected = true;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public Variety Variety { get; }        
        public bool Selected
        {
            get
            {
                return _selected;
            }
            set
            {               
                _selected = value;                           
                _NotifyPropertyChanged($"{nameof(ForegroundColor)}");
            }
        }
        public Color ForegroundColor => Selected ? Colors.Black : Colors.Gray;

        public override string ToString()
        {
            return Variety.ToString();
        }


        void _NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));            
        }

        bool _selected;
    }

code

 //declare: 
 ObervableCollection<VarietyEx> _vtVarietyEx = new ObservableCollection<VarietyEx>();
 //Usage:
 listBoxIds.ItemsSource = _vtVarietyEx;

其实主要Point就是在ListView的xaml中加入 Listview.ITemTemplate/DataTemplate/TextBlock/…..
主要xaml中的Binding xxxx 其中 xxxx对应这PropertyName,千万不要写错,vs没有提示,直接会显示空白……
另外要动态触发时只需要NotifyPropertyChanged(PropertyName)
在我的工程中实际是当data.Selected 发生变化时,我会在后台调用 _NotifyPropertyChanged(“ForegroundColor”) 使得wpf动态绘画

参考:
https://stackoverflow.com/questions/20806528/change-listviewitem-text-color
https://www.codeproject.com/Questions/705686/Change-the-forecolor-of-a-ListViewItem-in-WPF

猜你喜欢

转载自blog.csdn.net/norsd/article/details/82532112