相关疑难解决方法(0)

为什么OnPropertyChanged在Code Behind中不起作用?

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

为什么在单击按钮时,绑定到"Message"的TextBlock不会更改,即使调用了OnPropertyChanged("Message")?

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>
Run Code Online (Sandbox Code Playgroud)

代码背后:

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 …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml inotifypropertychanged

8
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×1

inotifypropertychanged ×1

wpf ×1

xaml ×1