Reputation: 381
Hi I am trying to add color to bg of a listview item dynamically while runtime but I get the following exception.
Unable to cast object of type 'RootObject.Controls.ListItem' to type '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. Here is my WPF code
<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;
}
}
Upvotes: 0
Views: 514
Reputation: 8643
The Items
property of the ListView does not contain controls, it contains your (view)models. (the ones you set as the 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.
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?
(but be warned, they're not so easy to reach)
Upvotes: 1