单击按钮时文本框值未更新

TextBox value not updating on Button click

这是我的 XAML 代码:

<TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Width="25" Margin="100,0,0,0" Height="25" Text="{Binding Quantity, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<Button Grid.Row="2" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="25" Content="+" Command="{Binding AddCommand}"></Button>
<Button Grid.Row="2" Grid.Column="1" HorizontalAlignment="Right" Margin="10" VerticalAlignment="Center" Width="100" Height="25" Content="-" Command="{Binding SubtractCommand}"></Button>

这是我的 C# 代码:

public class ViewModel : ObservableObject, INotifyPropertyChanged
{
    private int quantity = 0;
    public int Quantity
    {
        get => quantity;
        set
        {
            if (quantity == value) return;
            quantity = value;
            this.RaisePropertyChangedEvent(nameof(Quantity));
        }
    }
    public ICommand AddCommand => new RelayCommand<string>(
        Add,
        x => true
    );
    public ICommand SubtractCommand => new RelayCommand<string>(
        Sub,
        x => true
    );
    private void Add(string obj)
    {
        quantity += 1;
        Debug.WriteLine(quantity);
    }
    private void Sub(string obj)
    {
        quantity -= 1;
        Debug.WriteLine(quantity);
    }
}

如果按 +/- 按钮,quantity 的值会改变。 Debug.Writeline 的输出是正确的结果。问题是单击按钮时文本框的文本没有更新。

您正在更改不调用 RaisePropertyChangedEvent 的支持字段的值。将 quantity 更改为 Quantity:

private void Add(string obj)
{
    Quantity += 1;
    Debug.WriteLine(quantity);
}
private void Sub(string obj)
{
    Quantity -= 1;
    Debug.WriteLine(quantity);
}