【问题标题】:WPF Drawing visuals with an instance of a class C#WPF 使用类 C# 的实例绘制视觉效果
【发布时间】:2013-11-24 09:27:10
【问题描述】:

我今天开始玩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());
 }  

【问题讨论】:

    标签: c# wpf frameworkelement


    【解决方案1】:

    您可以为在 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-11
      • 2012-03-20
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多