[.NET]找到控制項後針對它要做一些設定的方式

有時找到控制項後針對它要做一些設定,
本文記錄一些程式的寫法。

今天看到有個程式利用 id 找到該控制項後,會針對該控制項做一些設定,如下,

var ctrl = this.Controls.Find("button1", true).OfType<Button>().FirstOrDefault();
if (ctrl == null) throw new NullReferenceException();
ctrl.Text = "this is test way 1";
ctrl.Left += 10;
//.... 其他設定

 

像這樣子,我們也可以將這樣的行為包裝起來,如下,

/// <summary>
/// 依id找到該控項,並執行傳入的程式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"></param>
/// <param name="executeCode"></param>
public void  FindControl<T>(string id, Action<T> executeCode)
{
	var ctrl = this.Controls.Find(id, true).OfType<T>().FirstOrDefault();
	if (ctrl == null) throw new NullReferenceException();
	executeCode.Invoke(ctrl);
}

 

而呼叫就會變成如下的方式,

//way 2
FindControl<Button>("button2", (c) =>
{
	c.Text = "this is test way 2";
	c.Left += 10;
	//.... 其他設定
});

 

另外將某物件包在一個範圍中設定也可以建立一個擴充方式來使用,如下,

//http://stackoverflow.com/questions/481725/with-block-equivalent-in-c
public static class ExtensionHelper
{
	public static T With<T>(this T item, Action<T> action)
	{
		action(item);
		return item;
	}
}

 

使用方式如下,

// other discussion
button3.With(c =>
{
	c.Text = "assign with...";
	c.Left += 10;
	//.... 其他設定
});

 

參考資料

With block equivalent in C#?

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^