Эх...WinForms. Как вспомню, так вздрогну. В дремучее время было как-то так:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using MonadTeq.Toster.UI.Annotations;
namespace MonadTeq.Toster.UI
{
/// <summary>
/// An abstraction of view model for data binding.
/// </summary>
public abstract class ViewModel
: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool UpdateProperty<T>(ref T oldValue, T newValue, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(oldValue, newValue))
{
return false;
}
oldValue = newValue;
OnPropertyChanged(propertyName);
return true;
}
}
/// <summary>
/// Represents a view model for business logic.
/// </summary>
public sealed class RandomSummaryViewModel
: ViewModel
{
private int _accumulatedValue;
private int _value;
public RandomSummaryViewModel(int initialValue = 0)
{
_accumulatedValue = initialValue;
}
public int Value
{
get => _value;
set => UpdateProperty(ref _value, value);
}
public int AccumulatedValue
{
get => _accumulatedValue;
set => UpdateProperty(ref _accumulatedValue, value);
}
}
public partial class RandomNumberSumForm : Form
{
private readonly RandomSummaryViewModel _vm = new RandomSummaryViewModel();
private readonly Random _rnd = new Random();
public RandomNumberSumForm()
{
InitializeComponent();
//
// Configure data bindings here...
//
// Bind text box (id: tbxCurrentRandom) property Text to 'Value' property of RandomSummaryViewModel instance...
tbxCurrentRandom.DataBindings.Add("Text", _vm, "Value", false, DataSourceUpdateMode.OnPropertyChanged);
// The same but for label (See logic above)
lblSum.DataBindings.Add("Text", _vm, "AccumulatedValue", true, DataSourceUpdateMode.OnPropertyChanged);
}
private void btnNextRandom_Click(object sender, EventArgs e)
{
_vm.Value = _rnd.Next(0, 100);
_vm.AccumulatedValue += _vm.Value;
}
}
}
Сумеете объяснить, что тут происходит и добавить сумму по следующему нажатию, а не мгновенно - приходите junior'ом :)