I found it ,
var window = Application.Current.MainWindow;
(window as MainWindow).File.Header = "my change";
Direct access to object properties from another window without creating a new window
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
-
رضا جافری 1,296 Reputation points
2020-12-03T03:58:28.903+00:00
1 additional answer
Sort by: Most helpful
-
DaisyTian-1203 11,626 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:
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.