Home > Blockchain >  how to Acces a Button/Textbox..... from mainwindow in class
how to Acces a Button/Textbox..... from mainwindow in class

Time:09-27

Im new at OOP and im wondering how i can say in my edit Class, get this textbox from the mainwindow and clear it. I tried this:

public partial class MainWindow : Window
    {
        Edit edit = new Edit();
        public MainWindow()
        {
            InitializeComponent();
           
        }

        private void ClearBtn_Click(object sender, RoutedEventArgs e)
        {
            //TxtBox.Clear();
            edit.Clear();
            
        }
    }

Edit class

public class Edit
    {
        MainWindow main = new MainWindow();

        public void Clear()
        {
            main.TxtBox.Clear();
          
        }
        public Edit()
        {
            
        }

    }

CodePudding user response:

It's unclear to me why you would need to clear the MainWindow's text box from another class, as it's not practical in a real-world situation, but here you go:

public class Edit
{
    public void Clear(MainWindow window)
    {
        window.TxtBox.Clear();
    }
}

Another way to do it would be to pass the MainWindow into the Edit class's constructor, because I can see that you are instantiating Edit from the MainWindow class anyways.

public class Edit
{
    private MainWindow _window;

    public Edit(MainWindow window)
    {
        _window = window;
    }

    public void Clear()
    {
        _window.TxtBox.Clear();
    }
}

CodePudding user response:

if you wish to access controls of MainWindow from different classes you could use a similiar code:

MainWindow MWin = (MainWindow)Application.Current.MainWindow;
MWin.TxtBox.Clear();
  • Related