WPF如何创建一个DataTemplate,其中包含Canvas作为内容按代码?

时间:2018-02-12 02:53:25

标签: c# wpf xaml datatemplate

我有XAML定义的数据模板如下:

<DataTemplate x:Key="PointPushPinItemTemplate">
    <mapControl:MapItem mapControl:MapPanel.Location="{Binding}" >
        <Canvas>
            <Path StrokeThickness="2" Fill="Aqua">
                <Path.Data>
                    <EllipseGeometry RadiusX="10" RadiusY="10"/>
                </Path.Data>
            </Path>
        </Canvas>
    </mapControl:MapItem>
</DataTemplate>

我使用下面的代码创建它,但失败了:

private DataTemplate PushPinPointDataTemplate()
{
    var pointItemFactory = new FrameworkElementFactory(typeof(MapItem));
    pointItemFactory.SetValue(MapPanel.LocationProperty, new Binding());
    var pointCanvas = new Canvas();
    pointCanvas.Children.Add(new Path
    {
        StrokeThickness = 2.0,
        Fill = new SolidColorBrush(Colors.Yellow),
        Data = new EllipseGeometry {RadiusX = 3, RadiusY = 3}
    });

    //below line always throw exception that FrameworkElementFactory.SetValue can't set a visual value
    pointItemFactory.SetValue(MapItem.ContentProperty, pointCanvas);
    return new DataTemplate
    {
        DataType = typeof(Location),
        VisualTree = pointItemFactory
    };
}

如何实现这一目标?如果没有Canvas,我实现了这一点,但是对于这种情况,Canvas是内容控件的内容。 ps:mapControl:MapItem是一个继承自ListBoxItem的UI元素 mapControl:MapPanel.Location是附加属性

1 个答案:

答案 0 :(得分:1)

您还需要为import xml.etree.ElementTree as ET xml_data = """<xml> <child type = "smallHuman"/> <adult type = "largeHuman"/> </xml>""" # This is like ET.parse(), but for strings root = ET.fromstring(xml_data) for a child in root: print(child.tag, child.attrib) Canvas创建工厂:

Path

请注意,使用private DataTemplate PushPinPointDataTemplate() { var pointItemFactory = new FrameworkElementFactory(typeof(MapItem)); pointItemFactory.SetValue(MapPanel.LocationProperty, new Binding(".")); var pathFactory = new FrameworkElementFactory(typeof(Path)); pathFactory.SetValue(Path.StrokeThicknessProperty, 2.0); pathFactory.SetValue(Path.FillProperty, Brushes.Yellow); pathFactory.SetValue(Path.DataProperty, new EllipseGeometry { RadiusX = 3, RadiusY = 3 }); var pointCanvasFactory = new FrameworkElementFactory(typeof(Canvas)); pointCanvasFactory.AppendChild(pathFactory); pointItemFactory.AppendChild(pointCanvasFactory); return new DataTemplate { DataType = typeof(Location), VisualTree = pointItemFactory }; } 是以编程方式创建模板的弃用方式:https://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory(v=vs.110).aspx

  

以编程方式创建模板的推荐方法是使用FrameworkElementFactory类的string方法从Load或内存流加载XAML。