Direct access to object properties from another window without creating a new window

رضا جافری 1,291 Reputation points
2020-12-01T15:10:55.083+00:00

Hi
First and foremost, I apologize for my grammatical errors; my first language is Persian (Iran).

In my project (WPF) i have many windows. in window form i have no problem to access object property from Another window With following codes for example:

(Application.OpenForms[1].Controls[0].Controls[0].Controls[2] as TreeView).SelectedImageIndex = 10;

But in WPF i try many codes like

Application.Current.MainWindow

Or

App.Current.MainWindow

But the problem was not solved
Please answer accurately by C# coding

My control name is "File" (as menuItem) and i want change header property

Thanks

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,706 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,573 questions
{count} votes

1 additional answer

Sort by: Most helpful
  1. DaisyTian-1203 11,621 Reputation points
    2020-12-02T03:33:46.05+00:00

    I will show you a sample of updating MainWindow's MenuItem which named myEdit in Window1:
    Here is the code for MainWindow.xaml:

    <StackPanel>  
            <Menu>  
                <MenuItem Name="myEdit" Header="_Edit" x:FieldModifier="public" >  
                    <MenuItem Command="ApplicationCommands.Copy"/>  
                    <MenuItem Command="ApplicationCommands.Cut"/>  
                    <MenuItem Command="ApplicationCommands.Paste"/>  
                </MenuItem>  
            </Menu>  
            <Button Width="120" Height="30" Content="Show Window1" Click="Button_Click"></Button>  
        </StackPanel>  
    

    MainWindow.xaml.cs is:

     private void Button_Click(object sender, RoutedEventArgs e)  
            {  
                Window1 window1 = new Window1();  
                window1.Show();  
            }  
    

    Create a Button in Window1, and it's click event code is:

     private void Button_Click(object sender, RoutedEventArgs e)  
            {  
                foreach (Window window in Application.Current.Windows)  
                {  
                    if (window.GetType() == typeof(MainWindow))  
                    {  
                        (window as MainWindow).myEdit.Header = "I changed it from another window1";  
                    }  
                }  
            }  
    

    The result picture is:
    44068-2.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.