1

This is my XAML code:

<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>

This is my C# code:

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);
    }
}

If you press the +/- buttons, the value of quantity changes. The output of Debug.Writeline is the correct result. The problem is that the text of the TextBox is not updated on Button click.

1 Answer 1

3

You are changing the value of the backing field which does not call RaisePropertyChangedEvent. Change quantity to Quantity:

private void Add(string obj)
{
    Quantity += 1;
    Debug.WriteLine(quantity);
}
private void Sub(string obj)
{
    Quantity -= 1;
    Debug.WriteLine(quantity);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.