label1.text = label.text × textbox.text
public partial class Form1 : Form
{
private vm _vm;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_vm = new vm(){A=24.2m};
this.label1.DataBindings.Add(nameof(Label.Text), _vm, nameof(vm.A));
this.textBox1.DataBindings.Add(nameof(TextBox.Text), _vm, nameof(vm.B));
this.label2.DataBindings.Add(nameof(Label.Text), _vm, nameof(vm.C));
this.textBox1.KeyPress += TextBox1_KeyPress;
this.textBox1.TextChanged += TextBox1_TextChanged;
}
private void TextBox1_TextChanged(object? sender, EventArgs e)
{
this.textBox1.DataBindings[0].WriteValue();
}
private void TextBox1_KeyPress(object? sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
{
e.Handled = true;
}
}
}
public class vm:INotifyPropertyChanged
{
private decimal _a;
private int _b;
public decimal A
{
get => _a;
set
{
if (value == _a) return;
_a = value;
OnPropertyChanged();
}
}
public int B
{
get => _b;
set
{
if (value == _b) return;
_b = value;
OnPropertyChanged();
}
}
public decimal C => A * (decimal)B;
public event PropertyChangedEventHandler? PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}