你可以重用你的UI功能吗?

时间:2022-09-05 21:21:48

A simple example is a function I want to create.

一个简单的例子是我想要创建的函数。

private void drawRectangle(int x, int y)

I send coordinates and it draws a rectangle with some particularities. That function will be in at least two forms. What do you do to make that function reusable and prevent from writing it in two places?

我发送坐标,它绘制一个具有一些特殊性的矩形。该功能至少有两种形式。您如何使该功能可重复使用并防止将其写入两个位置?

Thank you!

谢谢!

3 个解决方案

#1


2  

For WinForms, pass the Graphics object to your method:

对于WinForms,将Graphics对象传递给您的方法:

private void drawRectangle(int x, int y, Graphics g)

Then draw the rectangle to the Graphics object.

然后将矩形绘制到Graphics对象。

#2


2  

You could add a third parameter, eg UIElement so that your method looks like this:

您可以添加第三个参数,例如UIElement,以便您的方法如下所示:

private void drawRectangle(int x, int y, UIElement space)

and let the method print the Rectangle on the specified space.

并让该方法在指定的空间上打印Rectangle。

#3


1  

Add another class to your project, add this method as a public static helper function. You'll need to provide more arguments, at least a Graphics object I imagine. A rectangle is also going to need a width and height. Avoid hard-coding these, it is rarely appropriate when your form gets rescaled on a machine with a higher video DPI setting.

在项目中添加另一个类,将此方法添加为公共静态助手函数。你需要提供更多的参数,至少是我想象的Graphics对象。矩形也需要宽度和高度。避免对这些进行硬编码,当您的表单在具有更高视频DPI设置的计算机上重新调整时很少适用。

#1


2  

For WinForms, pass the Graphics object to your method:

对于WinForms,将Graphics对象传递给您的方法:

private void drawRectangle(int x, int y, Graphics g)

Then draw the rectangle to the Graphics object.

然后将矩形绘制到Graphics对象。

#2


2  

You could add a third parameter, eg UIElement so that your method looks like this:

您可以添加第三个参数,例如UIElement,以便您的方法如下所示:

private void drawRectangle(int x, int y, UIElement space)

and let the method print the Rectangle on the specified space.

并让该方法在指定的空间上打印Rectangle。

#3


1  

Add another class to your project, add this method as a public static helper function. You'll need to provide more arguments, at least a Graphics object I imagine. A rectangle is also going to need a width and height. Avoid hard-coding these, it is rarely appropriate when your form gets rescaled on a machine with a higher video DPI setting.

在项目中添加另一个类,将此方法添加为公共静态助手函数。你需要提供更多的参数,至少是我想象的Graphics对象。矩形也需要宽度和高度。避免对这些进行硬编码,当您的表单在具有更高视频DPI设置的计算机上重新调整时很少适用。