Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class NotificationObject : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged;
- protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
- {
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- }
- protected void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
- {
- if (!EqualityComparer<T>.Default.Equals(field, value))
- {
- field = value;
- OnPropertyChanged(propertyName);
- }
- }
- }
- public partial class MainWindow : Window
- {
- ModalViewModel mainView;
- public MainWindow()
- {
- InitializeComponent();
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- mainView = new ModalViewModel(new ModalWindow());
- mainView.SetMessage("Окошко!");
- mainView.ShowWindow();
- }
- }
- public class ModalViewModel : NotificationObject
- {
- private ModalWindow _modalWindow;
- private string _message;
- public string Message
- {
- get => _message;
- set
- {
- _message = value;
- // Этот метод уже реализовывает OnPropertyChanged("Message");
- SetField(ref _message, value);
- }
- }
- public ModalViewModel()
- {
- _message = "Hi"; // Тут работает
- }
- public ModalViewModel(ModalWindow modalWindow)
- {
- _modalWindow = modalWindow;
- _message = "Hello!"; // Тут не работает
- }
- public void ShowWindow()
- {
- _modalWindow.Show();
- }
- public void SetMessage(string message)
- {
- _message = message;
- }
- }
- <Window x:Class="DataContextAndBindingTest.View.ModalWindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:local="clr-namespace:DataContextAndBindingTest.ViewModel"
- mc:Ignorable="d"
- Title="ModalWindow" Height="300" Width="300">
- <Window.Resources>
- <local:ModalViewModel x:Key="ModalViewModel" />
- </Window.Resources>
- <Grid DataContext="{StaticResource ModalViewModel}">
- <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="0,24,0,85"
- FontSize="18" Content="{Binding Message}"/>
- <Button Height="30" Width="100" Content="Ok" Margin="96,208,96,31" />
- </Grid>
Add Comment
Please, Sign In to add comment