如何将分隔符添加到列表框项,而不受项模板的影响
本文关键字:影响 分隔符 添加 列表 | 更新日期: 2023-09-27 18:20:47
下面你可以看到视图和视图模型。结果将是:"A B C",每个字母的背景都是红色的。我想在项目之间添加一个箭头,但我不希望箭头被红色着色。这意味着它应该是这样的:"A --> B -> C",只有字母会被红色着色,而箭头会变成NOT。我可以使用转换器在文本上添加箭头,但它最终也会为箭头着色。
任何想法 ?
Xaml:
<ListBox ItemsSource="{Binding MyArray}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Background="Red" Text="{Binding}" Margin="5"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码隐藏:
public class MainWindowViewModel
{
public MainWindowViewModel()
{
MyArray = new ObservableCollection<string>();
MyArray.Add("A");
MyArray.Add("B");
MyArray.Add("C");
}
public ObservableCollection<string> MyArray { get; set; }
}
你可以很容易地做到这一点:
<TextBlock Margin="5">
<Run Background="Red" Text="{Binding}"/>
<Run Text="->"/>
</TextBlock>
或者,如果您确实必须将其排除在数据模板之外,请使用ItemContainerStyle
并为ListBoxItem
分配一个新Template
,该在项模板所在的ContentPresenter
旁边包含一个箭头(这可能是一个好主意,因为这样您就可以阻止箭头被选中(。
编辑:我会使用带有PreviousData
绑定的附加箭头来解决问题,如果它为 null,则它之前没有项目:
<DataTemplate>
<!-- StackPanel because Runs can't be collapsed, you could clear their text though -->
<StackPanel Orientation="Horizontal">
<TextBlock Text="->">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource PreviousData}}"
Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Text="{Binding}" Background="Red" />
</StackPanel>
</DataTemplate>
如果您
知道集合中的最大项目数,则可以将ListBox
AlternationCount
设置为大于集合中项目数的数字,然后使用DataTrigger
来确定分隔符项目的可见性或文本。
<Style x:Key="ArrowTextBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="->" />
<Style.Triggers>
<DataTrigger Value="0" Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=(ItemsControl.AlternationIndex)}">
<Setter Property="Text" Value="" />
</DataTrigger>
</Style.Triggers>
</Style>
<ListBox AlternationCount="100" ItemsSource="{Binding MyArray}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="5">
<TextBlock Style="{StaticResource ArrowTextBlockStyle}" />
<TextBlock Text="{Binding }" Background="Red" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
编辑
正如HB在他的回答中指出的那样,你也可以将你的DataTrigger
基于RelativeSource.PreviousData,但是这只有在你ItemsSource
中的任何项目都没有null
时才有效。