2011-10-01 48 views
4

我正在創建一個自定義控件,它是一個按鈕。它可能根據類型有一個類型和一個指定的圖像。它的類型可以是:使用資源和用戶定義的控制屬性

public enum ButtonType 
{ 
    PAUSE, 
    PLAY 
} 

現在我可以改變它的外觀和圖像的方法:

public ButtonType buttonType; 
public void ChangeButtonType(ButtonType type) 
{ 
    // change button image 
    if (type == ButtonType.PAUSE) 
     button1.Image = CustomButtonLibrary.Properties.Resources.PauseButton; 
    else if (type == ButtonType.PLAY) 
     button1.Image = CustomButtonLibrary.Properties.Resources.PlayButton; 

    buttonType = type; 
} 

確定,這種方法似乎並不那麼好,例如也許以後我希望有另一種類型爲STOP,例如對於此按鈕,我只需將其圖像添加到資源並將其添加到ButtonType enum,而不更改此方法。

如何實現此方法以適應未來的變化?

+0

'ChangeButtonType'方法在哪裏?它在您的自定義按鈕上嗎? –

+0

@Anna:是的,它是一個控制庫和這種方法,枚舉和所有在那裏。 – Mouliyan

回答

3

的一件事是把ButtonType成一個基類(或接口,如果你喜歡):

public abstract class ButtonType 
{ 
    public abstract Image GetImage(); 
} 

你的類型。然後每變成一個子類:

public class PauseButtonType : ButtonType 
{ 
    public Image GetImage() 
    { 
     return CustomButtonLibrary.Properties.Resources.PauseButton; 
    } 
} 

public class PlayButtonType : ButtonType 
{ 
    public Image GetImage() 
    { 
     return CustomButtonLibrary.Properties.Resources.PlayButton; 
    } 
} 

你的影像變更方法就變成了:

private ButtonType buttonType; // public variables usually aren't a good idea 
public void ChangeButtonType(ButtonType type) 
{ 
    button1.Image = type.GetImage(); 
    buttonType = type; 
} 

,當你想添加另一種類型的這種方式,你再添ButtonType子類並將其傳遞給您的ChangeButtonType方法。


由於這種方法是在你的自定義按鈕,我可能會藉此一點,並封裝風格/外觀類:

public class ButtonStyle 
{ 
    // might have other, non-abstract properties like standard width, height, color 
    public abstract Image GetImage(); 
} 

// similar subclasses to above 

,然後在按鈕本身:

public void SetStyle(ButtonStyle style) 
{ 
    this.Image = style.GetImage(); 
    // other properties, if needed 
} 

您可以按照與ButtonAction基類相似的方式設置按鈕行爲(即它們在單擊時執行的操作),並在您想要更改按鈕的目的時指定特定的操作(如停止和播放)和風格。

+0

很好,謝謝。 +1 – Mouliyan

2

唐`知道這是不是最好的選擇,但你可以創建一個自定義屬性的枚舉,包含圖像

public enum ButtonType 
{ 
    [ButtonImage(CustomButtonLibrary.Properties.Resources.PauseButton)] 
    PAUSE, 

    [ButtonImage(CustomButtonLibrary.Properties.Resources.PlayButton)] 
    PLAY 
} 

我不會進入這個細節,因爲這是易谷歌......其實,這是一個很好的資源開始:

你可以做http://joelforman.blogspot.com/2007/12/enums-and-custom-attributes.html?showComment=1317161231873#c262630108634229289