winformsのコントロールに参加するための最良のアプローチは何ですか?例:ラベルが付いたボタンがあり、クリック数をカウントします。winformsのコントロールに参加するための最良のアプローチ
まず、私はwinformデザイナでコントロールを準備し、次にそれらをClicksCount1クラスのコンストラクタに送信します。これは私のコントロールを互いに簡単に配置したいときには良いことです。
第2のものは、パネル中のコントロールをカップリングすることである。それは私のツールボックスにあるので、それは良いです。
第3のものは第2のものと似ていますが、パネルはありません。
1.
public class ClicksCount1
{
Button _oButton;
Label _oLabel;
int _clickCount = 0;
public int ClickCount {
get {
return _clickCount;
}
set {
_clickCount = value;
_oLabel.Text = _clickCount.ToString();
}
}
public ClicksCount1(Button oButton, Label oLabel)
{
_oButton = oButton;
_oLabel = oLabel;
_oLabel.Text = _clickCount.ToString();
_oButton.Click += _oButton_Click;
}
void _oButton_Click(object sender, EventArgs e)
{
_clickCount++;
}
}
2.
public class ClicksCount2 : Panel
{
Button _oButton = new Button() {Location = new Point(10,10)};
Label _oLabel = new Label() {Location = new Point(100,10)};
int _clickCount = 0;
public int ClickCount {
get {
return _clickCount;
}
set {
_clickCount = value;
_oLabel.Text = _clickCount.ToString();
}
}
public ClicksCount2()
{
_oLabel.Text = _clickCount.ToString();
_oButton.Click += _oButton_Click;
this.Controls.Add(_oButton);
this.Controls.Add(_oLabel);
}
void _oButton_Click(object sender, EventArgs e)
{
ClickCount++;
}
}
3.
public class ClicksCount3 : Button
{
Label _oLabel = new Label();
int _clickCount = 0;
public int ClickCount {
get {
return _clickCount;
}
set {
_clickCount = value;
_oLabel.Text = _clickCount.ToString();
}
}
public ClicksCount3()
{
}
protected override void OnCreateControl()
{
base.OnCreateControl();
_oLabel.Location = new Point(this.Location.X+100,this.Location.Y);
_oLabel.Text = _clickCount.ToString();
this.Parent.Controls.Add(_oLabel);
}
protected override void OnMove(EventArgs e)
{
base.OnMove(e);
_oLabel.Location = new Point(this.Location.X+100,this.Location.Y);
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
ClickCount++;
}
protected override void OnControlRemoved(ControlEventArgs e)
{
base.OnControlRemoved(e);
this.Parent.Controls.Remove(_oLabel);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_oLabel.Dispose();
}
}
[UserControl](https://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol(v = vs.110).aspx)の概念を調査する必要があるようです。 – Steve