Reputation: 3238
this is tearing my hair out,
I have a listview
<ListView Canvas.Left="1045" Canvas.Top="667" FontSize="25" ItemsSource="{Binding Items}" FontFamily="Gill Sans MT" Height="173" Name="lvContact" Width="536" SelectionChanged="lvContact_SelectionChanged">
In my code behind im dynamically adding an item to the list
public void UpdateContactList(Hashtable contactList)
{
this.lvContact.Items.Clear();
SortedDictionary<string,string> sortedContactList = new SortedDictionary<string,string>();
foreach (DictionaryEntry de in contactList)
{
sortedContactList.Add(de.Key.ToString(), de.Value.ToString());
}
foreach (var de in sortedContactList)
{
System.Windows.Controls.ListViewItem contactItem = new System.Windows.Controls.ListViewItem();
string contactItemString = de.Key.ToString();
System.Windows.Controls.ListViewItem text = new System.Windows.Controls.ListViewItem();
text.Content = contactItemString;
if (de.Value == "NLN")
{
text.Background = Brushes.Green;
}
else
{
text.Background = Brushes.Gray;
}
lvContact.Items.Add(text);
}
}
However the background color never changes and the list doesnt update.
Any ideas why ? Many thanks
Upvotes: 0
Views: 1693
Reputation: 132658
ListViews can either be bound to an ItemsSource
, or you can specify the ListView.Items
manually. You cannot have both.
Your ListView definition binds your ListView.ItemsSource
, so you cannot manually specify ListView.Items
.
Since your ItemsSource
is bound to a property Items
, then I would assume you have a List<T>
or ObservableCollection<T>
somewhere called Items
with the items for your ListView. To modify the ListView's Items, you should be modifying this collection.
To change the Background color based on a value, I would use a DataTrigger. This will allow you to keep your ItemsSource bindnig, and keeps your data separated from your UI.
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Gray" />
<Style.Triggers>
<DataTrigger Binding="{Binding Value}" Value="NLN">
<Setter Property="Background" Value="Green" />
</DataTriggers>
</Style.Triggers>
</Style>
Upvotes: 1