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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!