2011-01-19 78 views
0

首先,我對我的英語感到抱歉,希望你能理解我的問題(接受更正並且下一篇文章會更加正確)。以編程方式創建一個按鈕模板

好吧,這是我的場景:開發Windows Phone 7.我無法使用XAML模板。我需要在運行時用C#代碼創建一個模板。我必須自定義的唯一元素是處於非活動狀態的背景和前景顏色,以及用戶按住按鈕時的邊框以及邊框的圓角。

建立Button.Style屬性只能默認狀態(未激活),我不能創建一個拐角半徑:

Style buttonStyle = new Style(typeof(Button); 

buttonStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Colors.Blue)); 
buttonStyle.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush(Colors.White))); 

Button myBytton = new Button(); 
myButton.Style = buttonStyle; 

下一步是創建一個CustomTemplate爲Button.Template財產,但總是會引發一個例外:

CustomTemplate myTemplate = new CustomTemplate(); 
myTemplate.TargetType = typeof(Button); // Exception raises here: InvalidOperationException wihtout more info 

(..Continues代碼...)

Button myBytton = new Button(); 
myButton.Template = myTemplate; 

我看過的所有例子都使用XAML作爲CutomTemplate。我不知道如何爲不同的按鈕狀態和邊框半徑設置樣式。

如果有人可以幫我...感謝您的閱讀,

+0

這只是它是不是可能的,但在控制分配TemplateProperty將取代一個好辦法整個按鈕模板,所以基本上你會最終在代碼中從頭開始創建模板。 TargetType屬性用於Xaml解析器使用的PropertyDescriptor。您應該考慮在xaml中放置模板,並在必要時分配它,或者更好地利用Triggers機制,以便更改這些屬性。讓我知道你喜歡哪種方式,我會發布代碼。 – baalazamon 2011-01-19 18:26:51

+0

在代碼中創建控件還有一個缺點Silverlight沒有FrameworkElementFactory,並且創建模板的唯一方法是XamlReader.Load,因此您最終將使用cam文件中的xaml或讀取它的形式文件。 – baalazamon 2011-01-19 19:19:05

+1

爲什麼你不能使用xaml? – 2011-01-19 19:50:19

回答

相關問題