Is it a good practice to use static classes to making the UI elements accessible from all the classes in .NET?

别来无恙 提交于 2019-12-13 15:23:02

问题


Please let me know which of the following is a good programming practise:

1. Using a static class and then using a reference to it from the class MainWindow constructor as shown:

    public partial class Mainwindow : Window
    {
    public MainWindow()
    {
        InitializeComponent();
        UI.window = this;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {   
        Shutdownads attempt1 = new Shutdownads();
    }
    }

    static class UI
    {
        public static MainWindow window; 
    }

    /*and then refering to the wpf elements from other classes as follows
       UI.window.textbox.Text="blahblah"
       UI.window.button ... and so on
    */

or

2. Is it better to include all the classes in my program in the MainWindow class?

or

3. Is there a better option (that also implements better OOP as well as I can acccess UI through other classes)?


回答1:


It is usually poor practice to control UI elements from multiple classes.

You should create an interface that exposes methods and properties that abstract the UI from the other classes, and implement that interface in the MainWindow class.

The other classes can accept that interface as a constructor parameter or use it from a static class.




回答2:


I don't know exactly winforms. But you should follow the mvc model.

Usually you got your mainclass (your case mainwindow) which is the controller. So all views (subelements) are controlled from this class. The subelements may hold a reference to the mainwindow. The main class should be very slick. The model should be decoupled too of course. Static classes are bad practice. Don't.




回答3:


good practice is to create code which is not coupled. If you work with this approach it will be very possible that you lose track where you commit your changes...

a possibility to react on "far" events is to implement an observer pattern. like that you handle the changes of the visualisation (in this case the MainWindow) truly on the presentation layer



来源:https://stackoverflow.com/questions/6142288/is-it-a-good-practice-to-use-static-classes-to-making-the-ui-elements-accessible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!