WPF INotifyPropertyChanged 不更新标签

WPF INotifyPropertyChanged not updating label

我目前正在学习 WPF 的一些基础知识,我已经找了大约 2 天的错误。希望你们能帮忙。

我正在尝试通过使用 INotifyPropertyChanged 和 XAML 中的绑定来更新我的 UI(在本例中是标签的内容)。问题是:它只取第一个值并将其放入内容中。此外,除了事件 (OnPropertyChanged) 被触发之外什么也没有发生。

这是我在 XAML 中的内容:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1" x:Class="MainWindow"
    Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:View x:Key="ViewModel"/>
    </Window.Resources>

    <Grid Margin="0,0,2,-4" DataContext="{Binding Source={StaticResource ViewModel}}">
....
    <Label x:Name="lbl_money" Grid.ColumnSpan="2" Content="{Binding Path=PropMoney}" HorizontalAlignment="Left" Margin="403,42,0,0" VerticalAlignment="Top">

这是我的 class 视图的必要部分:

Public Class View
Inherits ViewModelBase

Private rest1 As New Restaurant
Private mainPlayer As New Player
Private mycurrentMoney As Double = 3
Private currentClickIncrease = mainPlayer.PropClickIncrease

 Public Property PropMoney() As Double
    Get
        Return mycurrentMoney
    End Get
    Set(value As Double)
        mycurrentMoney = value
        OnPropertyChanged("mycurrentMoney")
    End Set
End Property

Sub SelfClicked()
    PropMoney() += 1
End Sub

最后但同样重要的是 MainWindow class,我在其中实例化我的视图:

Class MainWindow

Private view As New View

    Sub New()
        InitializeComponent()
    End Sub

    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
        view.SelfClicked()
    End Sub

End Class

所以我的 mycurrentMoney 每次点击都会增加,事件会被触发,但标签不会更新。

提前致谢!

您的 OnPropertyChanged("mycurrentMoney") 声明不会在您的 属性 上引发 属性 更改,因为它被称为 PropMoney.

您必须在 setter 中设置 OnPropertyChanged("PropMoney")

如果您有 Visual Studio 15,请使用 NameOf 运算符而不是像这样的字符串文字:

NameOf(PropMoney);

如果您稍后重命名您的 属性,它仍然会与字符串文字相反,后者不会。或者修改您的 OnPropertyChange 以使用 CallerMemberName

OnPropertyChange ([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{

}

属性 名称将被填写,但是这仅适用于 setter 当前 属性。

此外,为整个 window (Setting DataContext in XAML in WPF) 设置 DataContext。 DataContext={StaticResource ViewModel} 并且不要在绑定中使用 Path,只需 {Binding PropertyName}

您的代码有 2 个问题

首先你为支持字段引发 PropertyChanged 事件并且应该为 属性 name

引发它
OnPropertyChanged("PropMoney")

其次,您更改的 属性 属于 View 的不同实例,然后设置为 DataContext。所以在XAML中去掉DataContext变化,只留下属性绑定

<Window ...>
    <Grid Margin="0,0,2,-4">
        <!-- .... -->
        <Label ... Content="{Binding Path=PropMoney}">

然后在 MainWindow 的代码集 DataContext 中到您创建和修改的实例

Class MainWindow

Private view As New View

    Sub New()
        InitializeComponent()
        DataContext = view
    End Sub

    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
        view.SelfClicked()
    End Sub

End Class