课程名:Windows应用程序开发入门到精通四:Windows窗体开发中的面向对象概念
1,自定义控件的开发。
最简单的控件自定义是重写公共控件的方法。例如,可以重写 TextBox 控件的 OnKeyPress 继承方法,提供将输入限制为数字字符的代码。
public class NumricTextBox : System.Windows.Forms.TextBox
{
bool allowSpace = false; //不允许出现空格
protected override void OnKeyPress(KeyPressEventArgs e)
{ // 限制输入字符为数字,小数点,负号,Backspace键
base.OnKeyPress(e);
NumberFormatInfo numberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
if (Char.IsDigit(e.KeyChar))
{
//输入为数字
}
else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
keyInput.Equals(negativeSign))
{
// 输入小数分隔符号
}
else if (e.KeyChar == '\b')
{
// Backspace键
}
else if (this.allowSpace && e.KeyChar == ' ')
{
}
else
{
e.Handled = true; //通知父类事件已经处理过了,父类不必再响应
}
}
public int IntValue
{
get
{
return Int32.Parse(this.Text);
}
}
public decimal DecimalValue
{
get
{
return Decimal.Parse(this.Text);
}
}
public bool AllowSpace
{
set
{
this.allowSpace = value;
}
get
{
return this.allowSpace;
}
}
}
2, “组合”和“聚合”的区别到底是什么呢?用接口来代替继承更易于应对变化?
3,Observer模式实例
public interface ISubject
{
}
public interface IObserver
{
ISubject Subject
{
set;
}
}
public class MainSubject : ISubject
{
public event EventHandler SelectedChanged;
private int m_selected;
public int Selected
{
get
{
return m_selected;
}
set
{
m_selected = value;
if (SelectedChanged != null)
{
SelectedChanged(this, EventArgs.Empty);
}
}
}
public MainSubject()
{
}
}
public class Buttons : System.Windows.Forms.UserControl, IObserver
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private MainSubject m_subject;
private void button1_Click(object sender, System.EventArgs e)
{
this.m_subject.Selected = 1;
}
private void button2_Click(object sender, System.EventArgs e)
{
this.m_subject.Selected = 2;
}
private void button3_Click(object sender, System.EventArgs e)
{
this.m_subject.Selected = 3;
}
IObserver Members
}
public class Views : System.Windows.Forms.UserControl, IObserver
{
private System.Windows.Forms.TextBox textBox1;
private MainSubject m_subject;
IObserver Members
private void m_subject_SelectedChanged(object sender, EventArgs e)
{
this.textBox1.Text = m_subject.Selected.ToString();
}
}
public class Form1 : System.Windows.Forms.Form
{
private ObserverPattern.Buttons buttons1;
private ObserverPattern.Views views1;
private MainSubject m_subject;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
m_subject = new MainSubject();
this.buttons1.Subject = m_subject;
this.views1.Subject = m_subject;
}
}
本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2006/10/24/538873.html,如需转载请自行联系原作者