首页 > 解决方案 > 绑定不更新 WPF

问题描述

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

我已经尽可能地简化了代码,但我看不到问题所在。

我认为问题在于NotifyPropertyChanged(String propertyName)在运行时开始标签的内容会使用 int 的值进行更新。但是,当 int 更新时,标签不会。

主窗口.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>

主窗口.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);
        }
    }
}

标签: c#wpfdata-binding

解决方案


你需要MainWindow实现接口INotifyPropertyChanged


推荐阅读