代码之家  ›  专栏  ›  技术社区  ›  Dan

绑定未更新WPF

  •  0
  • Dan  · 技术社区  · 6 年前

    我正在尝试将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);
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   FakeCaleb    6 年前

    你需要 MainWindow 实现接口 INotifyPropertyChanged