【问题标题】:WPF ControlTemplate with foreach?带有foreach的WPF ControlTemplate?
【发布时间】:2011-09-28 08:19:26
【问题描述】:

我目前尝试为类似绘画的 WPF 应用程序创建类。我必须基类 LineMovement(从 StartPoint 到 EndPoint 的线)和 PathMovement(穿过 PointCollection 类型的属性 Points 中指定的所有点的线)。这些类继承自 Control,并通过 ControlTemplate 获取外观。

现在我想将(我称之为)PointMovers 添加到 ControlTemplate。这些应该是驻留在任一运动类中的每个点上的小视觉元素。它们应该成为一种抓取机制来拖动底层点。

问题当然是我不知道如何在 ControlTemplate 中创建可变数量的元素。如果我能做这样的事情会很酷:

<Style x:Key="{x:Type mov:PathMovement}" TargetType="{x:Type mov:PathMovement}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type mov:PathMovement}">
                <Grid>
                    <Polyline Points="{TemplateBinding Points}" />
                    <!-- interesting part start -->
                    <foreach loopvariable="Point" in="{TemplateBinding Points}">
                        <PointMover Point="Point" />
                    </foreach>
                    <!-- interesting part end -->
                </Grid>
           </ControlTemplate>
       </Setter.Value>
  </Setter>
</Style>

这可能吗?您是否有其他可行的方法?

提前致谢!

【问题讨论】:

    标签: wpf foreach controltemplate


    【解决方案1】:

    ItemsControlItemTemplate 结合使用:

    <ItemsControl ItemsSource="{Binding Points}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <!-- rendered for each point -->
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    根据您的用例,您可能还想阅读AdornerLayers。

    【讨论】:

    • 看起来不错。我要试试。但是,关于您对 AdornerLayers 的建议:我读到无法在 XAML 中指定它们,因此我不会使用它(不要将 XAML 和代码混合在一起,而不是绝对需要)。
    猜你喜欢
    • 2022-11-07
    • 1970-01-01
    • 2010-12-06
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多