2011-12-13 73 views
0

這是撕裂我的頭髮,更改的ListViewItem的背景色填入

我有一個列表視圖

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

在後面的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); 
    } 
} 

但是,背景顏色不會改變,列表不會更新。

任何想法爲什麼? 非常感謝

+1

據我所知,您不能在ItemsSource模式下將項目添加到列表中,您需要更改項目源。 –

+0

我的xaml中的ListView的類型是System.Windows.Controls.ListView,這個綁定是不正確的? –

+0

如果你想改變你的列表視圖的內容,不管DataContext的'Item'屬性是什麼,或者不綁定這些itemsource,然後你就可以直接改變列表視圖項目。 –

回答

1

ListViews可以綁定到ItemsSource,也可以手動指定ListView.Items。你不能擁有兩個。

您的ListView定義綁定了您的ListView.ItemsSource,因此您無法手動指定ListView.Items

由於您的ItemsSource綁定到財產Items,那麼我會假設你有一個List<T>ObservableCollection<T>地方叫Items與物品您的ListView。要修改ListView的Items,你應該修改這個集合。

要根據值更改背景顏色,我會使用DataTrigger。這將允許你保持你的ItemsSource bindnig,並保持你的數據與你的用戶界面分開。

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