简体   繁体   English

为表单创建多个接口

[英]Making multiple interfaces for a Form

I have an application that I want to have 2 optional interfaces for: Touchscreen and Non-Touchscreen. 我有一个应用程序,我想有2个可选接口:触摸屏和非触摸屏。

I obviously can make 2 separate forms but there is a lot of underlying code that would have to be duplicated anytime there is a change to it. 我显然可以制作两个单独的表单,但是有很多底层代码,只要有更改就必须重复。 All the controls are the same, they just have different sizes and positions. 所有控件都相同,只是有不同的大小和位置。 I was thinking of putting in 2 InitializeComponent methods but then I would have no way of designing both interfaces with visual studio. 我想要放入2个InitializeComponent方法,但后来我无法用visual studio设计这两个接口。

Hoping someone else has any idea. 希望别人有任何想法。

I think that would be one interface with two implementations and then you inject the one you want into the form. 我认为这将是一个具有两个实现的接口,然后您将所需的一个注入到表单中。

A quick example: 一个简单的例子:

public interface IScreen
{
  void DoStuff();
}

public class TouchScreen : IScreen
{
  public void DoStuff()
  { }
}

public class NonTouchScreen : IScreen
{
  public void DoStuff()
  { }
}

public partial class ScreenForm : Form
{
  IScreen _ScreenType;

  public ScreenForm(IScreen screenType)
  {
    InitializeComponent();
    _ScreenType = screenType;
  }
}

And you would load it thus: 你会加载它:

  TouchScreen touchThis = new TouchScreen();
  ScreenForm form1 = new ScreenForm(touchThis);
  form1.Show();

  //or

  NonTouchScreen notTouchThis = new NonTouchScreen();
  ScreenForm form2 = new ScreenForm(notTouchThis);
  form2.Show();

You might be interested in looking at this (and related) questions: MVVM for winforms more specifically stuff related to WPF Application Framework (WAF) . 您可能有兴趣查看此(和相关)问题: MVVM for winforms更具体地说是与WPF应用程序框架(WAF)相关的东西。 One of the samples has a WinForms and a WPF UI sharing the same application logic. 其中一个示例具有WinForms和WPF UI,共享相同的应用程序逻辑。 In your case it would just be two different WinForms UIs sharing the same application logic. 在您的情况下,它只是两个不同的WinForms UI共享相同的应用程序逻辑。

Also, have you considered using a templating engine (something like T4 ) to just generate both forms? 另外,您是否考虑过使用模板引擎(类似于T4 )来生成两种形式?

If this is a winform, then you can add an event handler for Load event: 如果这是一个winform,那么您可以为Load事件添加一个事件处理程序:

this.Load += new System.EventHandler(this.YourForm_Load);

...and there you can check whether this is touchscreen or not, then arrange the positions, shapes and sizes in separate helper methods for the two cases. ...在那里你可以检查这是否是触摸屏,然后在两种情况下用不同的辅助方法排列位置,形状和大小。

private void YourForm_Load(object sender, System.EventArgs e)
{
  if (IsTouchScreen)
  {
    ArrangeControlsForTouchScreen();
  }
  else
  {
    ArrangeControlsForPlainScreen();
  }
}

If this is in a web page, then you can do pretty much the same in the overridden Page.Load method. 如果这是在网页中,那么您可以在重写的Page.Load方法中执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM