简体   繁体   中英

Making multiple interfaces for a Form

I have an application that I want to have 2 optional interfaces for: Touchscreen and Non-Touchscreen.

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.

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) . One of the samples has a WinForms and a WPF UI sharing the same application logic. In your case it would just be two different WinForms UIs sharing the same application logic.

Also, have you considered using a templating engine (something like T4 ) to just generate both forms?

If this is a winform, then you can add an event handler for Load event:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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