NotifyPropertyChanged未绑定到UI

时间:2018-08-13 15:28:28

标签: c# wpf mvvm

学习WPF数据绑定。逐步完成解决方案,我可以看到调用了propertychanged,但是标签未更新为“ Hi”。谁能指出我正确的方向?

在textbox / textblock中对其进行了尝试,但效果不佳。该MVVM非常令人困惑。

XAML:

<Window x:Class="binding.MainWindow"
    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:binding"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Label Name="MyLabel" Background="LightGray" FontSize="17pt" HorizontalContentAlignment="Right" Margin="10,10,10,0" VerticalAlignment="Top" Height="40" 
           Content="{Binding Path=CalculatorOutput, UpdateSourceTrigger=PropertyChanged}"/>        
</Grid>

ViewModel:

using System;
using System.ComponentModel;

namespace binding
{
    public class CalculatorViewModel : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged;

    private String _calculatorOutput;

    public CalculatorViewModel()
    {
        CalculatorOutput = "Hi";
    }

    private String CalculatorOutput
    {
        get { return _calculatorOutput; }
        set
        {
            _calculatorOutput = value;
            NotifyPropertyChanged("CalculatorOutput");
        }
    }

    protected virtual void NotifyPropertyChanged(String propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

MainWindow.xaml.cs

namespace binding
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            DataContext = new CalculatorViewModel();
            InitializeComponent();
        }
    }
}

0 个答案:

没有答案