【问题标题】:Change the background color of a ListViewItem on populate在填充时更改 ListViewItem 的背景颜色
【发布时间】:2014-08-30 20:54:45
【问题描述】:

这把我的头发扯掉了,

我有一个列表视图

<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">

在我背后的代码中,我动态地将一个项目添加到列表中

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);
    }
}

但是背景颜色永远不会改变,列表也不会更新。

任何想法为什么? 非常感谢

【问题讨论】:

  • 据我所知,在 ItemsSource 模式下无法将项目添加到列表中,您需要更改项目来源。
  • 我的 xaml 中的 ListView 的类型是 System.Windows.Controls.ListView 是否绑定不正确?
  • 如果您想更改列表视图的内容,请更改 DataContext 的“项目”属性包含的任何内容...或者不绑定项目源,然后您将能够直接更改列表视图项目。

标签: c# wpf listview listviewitem


【解决方案1】:

ListViews 可以绑定到ItemsSource,也可以手动指定ListView.Items。你不能两者兼得。

您的 ListView 定义绑定了您的 ListView.ItemsSource,因此您无法手动指定 ListView.Items

由于您的ItemsSource 绑定到属性Items,那么我假设您有一个名为ItemsList&lt;T&gt;ObservableCollection&lt;T&gt; 与您的ListView 的项目。要修改 ListView 的 Items,您应该修改此集合。

要根据值更改背景颜色,我会使用 DataTrigger。这将允许您保持您的 ItemsSource 绑定,并使您的数据与您的 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>

【讨论】:

    猜你喜欢
    • 2016-03-27
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2017-06-11
    • 2011-01-29
    • 1970-01-01
    • 2015-06-09
    相关资源
    最近更新 更多