如何从单独的类文件向WPF画布添加元素? [英] How do I add elements to a WPF canvas from a separate class file?

查看:130
本文介绍了如何从单独的类文件向WPF画布添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用C#语言编写一个函数,将椭圆绘制到在单独的Window1.xaml文件中创建的画布(canvas1).我尝试通过以下方式将Ellipse(node)添加到画布时出现问题:

canvas1.Children.Add(node);


canvas1在当前上下文中不存在.我需要知道如何在这种情况下访问canvas1.

I am trying to write a function in C# to draw an Ellipse to a canvas (canvas1) that I have created in a separate Window1.xaml file. My problem arises when I try to add the Ellipse(node) to the canvas via:

canvas1.Children.Add(node);


canvas1 does not exist in the current context. I need to know how to access canvas1 in this context.

推荐答案

如果从Window1后面的代码中调用函数,则可以将canvas作为参数传递给您的功能.

If your function is being called from the code behind of Window1 you can pass the canvas as a parameter to your function.

public void AddEllipse(Canvas canvas)
{
    ...
    ...

    canvas.Children.Add(node);
}



如果从其他代码中调用函数,则可以将画布公开为Window1的公共属性.



If your function is being called from some other code you can expose the canvas as a public property of Window1.

public Canvas Canvas1
{
    get
    {
        return canvas1;
    }
}



然后,通过Window1的任何实例,您都可以访问Canvas1属性并将其传递给函数.



Then through any instance of Window1 you can access the Canvas1 property and pass it to your function.


我将有问题的Canvas对象创建为静态(可全局访问)对象,并且
I would create the Canvas object in question as a static (and globally accessible) object, and just use the static instance wherever it''s needed.


我不确定这是否是询问有关答案的正确方法,但是谢谢您的答复. >
Rajitha,您的第一个解决方案已修复了相关错误,谢谢您!

约翰,我应该如何在XAML中将画布设为静态和全局?
I''m not sure if this is the proper method of asking questions about answers, but Thank you for your responses.

Rajitha, your first solution has fixed the related errors thank you!

John, how should I go about making the canvas static and global in XAML?


这篇关于如何从单独的类文件向WPF画布添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆