2012-05-28 76 views
1

我被困在一個場景中,我可以有很多遊戲屏幕,我希望能夠使用單選按鈕或組合框選擇遊戲屏幕。 但問題是實現它的最佳方式?如何使用WPF的工廠模式

我是否應該將複選框或組合框選擇的字符串傳遞給Factory,還是應該使用Enum?如果Enum是我要如何使用它的方法?一個簡單的例子會很好,謝謝。

+0

你的意思是一個換膚的UI ?像這個? http://www.codeproject.com/Articles/19782/Creating-a-Skinned-User-Interface-in-WPF –

+0

我認爲這實際上是修改了現有的用戶控件。 我想在運行時爲'Grid.Children [reservedIndex]'添加一個新的用戶控件 –

+1

爲什麼你需要創建一個新的用戶控件? 「主題」的意思有點不清楚。 –

回答

2

我喜歡在這種情況下使用枚舉而不是魔法字符串,因爲它可以防止由拼寫錯誤導致的問題,並使選項可用於intellisense。

namespace TheGame 
{ 
    // declare enum with all available themes 
    public enum EnumGameTheme { theme1, theme2 }; 

    // factory class 
    public class ThemeFactory 
    { 
     // factory method. should create a theme object with the type of the enum value themeToCreate 
     public static GameTheme GetTheme(EnumGameTheme themeToCreate) 
     { 
      throw new NotImplementedException(); 
      // TODO return theme 
     } 
    } 

    // TODO game theme class 
    public class GameTheme { } 
} 

代碼調用工廠給定的(比如說)lstThemes選擇一個主題:

// get the enum type from a string (selected item in the combo box) 
TheGame.EnumGameTheme selectedTheme = Enum.Parse(typeof(TheGame.EnumGameTheme), (string)lstThemes.SelectedValue); 
// invoke the factory method 
TheGame.GameTheme newTheme = TheGame.ThemeFactory.GetTheme(selectedTheme); 

代碼以獲取可用的主題爲字符串:

// get a string array of all the game themes in the Enum (use this to populate the drop-down list) 
string[] themeNames = Enum.GetNames(typeof(TheGame.EnumGameTheme)); 
+0

我不明白這是如何工作的,但它看起來像一個開始謝謝。 –

+0

@LewsTherin我加了一些評論,希望有所幫助。 – McGarnagle

+0

非常感謝,它有幫助。 –