Tôi đã xem một số bài viết cho thấy cách sử dụng AlternationIndex
với ListBox
es hoặc ListView
s, nhưng tôi đã dành một vài giờ cố gắng để có được màu nền xen kẽ trên lớp cơ sở ItemsControl
và không có gì có vẻ hiệu quả. Tất cả ListBox
mẫu tôi thấy sử dụng ListBoxItem
như các loại mục tiêu cho phong cách mà bộ nền dựa trên AlternationIndex
- như thế này từ MSDN:Làm thế nào để sử dụng AlternationIndex trong ItemsControls?
<Grid>
<Grid.Resources>
<Style x:Key="alternatingWithTriggers" TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="Blue"/>
<Setter Property="Foreground" Value="White"/>
<Style.Triggers>
<Trigger Property="ListBox.AlternationIndex" Value="1">
<Setter Property="Background" Value="CornflowerBlue"/>
<Setter Property="Foreground" Value="Black"/>
</Trigger>
<Trigger Property="ListBox.AlternationIndex" Value="2">
<Setter Property="Background" Value="LightBlue"/>
<Setter Property="Foreground" Value="Navy"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<ListBox AlternationCount="3" ItemsSource="{StaticResource data}"
ItemContainerStyle="{StaticResource alternatingWithTriggers}">
</ListBox>
</Grid>
Tôi muốn sử dụng ItemsControl
bởi vì tôi không muốn các chức năng lựa chọn và Tôi nghĩ rằng restyling một ListBox
để ẩn nó có thể không phải là sự lựa chọn tốt nhất.
Đây là một trong những điều tôi đã cố gắng:
<DataTemplate DataType="{x:Type vm:ObservableCollectionItem}">
<Grid>
<!-- some content here -->
</Grid>
</DataTemplate>
<!-- ... -->
<ItemsControl
ItemsSource="{Binding ObservableCollectionItems}"
AlternationCount="2"
>
<ItemsControl.ItemContainerStyle>
<Style>
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Grid.Background" Value="Red"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Grid.Background" Value="Blue"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
Vấn đề tôi thấy là cây thị giác có một danh sách các ContentPresenter
s có ItemsControl.AlternationIndex
luân phiên giữa 0 và 1, nhưng Grid
trong mỗi ContentPresenter
đã ItemsControl.AlternationIndex
thiết lập để 0.
có lẽ là một cái gì đó rõ ràng tôi đang thiếu ...
Đã hoạt động! Cảm ơn! Tôi tự hỏi nếu điều này tra cứu ràng buộc sẽ quy mô lớn ItemControls, nhưng may mắn thay tôi không phải là trường hợp. –
Ví dụ thứ hai hoạt động, ví dụ đầu tiên không, vì ContentPresenter không * không * có thuộc tính 'Background'. – Will
Giống như tôi nói ngay trước ví dụ;) – Bubblewrap