简体   繁体   English

更改填充时ListViewItem的背景颜色

[英]Change the background color of a ListViewItem on populate

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 在我后面的代码中,im动态地将项目添加到列表中

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 非常感谢

ListViews can either be bound to an ItemsSource , or you can specify the ListView.Items manually. ListView可以绑定到ItemsSource ,也可以手动指定ListView.Items You cannot have both. 不能同时拥有。

Your ListView definition binds your ListView.ItemsSource , so you cannot manually specify ListView.Items . 您的ListView定义绑定了ListView.ItemsSource ,因此您不能手动指定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. 由于您的ItemsSource绑定到属性Items ,所以我假设您在某个地方有一个List<T>ObservableCollection<T> ,称为Items ,其中包含ListView的项目。 To modify the ListView's Items, you should be modifying this collection. 要修改ListView的Items,您应该修改此集合。

To change the Background color based on a value, I would use a DataTrigger. 要基于值更改背景色,我将使用DataTrigger。 This will allow you to keep your ItemsSource bindnig, and keeps your data separated from your UI. 这将允许您保留ItemsSource bindnig,并使数据与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>

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

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