我今天开始玩WPF,我遇到了一些关于绘制Visuals的问题
我有一个名为Prototype.cs的类,基本上它所做的就是以椭圆的形式绘制视觉效果。这里没什么棘手的。
class Prototype : FrameworkElement
{
// A collection of all the visuals we are building.
VisualCollection theVisuals;
public Prototype()
{
theVisuals = new VisualCollection(this);
theVisuals.Add(AddCircle());
}
private Visual AddCircle()
{
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
// Create a circle and draw it in the DrawingContext.
Rect rect = new Rect(new Point(160, 100), new Size(320, 80));
drawingContext.DrawEllipse(Brushes.DarkBlue, null, new Point(70, 90), 40, 50);
}
return drawingVisual;
}
}
但这是我感到困惑的地方。我正在通过xaml代码调用此类的构造函数,这对我来说是非常新的。它按预期工作,绘制了椭圆。但是我希望有一个班级的实例,我可以在我的程序中使用。
如果我自己删除了xaml代码并创建了我的对象实例,那么我的窗口中就不会绘制任何内容。即使我提供MainWindow作为我的VisualCollection的VisualParent参数它仍然不起作用。我想保留一些东西,以便我不需要在MainWindow.cs中开始创建我的视觉集合。我已经考虑过创建一个静态类来处理所有的视觉效果,但是有没有更简单的方法来实现它?
原型类的实例化:
public MainWindow()
{
Prototype pt = new Prototype(this);
InitializeComponent();
}
原型构造函数:
public Prototype(Visual parent)
{
theVisuals = new VisualCollection(parent);
theVisuals.Add(AddCircle());
}
答案 0 :(得分:0)
您可以为在XAML中创建的Prototype
实例分配名称
<Window ...>
<custom:Prototype x:Name="prototype"/>
</Window>
然后使用以下代码访问实例:
public MainWindow()
{
InitializeComponent();
prototype.DoSomething();
}
或者,您在代码中创建它并将其分配给Wondow的Content
属性:
public MainWindow()
{
InitializeComponent();
var prototype = new Prototype();
Content = prototype;
prototype.DoSomething();
}