I would like to change the property Visible of a control in the PAGE1 when I click on a button on the PAGE2. The PAGE2 is a Pop'Up window with a message for the user. I want when he clicks on a button below that the property Visible from a control in the PAGE2 (still displayed in the background at the same time) change.
The problem for me is that the event of my button belongs to the PAGE2 class and I'm not able to reach PAGE1's objects from there.
I you want to do it the "right" way you should share some data with an intermediate object.
Here is a full sample:
The view-model, shared by both pages/windows:
using System.ComponentModel;
namespace WpfMagic
{
public class MyViewModel : INotifyPropertyChanged
{
private bool flag;
public bool Flag
{
get { return flag; }
set
{
if (value != flag)
{
flag = value;
PropertyChanged(this, new PropertyChangedEventArgs("Flag"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
}
The main page/window:
XAML:
<Window x:Class="WpfMagic.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfMagic"
Title="MainWindow"
SizeToContent="WidthAndHeight">
<StackPanel>
<StackPanel.Resources>
<BooleanToVisibilityConverter x:Key="boolToVisibility"></BooleanToVisibilityConverter>
</StackPanel.Resources>
<TextBlock Visibility="{Binding Model.Flag,Converter={StaticResource boolToVisibility}}">Hey I'm Here!</TextBlock>
<Button Click="Button_Click">Show Popup!</Button>
</StackPanel>
</Window>
Code-behind:
using System.Windows;
namespace WpfMagic
{
public partial class MainWindow : Window
{
public MyViewModel Model { get; set; }
public MainWindow()
{
InitializeComponent();
Model = new MyViewModel();
this.DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
new AnotherWindow(Model).Show();
}
}
}
The popup page/window:
XAML:
<Window x:Class="WpfMagic.AnotherWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AnotherWindow" Height="300" Width="300">
<Grid>
<CheckBox IsChecked="{Binding Model.Flag}">Check Me!</CheckBox>
</Grid>
</Window>
Code-behind:
using System.Windows;
namespace WpfMagic
{
public partial class AnotherWindow : Window
{
public MyViewModel Model { get; set; }
public AnotherWindow(MyViewModel model)
{
InitializeComponent();
Model = model;
this.DataContext = this;
}
}
}
If you get this example you'll get 90% of MVVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With