【发布时间】:2021-01-17 11:48:50
【问题描述】:
这是我的 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 的输出是正确的结果。问题是 TextBox 的文本在按钮单击时没有更新。
【问题讨论】:
标签: c# .net wpf data-binding