c# – 如何覆盖ListView的ContentTemplate以添加垂直分隔符?
作者:互联网
我正在寻找修改WPF ListView以便项目水平呈现,并在第一个项目和所有后续项目之间有一个分隔符.像这样:
我有水平位,但我坚持使用分离器.我尝试使用DataTemplate,但这将分隔符合并到实际项目中,这意味着当我悬停时它会突出显示(注意我正在使用Caliburn,但我不认为它会影响这个问题):
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</UserControl.Resources>
<StackPanel Margin="20">
<ListView Name="Items" BorderThickness="0">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ContentControl cal:View.Model="{Binding}" />
<Border Name="Separator" Width="2" Margin="5,10" HorizontalAlignment="Center" Background="Red" Visibility="{Binding IsFirst, Converter={StaticResource BooleanToVisibilityConverter}}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
</StackPanel>
Items是具有此边框的非常基本的视图:
<Border Background="White" BorderBrush="Black" BorderThickness="2">
DataTemplate的外观如何:
早上读完模板后,我决定使用ControlTemplate解决方案,经过一番努力后给了我这个代码:
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<StackPanel Margin="10" Orientation="Horizontal">
<ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" />
<Border Name="Separator" Width="2" Margin="5,10" HorizontalAlignment="Center" Background="Red" Visibility="{Binding IsFirst, Converter={StaticResource BooleanToVisibilityConverter}}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<StackPanel>
<ListView Name="Items">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
</StackPanel>
这看起来几乎相同,但现在由于某种原因我无法突出显示项目.我想也许我已经覆盖了触发器,并尝试根据这个答案添加ControlTemplate.Triggers条目:Change selection-color of WPF ListViewItem以恢复突出显示行为,但没有成功.
如何获得我正在寻找的结果,ControlTemplate是否是进行此更改的正确位置?
编辑:理想情况下,我正在寻找一个使用xaml的解决方案.
解决方法:
这是使用分隔符的自定义面板的快速尝试
public class MyPanel : StackPanel
{
static MyPanel()
{
OrientationProperty.OverrideMetadata(typeof(MyPanel), new FrameworkPropertyMetadata(Orientation.Horizontal));
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (Children.Count >= 2)
{
var child = Children[0] as FrameworkElement;
if (child != null)
dc.DrawLine(new Pen(Brushes.Red, 2), new Point(child.ActualWidth + 2, 5), new Point(child.ActualWidth + 2, ActualHeight - 5));
}
}
}
像这样使用它
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<local:MyPanel/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
目前面板没有安排/测量子项为分隔符分配空间,您必须确保它们之间存在差距.
标签:c,wpf,listview,controltemplate 来源: https://codeday.me/bug/20190701/1349381.html