2009-04-25 28 views
1

我試圖在Silverlight中使用控件模板來改變它的外觀。Silverlight中的動態控制模板

我需要在代碼中動態地執行此操作(而不是xaml標記)。 Button對象有一個Template屬性,您可以爲其分配ControlTemplate。

但是如何將UI元素添加到ControlTemplate中? (在WPF中,有一個VisualTree屬性,但在Silverlight中不存在此類屬性)

回答

2

我不確定這是否有幫助,但以防萬一。要在代碼中使用控件模板背後的按鈕(不XAML)我已經做了這樣的:

  1. 負載從XML定義的控件模板(下面是一個鏈接到源)

    byte[] bytes = ReadBytesFromStream("BestBuyRemix.BL.buttontemplate.xml"); 
        string buttonTemplate = ""; 
        UTF8Encoding encoding = new UTF8Encoding(); 
        buttonTemplate = encoding.GetString(bytes.ToArray(), 0, (int)bytes.Length); 
    
  2. 創建按鈕,並將其添加到視件樹(在此情況下的渦卷面板)

串onebutton =的String.Format(buttonTemplate,mnu.CatItemName,mnu.CatItemImage, 「{StaticResource buttonStyle1}」, 「{StaticResource CatItemNameBlock}」,「{StaticResource ThumbNailPreview}」, ictr.ToString()); ictr + = 1;

 Button bt = (Button)XamlReader.Load(onebutton); 
     bt.Tag = mnu.CatItemPageUri; 
     bt.Click += new RoutedEventHandler(bt_Click); 

     Wrappable.Children.Add(bt); 

我在博客上寫了一篇關於Best Buy Remix API的文章,該文章使用它來在詳細信息頁面中構建產品列表。它有一個指向Silverlight源的鏈接。如果你有興趣。
blog post link