Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
I'm trying to build a program, where I have a simple keypad in child window. In my parent window I have a button that opens my keypad and two text boxes. When I click on my buttons on keypad (child) window, it should display values in text boxes, that are respresented by a specific button. What should I do to get this child/parent communication working?

What I have tried:

I found some good resources on delegates and I tried with this code, but it still doesn't work. The invoke function doesn't seem to work, because my text box is still empty, when I click on my keypad buttons.

My parent window:

public partial class MainWindow : MetroWindow
    {
       
        public MainWindow()

        {
            InitializeComponent();

        }

        public void WriteToTextBoxes(string a)
        {
            TextBox2.Text += a;
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            TextBox1.Text = String.Empty;
            TextBox2.Text = String.Empty;
        }


My child window:

public partial class KeyboardWindow : MetroWindow
{
    public delegate void someDelegate(string a);
    MainWindow _mainW = new MainWindow();

    public KeyboardWindow()
    {
        InitializeComponent();

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {


    }

    private void Window_Closed(object sender, EventArgs e)
    {

    }

    private void KeypadOne_Click(object sender, RoutedEventArgs e)
    {
        someDelegate p = null;
        p = this._mainW.WriteToTextBoxes;
        p.Invoke("1");

    }
Posted
Updated 7-Apr-17 5:51am
v3
Comments
CHill60 7-Apr-17 6:58am    
"couldn't get it to work" doesn't help. Post the code that you are struggling with and explain what is going wrong. Use the Improve question link to do this
[no name] 7-Apr-17 12:02pm    
" MainWindow _mainW = new MainWindow();" because you are instantiating an brand new never before used or seen before window and using that instead of the already existing instance of the window.
Mitja Klokočovnik 8-Apr-17 2:30am    
Okay, how should I instantiate then? I'm quite new to WPF and programming itself, so sorry if this seems too trivial to you.
Mitja Klokočovnik 8-Apr-17 2:58am    
private MainWindow m_parent;

public KeyboardWindow(MainWindow parent)
{
InitializeComponent();
m_parent = parent;
}

Solved it :)
Philippe Mori 8-Apr-17 10:23am    
Usually, it is a bad design when a component need to know its parent. You should use events for that purpose.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900