簡體   English   中英

WPF使用C#類的實例繪制視覺效果

[英]WPF Drawing visuals with an instance of a class C#

我今天開始玩WPF,遇到了一些有關繪制視覺效果的問題

我有一個叫做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代碼在此類上調用構造函數,這對我來說是很新的。 它按預期工作,並繪制了橢圓。 但是我想要一個類的實例,以后可以在程序中使用。

xamlCode

如果刪除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());
 }  

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM