Dynamic Control Template in Silverlight

心已入冬 提交于 2020-01-16 05:28:04

问题


I'm trying to make a button in Silverlight use a control template to change the way it looks.

I need to do this dynamically in code (not xaml markup). The Button object has a Template property to which you can assign a ControlTemplate.

But how do you stuff UI elements into the ControlTemplate? (In WPF, there is a VisualTree property but no such property exists in Silverlight)


回答1:


I'm not sure if this helps, but just in case. To create buttons using a control template in code behind (not XAML) I've done it like this:

  1. load the control template from an xml definition (below is a link to the source)

        byte[] bytes = ReadBytesFromStream("BestBuyRemix.BL.buttontemplate.xml");
        string buttonTemplate = "";
        UTF8Encoding encoding = new UTF8Encoding();
        buttonTemplate = encoding.GetString(bytes.ToArray(), 0, (int)bytes.Length);
    
  2. create the button and add it to the visual tree (in this case a wrap panel)

string 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);

I wrote a post on my blog about the Best Buy Remix API which uses this to build a product list in the details page. It has a link to the Silverlight source. In case you're interested.
blog post link



来源:https://stackoverflow.com/questions/788409/dynamic-control-template-in-silverlight

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!