简体   繁体   English

Listview WPF:以编程方式添加背景色

[英]Listview WPF : Add bg color programatically

Hi I am trying to add color to bg of a listview item dynamically while runtime but I get the following exception. 嗨,我试图在运行时动态地向listview项目的bg添加颜色,但出现以下异常。

Unable to cast object of type 'RootObject.Controls.ListItem' to type 'System.Windows.Controls.ListViewItem'. 无法将类型为“ RootObject.Controls.ListItem”的对象转换为类型为“ System.Windows.Controls.ListViewItem”的对象。

My requirement is to check a condition while clicking a button and if the process is success change the bg to green else red. 我的要求是在单击按钮时检查条件,如果过程成功,则将bg更改为绿色,否则更改为红色。 Here is my WPF code 这是我的WPF代码

 <ListView x:Name="ListView" SelectionChanged="List_SelectionChanged" MouseDoubleClick="List_MouseDoubleClick"  SelectionMode="Single"/>

And here is my code behind, 这是我的代码,

if(RootVal.sendResult == true)
{                       
  foreach (ListViewItem item1 in ListView.Items)
      {
        item1.Background = System.Windows.Media.Brushes.Green;
      }
}

The Items property of the ListView does not contain controls, it contains your (view)models. ListView的Items属性包含控件,它包含您的(视图)模型。 (the ones you set as the ItemsSource) (您设置为ItemsSource的那些)

The proper way of going about this MVVM style would be to bind the background color from the DataTemplate of the ListView to a property of your (view)model. 进行这种MVVM样式的正确方法是将ListView的DataTemplate中的背景颜色绑定到您的(视图)模型的属性。

If you are still looking for a way to set the ListViewItem 's background color, take a look at How can I access the ListViewItems of a WPF ListView? 如果您仍在寻找一种设置ListViewItem的背景色的方法,请查看如何访问WPF ListView的ListViewItems?

(but be warned, they're not so easy to reach) (但请注意,它们并非那么容易到达)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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