简体   繁体   中英

C# winforms change usercontrol in panel as method

I am trying to make a method for change usercontrol when a button is clicked.

UserControl

namespace LogAnalyzer
{
    public partial class UserSettings : UserControl
    {
        private static UserSettings _instance;
        public static UserSettings Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new UserSettings();
                return _instance;
            }
        }
        public UserSettings()
        {
            InitializeComponent();
        }

        private void btnUnpackPath_Click(object sender, EventArgs e)
        {
            flowLayoutPanel1.Hide();
        }
    }
}

My form

namespace LogAnalyzer
{
    public partial class LogAnalyzerMain : Form
    {
        public LogAnalyzerMain()
        {
            InitializeComponent();
        }

        private void ChangeInstance(Control tab) {
            if (!panelDisplay.Controls.Contains(tab))
            {
                panelDisplay.Controls.Add(tab);
                tab.Dock = DockStyle.Fill;
            }
            tab.BringToFront();
        }

        private void btnSettings_Click(object sender, EventArgs e)
        {
            ChangeInstance(UserSettings);
        }
    }
}

It gives me an error in this line in my form ('UserSettings' is a type, which is not valid in the given context)

ChangeInstance(UserSettings);

You are passing the class itself but the method takes an instance of it, since you have a singleton property you could use that:

ChangeInstance(UserSettings.Instance);

Otherwise you had to store the instance somewhere, for example in the LogAnalyzerMain as field or if it's a control on your form you could use this.Controls.OfType<UserSettings>().First()

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