Guest User

Untitled

a guest
Jun 18th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. public class NotificationObject : INotifyPropertyChanged
  2. {
  3. public event PropertyChangedEventHandler PropertyChanged;
  4.  
  5. protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
  6. {
  7. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  8. }
  9.  
  10. protected void SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
  11. {
  12. if (!EqualityComparer<T>.Default.Equals(field, value))
  13. {
  14. field = value;
  15. OnPropertyChanged(propertyName);
  16. }
  17. }
  18. }
  19.  
  20. public partial class MainWindow : Window
  21. {
  22. ModalViewModel mainView;
  23.  
  24. public MainWindow()
  25. {
  26. InitializeComponent();
  27. }
  28.  
  29. private void Button_Click(object sender, RoutedEventArgs e)
  30. {
  31. mainView = new ModalViewModel(new ModalWindow());
  32. mainView.SetMessage("Окошко!");
  33. mainView.ShowWindow();
  34. }
  35. }
  36.  
  37. public class ModalViewModel : NotificationObject
  38. {
  39. private ModalWindow _modalWindow;
  40.  
  41. private string _message;
  42. public string Message
  43. {
  44. get => _message;
  45. set
  46. {
  47. _message = value;
  48. // Этот метод уже реализовывает OnPropertyChanged("Message");
  49. SetField(ref _message, value);
  50. }
  51. }
  52.  
  53. public ModalViewModel()
  54. {
  55. _message = "Hi"; // Тут работает
  56. }
  57.  
  58. public ModalViewModel(ModalWindow modalWindow)
  59. {
  60. _modalWindow = modalWindow;
  61. _message = "Hello!"; // Тут не работает
  62. }
  63.  
  64. public void ShowWindow()
  65. {
  66. _modalWindow.Show();
  67. }
  68.  
  69. public void SetMessage(string message)
  70. {
  71. _message = message;
  72. }
  73. }
  74.  
  75. <Window x:Class="DataContextAndBindingTest.View.ModalWindow"
  76. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  77. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  78. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  79. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  80. xmlns:local="clr-namespace:DataContextAndBindingTest.ViewModel"
  81. mc:Ignorable="d"
  82. Title="ModalWindow" Height="300" Width="300">
  83. <Window.Resources>
  84. <local:ModalViewModel x:Key="ModalViewModel" />
  85. </Window.Resources>
  86. <Grid DataContext="{StaticResource ModalViewModel}">
  87. <Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Margin="0,24,0,85"
  88. FontSize="18" Content="{Binding Message}"/>
  89. <Button Height="30" Width="100" Content="Ok" Margin="96,208,96,31" />
  90. </Grid>
Add Comment
Please, Sign In to add comment