I wish it was that simple. In WPF, Pages are isolated from each other. In other words, your Page2
doesn't know which Controls Page1
has. You also can't hide a Control on Page1
from Page2
this way because whenever you navigate away from Page1
it's unloaded from memory and any changes you made are lost (unless you save them). In addition, you're most likely navigating to Page1
by using a new
instance which resets the page state (i.e., executes the code and loads the image again). You can do it by using MVVM (Model-View-ViewModel)
to monitor both pages and pass data from one to the other, however, I think this approach is futile. But here's how to do it anyway:
- First, create a new
ViewModel
class:
class ImageViewModel : INotifyPropertyChanged
{
public ImageViewModel(Visibility visibility)
{
_imageVisibility = visibility;
}
private Visibility _imageVisibility;
public Visibility ImageVisibility
{
get { return _imageVisibility; }
set
{
_imageVisibility = value;
OnPropertyChanged("ImageVisibility");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string p)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(p));
}
}
- Second, bind the
Visibility
property of the Image
to the Visibility
property you've defined in the ViewModel
class you just created:
<Image x:Name="gear111" ... Visibility="{Binding ImageVisibility}"/>
- Third, add
DataContext
to Page1
(where your image is). This passes the data from ViewModel
class to the Image
on Page1
:
public Page1(Visibility visibilty)
{
InitializeComponent();
DataContext = new ImageViewModel(visibilty);
}
public Page1()
{
InitializeComponent();
DataContext = new ImageViewModel(Visibility.Visible);
}
- Finally, add this code to your
Button_Click
event on Page2
. When you click the button, this creates a new Window
instance that shows the changes made to Page1
.
private void Button_Click(object sender, RoutedEventArgs e)
{
Window win = new Window();
win.Content = new Page1(Visibility.Collapsed);
win.Show();
}
Please note that the page limitations I mentioned above still apply here. You can make the change in Visibility
persist by saving it to either a bool setting (created in Settings.settings
in Properties
) or a local text file that the application can read before loading the page.
I still strongly suggest that you familiarize yourself with MVVM
(you don't need to fully grasp it as a beginner) and avoid using Windows/Pages when it's unnecessary. Pages are mainly used for navigation purposes or to be viewed through a web browser. For standalone applications, the MainWindow.xaml
is all you need; you simply add more to it to achieve what you want. Knowing the basics of WPF—UI Controls
, Properties
, Events
, Classes
, Data Binding
, Project Structure
, etc.—will make this a lot easier for yourself.