我正在尝试通过将ViewModel模型放在后面的代码中并将DataContext绑定为<!>“这个<!>”来简化一些代码,但是在下面的示例中它似乎有所不同: / p>

为什么在单击按钮时,TextBlock绑定到<!>“消息<!>”;即使调用OnPropertyChanged(<!> quot; Message <!> quot;),也不会改变?

<强> 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标记它来告诉它。这样,绑定机制可以将您的类识别为潜在的更新目标。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top