Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么OnPropertyChanged在代码隐藏中不起作用?_C#_Wpf_Xaml_Inotifypropertychanged - Fatal编程技术网

C# 为什么OnPropertyChanged在代码隐藏中不起作用?

C# 为什么OnPropertyChanged在代码隐藏中不起作用?,c#,wpf,xaml,inotifypropertychanged,C#,Wpf,Xaml,Inotifypropertychanged,我试图通过将ViewModel模型放入代码中并将DataContext绑定为“this”来简化一些代码,但在以下示例中,它的工作方式似乎有所不同: 为什么在单击按钮时,绑定到“消息”的文本块不会更改,即使调用了OnPropertyChanged(“消息”)? XAML: <Window x:Class="TestSimple223.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

我试图通过将ViewModel模型放入代码中并将DataContext绑定为“this”来简化一些代码,但在以下示例中,它的工作方式似乎有所不同:

为什么在单击按钮时,绑定到“消息”的文本块不会更改,即使调用了OnPropertyChanged(“消息”)?

XAML:

<Window x:Class="TestSimple223.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel HorizontalAlignment="Left">
        <Button Content="Button" 
                Click="button1_Click" />
        <TextBlock 
            Text="{Binding Path=Message, Mode=TwoWay}"/>
        <TextBlock
            x:Name="Message2"/>
    </StackPanel>
</Window>
using System.Windows;
using System.ComponentModel;

namespace TestSimple223
{
    public partial class Window1 : Window
    {
        #region ViewModelProperty: Message
        private string _message;
        public string Message
        {
            get
            {
                return _message;
            }

            set
            {
                _message = value;
                OnPropertyChanged("Message");
            }
        }
        #endregion

        public Window1()
        {
            InitializeComponent();
            DataContext = this;

            Message = "original message";
            Message2.Text = "original message2";
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Message = "button was clicked, message changed";
            Message2.Text = "button was click, message2 changed";
        }

        #region INotify
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        } 
        #endregion


    }
}

您尚未将类标记为可用于属性更改通知。将标题改为

public partial class Window1 : Window, INotifyPropertyChanged
仅仅因为实现了这些方法并不意味着WPF知道类支持更改通知—您需要通过使用INotifyPropertyChanged标记来告诉它。这样,绑定机制可以将您的类标识为潜在的更新目标