好吧,这是我的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);
}
}
如果按+按钮,数量的值将更改,而-则相同。如果执行Debug.Writeline,则会显示正确的结果。问题是单击按钮时文本框的文本未更新。
您正在更改不调用RaisePropertyChangedEvent的后备字段的值。将数量更改为数量
private void Add(string obj)
{
Quantity += 1;
Debug.WriteLine(quantity);
}
private void Sub(string obj)
{
Quantity -= 1;
Debug.WriteLine(quantity);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句