在 DataTemplate 中应用时路径只出现一次

Path only appears once when applied in DataTemplate

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

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

我已经尝试使用 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>

是否有人对可能导致此行为的原因以及如何解决有任何想法?

自从使用 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>