绑定不更新WPF

时间:2018-05-18 15:41:29

标签: c# wpf data-binding

我正在尝试将int绑定到一个简单应用程序中的标签。这个想法是,当按下一个按钮时,int和标签就会被更新。

我已经尽可能地简化了代码,但我无法看到问题。

我认为问题在于NotifyPropertyChanged(String propertyName),因为在运行时启动标签的内容会更新为int的值。但是,当int更新时,标签不会。

MainWindow.xaml

<Window x:Class="Press.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"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="Presses: "/>
            <Label Content="{Binding Path=PressCount}"/>
        </StackPanel>
        <Button Content="Press Me" Click="PressMe_Click"/>
    </StackPanel>
</Window>

MainWindow.xaml.cs

using System;
using System.Windows;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Press
{
    public partial class MainWindow : Window
    {
        public int pressCount = 0;

        public int PressCount {
            get {
                return pressCount;
            }
            private set {
                if(value != pressCount)
                {
                    pressCount = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        private void PressMe_Click(object sender, RoutedEventArgs e)
        {
            PressCount++;
            Console.WriteLine(PressCount);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要MainWindow来实施界面INotifyPropertyChanged