MVP Sample for Winform
이철우
MVC 에서 개선한 것.
- C# Winform의 DataBinding 과 INotifyPropertyChanged 를 이용하여
- Model 과 View 에서
- DataChangedEvent 를 뺐다.
-
먼저 Winform 프로젝트(.Net 7)를 만든다.
0-1. 프로젝트 속성에서 'Console Application’을 선택한다.
0-2. Form1 디자인에서 TextBoxData, ButtonReset, ButtonIncrease 를 추가한다. -
IView.cs
public interface IView
{
TextBox TextBoxData { get; }
event EventHandler<EventArgs>? ResetPressed;
event EventHandler<EventArgs>? IncreasePressed;
}
- Model.cs
public class Model : INotifyPropertyChanged
{
public Model() { }
public int Data
{
get => _data;
set
{
if (_data != value)
{
_data = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Data)));
Console.WriteLine(ToString());
}
}
}
private int _data = 0;
public void Reset() => Data = 0;
public void Increase() => Data++;
public void Set(int data) => Data = data;
public override string ToString() => $"Data:{Data}";
public event PropertyChangedEventHandler? PropertyChanged;
}
- Presenter.cs
public class Presenter
{
public Model Model { get; private set; }
public IView View { get; private set; }
public Presenter(Model model, IView view)
{
Model = model;
View = view;
View.ResetPressed += View_ResetPressed;
View.IncreasePressed += View_IncreasePressed;
var binding = new BindingSource
{
DataSource = Model
};
View.TextBoxData.DataBindings.Add(new Binding("Text", binding, "Data", true, DataSourceUpdateMode.OnPropertyChanged));
}
private void View_ResetPressed(object? sender, EventArgs e)
{
Model.Reset();
}
private void View_IncreasePressed(object? sender, EventArgs e)
{
Model.Increase();
}
}
- IView 상속받은 Form1.cs
public partial class Form1 : Form, IView
{
public Form1()
{
InitializeComponent();
}
TextBox IView.TextBoxData => TextBoxData;
public event EventHandler<EventArgs>? ResetPressed;
public event EventHandler<EventArgs>? IncreasePressed;
private void ButtonReset_Click(object sender, EventArgs e)
{
ResetPressed?.Invoke(this, new EventArgs());
}
private void ButtonIncrease_Click(object sender, EventArgs e)
{
IncreasePressed?.Invoke(this, new EventArgs());
}
}
- Program.cs
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
#region MVP Sample for Winform.
var view = new Form1();
var model = new Model();
_ = new Presenter(model, view);
#endregion
Application.Run(view);
}
}