![](/img/trans.png)
[英]How to create a wpf template with nested datatemplate (datatemplate in datatemplate)
[英]WPF How to Create a DataTemplate Which has Canvas As Content By Code?
我有 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 是附加屬性
您還需要為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
};
}
請注意,使用FrameworkElementFactory
是一種不推薦使用的以編程方式創建模板的方法: https : //msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory(v=vs.110).aspx 。
以編程方式創建模板的推薦方法是使用
XamlReader
類的Load
方法從string
或內存流加載 XAML。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.