【发布时间】:2012-08-17 17:07:08
【问题描述】:
在我用于 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 中,这是使用带触发器的样式完成的 - 请参阅 this page。
您如何在 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() 即时索引,以避免每次集合更改时都必须不断更新索引值。
【问题讨论】:
标签: .net xaml windows-runtime windows-store-apps winrt-xaml