Path在DataTemplate中应用时只出现一次

本文关键字:一次 DataTemplate 应用 Path | 更新日期: 2023-09-27 18:10:29

我需要重用一些矢量图像。我已经实现了这个使用样式的路径设置Data属性。

当此样式应用于设置为ListViewDataTemplate时,只有第一项实际显示路径。在我的调试过程中,路径在实时大纲中是可见的。设计时间,它确实显示在每个项目中。

我已经尝试使用x:Shared="False"使样式不共享,但是这会导致难以理解XBF generation error code 0x09c4.编译错误。

<!-- Path Style defined in a seperate resource dictionary -->
<Style x:Key="Icon" TargetType="Path">
    <Setter Property="Data" Value="F1 M32,32z M0,0z M8,7L8,8 8,9 5,9 4,9 4,10 4,24 4,25 5,25 27,25 28,25 28,24 28,10 28,9 27,9 24,9 24,8 24,7 23,7 19,7 18,7 18,8 18,9 14,9 14,8 14,7 13,7 9,7 8,7z M10,9L12,9 12,10 12,11 13,11 19,11 20,11 20,10 20,9 22,9 22,10 22,11 23,11 26,11 26,23 6,23 6,11 9,11 10,11 10,10 10,9z"/>
</Style>
<!-- DataTemplate defined in a seperate resource dictionary-->
<DataTemplate x:Key="ListViewItem">
    <ViewBox>
        <Path Style="{StaticResource Icon}" Fill="{StaticResource IconBrush}"/>
    </ViewBox>
</DataTemplate>
<!-- DataTemplate applied on a page -->
<ListView
    ItemTemplate="{StaticResource ListViewItem}"
    ItemsSource={Binding Items}>
</ListView>

有没有人知道是什么原因导致了这种行为以及如何解决?

Path在DataTemplate中应用时只出现一次

这是自Silverlight时代以来的一个已知问题。当在样式中使用时,Path将只实例化一次。与WPF不同的是,没有x:Shared="False"强制在每次请求时创建一个新实例。

那你还有三个选择。

首先,您可以直接在DataTemplate中使用Path

<DataTemplate x:Key="ListViewItem">
    <Viewbox>
        <Path Data="F1 M32,32z M0,0z M8,7L8,8 8,9 5,9 4,9 4,10 4,24 4,25 5,25 27,25 28,25 28,24 28,10 28,9 27,9 24,9 24,8 24,7 23,7 19,7 18,7 18,8 18,9 14,9 14,8 14,7 13,7 9,7 8,7z M10,9L12,9 12,10 12,11 13,11 19,11 20,11 20,10 20,9 22,9 22,10 22,11 23,11 26,11 26,23 6,23 6,11 9,11 10,11 10,10 10,9z" Fill="Red"/>
    </Viewbox>
</DataTemplate>

为了获得更大的灵活性,您还可以使用ContentControl来代替。

<Style x:Key="Icon" TargetType="ContentControl">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Path Fill="Red" Data="F1 M32,32z M0,0z M8,7L8,8 8,9 5,9 4,9 4,10 4,24 4,25 5,25 27,25 28,25 28,24 28,10 28,9 27,9 24,9 24,8 24,7 23,7 19,7 18,7 18,8 18,9 14,9 14,8 14,7 13,7 9,7 8,7z M10,9L12,9 12,10 12,11 13,11 19,11 20,11 20,10 20,9 22,9 22,10 22,11 23,11 26,11 26,23 6,23 6,11 9,11 10,11 10,10 10,9z"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
<DataTemplate x:Key="ListViewItem">
    <Viewbox>
        <ContentControl Style="{StaticResource Icon}"/>
    </Viewbox>
</DataTemplate>

最后一个可能是最好的,但它需要一些工作将Data属性更改为更具体的PathGeometry

<Style x:Key="Icon" TargetType="Path">
    <Setter Property="Data">
        <Setter.Value>
            <PathGeometry FillRule="EvenOdd">
                <PathFigure IsClosed="True" StartPoint="0,0">
                    <LineSegment Point="xxx,xxx" />
                    <LineSegment Point="xxx,xxx" />
                </PathFigure>
            </PathGeometry>
        </Setter.Value>
    </Setter>
</Style>