在我的Windows 8的Metro風格應用程序中,我將Listview綁定到ObservableCollection,我希望每個ListViewItem的背景顏色交替(白色,灰色,看到this page - 白色等)Metro應用程序 - ListView - 如何替代ListViewItems的背景顏色
<ListView x:Name="stopsListView" ItemsSource="{Binding}" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="66" >
<TextBlock Text="{Binding Title}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
在WPF中,這是使用樣式與觸發器來完成。
你如何在Metro應用程序中完成此操作?
更新:
正確答案以下給出後,我走了,實際上它編碼。這裏的任何人一些代碼誰需要它:
爲正值轉換器類代碼:
public class AltBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (!(value is int)) return null;
int index = (int)value;
if (index % 2 == 0)
return Colors.White;
else
return Colors.LightGray;
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
代碼XAML列表視圖:
<ListView x:Name="stopsListView" ItemsSource="{Binding}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="250" Height="66" Margin="5">
<Grid.Background>
<SolidColorBrush Color="{Binding IndexWithinParentCollection, Mode=OneWay, Converter={StaticResource AltBGConverter}}" />
</Grid.Background>
...,並在加入項目時收藏或修改收藏品,請記得在收藏品中設置其索引:
myCollection.add(item);
item.IndexWithinParentCollection = myCollection.Count;
當然,如果您的館藏經常變化,這種方法的維護成本會很高,因爲您必須重新爲您的項目建立索引,所以我發現在每個項目中存儲對父館藏的引用更容易,然後使用.IndexOf()即時計算索引,以避免每次收集更改時不斷更新索引值。
我想知道的是我自己,但你會如何打發行索引到轉換器?是否有一些XAML語法來做到這一點,還是我必須明確告訴每個對象它的索引在集合中是什麼? – 2012-08-17 17:27:12
您需要向對象添加屬性,是的。然後做一些像Background =「{Binding ItemIndex,Converter = {StaticResource ItemIndexToBackgroundConverter}}」 – 2012-08-17 17:33:04
這是正確的答案,謝謝。真的很遺憾,沒有XAML語法將項索引傳遞給轉換器。也許我可以設置項目來引用他們自己的父集合,並使用.indexOf--這種方法感覺它可能會破壞各種規則。 – 2012-08-17 20:37:10