Search code examples
c#wpfsilverlight

How can I access a control in WPF from another class or window


I want to access my controls like button or textbox in mainWindow in WPF, but I can't do this.

In Windows Form application it's so easy, you can set modifier of that control to True and you can reach that control from an instance of that mainWindow, but in WPF I can't declare a public control. How can I do this?


Solution

  • To access controls in another WPF forms, you have to declare that control as public. The default declaration for controls in WPF is public, but you can specify it with this code:

    <TextBox x:Name="textBox1" x:FieldModifier="public" />
    

    And after that you can search in all active windows in the application to find windows that have control like this:

    foreach (Window window in Application.Current.Windows)
    {
        if (window is Window1)
        {
            ((Window1)window).textBox1.Text = "I changed it from another window";
        }
    }
    

    or

    foreach (Window window in Application.Current.Windows)
    {
        if (window is Window1 window1)
        {
            window1.textBox1.Text = "I changed it from another window";
        }
    }
    

    or

    using System.Linq;
    ...
    
    foreach (Window1 window1 in Application.Current.Windows.OfType<Window1>())
    {
        window1.textBox1.Text = "I changed it from another window";
    }