Dot-Net
Metro 應用程序 - ListView - 如何替換 ListViewItems 的背景顏色
在適用於 Windows 8 的 Metro 風格應用程序中,我將 Listview 綁定到 ObservableCollection,並且我希望每個 ListViewItem 的背景顏色交替顯示(白色、灰色、白色等)
<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;當然,如果您的集合經常更改,這種方法的維護成本很高,因為您必須重新索引您的項目,所以我發現在每個項目中儲存對父集合的引用更容易,然後計算索引-the-fly 使用 .IndexOf() 避免每次集合更改時都必須不斷更新索引值。
您可以使用轉換器 - 從項目中獲取行索引並將其轉換為畫筆。此外 - 如果 ItemTemplate 沒有給您足夠的控制權 - 使用 ItemContainerStyle 在 ListViewItem 模板級別修改畫筆。
另一種選擇可能是指定一個 ItemTemplateSelector,它根據項目為您提供具有不同畫筆的不同模板。您仍然需要生成行索引,或者以某種方式啟用選擇器來確定項目是在偶數還是奇數位置。
我相信這裡的程式碼範例很有用 https://msdn.microsoft.com/en-us/library/ms750769(v=vs.85).aspx