【发布时间】:2020-09-15 23:03:25
【问题描述】:
您有一个程序可以在运行时将任何对象添加到画布。我根据要求使用 ContentControl。 ContentControl 将附加到拖动、调整大小和旋转,这就是我们不能使用其他对象的原因。项目将在运行时添加,所有创建的控件将在最后添加到画布上。下面的代码简单地添加了两个对象,一个椭圆和一个几何。椭圆显示在画布中,但不显示几何。但是,如果直接添加到 XAML 中,则会显示。如果在代码中直接将路径添加为画布的子级,它也可以工作。请帮忙。添加到 ContentControl 时如何在运行时通过代码显示此几何形状。
不起作用
C#
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
AddItemsToCanvas();
}
void AddItemsToCanvas()
{
//add Ellipse
var contentControl = new ContentControl();
contentControl.Width = 130;
contentControl.Height = 130;
contentControl.MinHeight = 5;
contentControl.MinWidth = 5;
Canvas.SetTop(contentControl, 50);
Canvas.SetLeft(contentControl, 100);
var ellipse = new Ellipse { Fill = Brushes.Blue, Stretch = Stretch.Fill, IsHitTestVisible = false };
var border = new Border { Background = Brushes.Transparent, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch };
border.Child = ellipse;
contentControl.Content = border;
canvas.Children.Add(contentControl);
//add geometry. This doesn't work.
var contentGeomControl = new ContentControl();
contentGeomControl.Width = 130;
contentGeomControl.Height = 130;
contentGeomControl.MinHeight = 5;
contentGeomControl.MinWidth = 5;
Canvas.SetTop(contentGeomControl, 50);
Canvas.SetLeft(contentGeomControl, 100);
var streamGeometry = StreamGeometry.Parse("M150,300 L300,300 A150,150 0 0 0 256,194 z");
var path = new Path { Data = streamGeometry, Fill = Brushes.Wheat, IsHitTestVisible = false };
var borderGeom = new Border { Background = Brushes.Transparent, VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch };
borderGeom.Child = path;
contentGeomControl.Content = borderGeom;
canvas.Children.Add(contentGeomControl);
}
}
}
XAML
<Window x:Class="DiagramDesigner.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStartupLocation="CenterScreen"
Title="Move, resize and rotate"
Height="550" Width="750" Name="Win1">
<Window.Resources>
<Canvas Name="canvas" Background="White" Opacity="99">
</Canvas>
这可行,但我们需要在运行时添加项目
XAML
<Canvas Name="canvas" Background="White" Opacity="99">
<ContentControl>
<ContentControl.Content>
<Border >
<Path Fill="Wheat" Data="M150,300 L300,300 A150,150 0 0 0 256,194 z"/>
</Border>
</ContentControl.Content>
</ContentControl>
</Canvas>
【问题讨论】: