我已经在Silverlight中搜索了FrameworkElementFactory,我们没有这个类,如果没有,我们还有其他任何选择请帮帮我。
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(Grid));
spFactory.Name = "myComboFactory";
spFactory.SetValue(Grid.WidthProperty, Convert.ToDouble(3));
spFactory.SetValue(Grid.HeightProperty, Convert.ToDouble(3));
spFactory.SetValue(Grid.RenderTransformProperty, new TranslateTransform(-6, -6));
FrameworkElementFactory ec1 = new FrameworkElementFactory(typeof(Ellipse));
ec1.SetValue(Ellipse.FillProperty, Brushes.Red);
spFactory.AppendChild(ec1);
上面的代码工作得很好WPF应用程序,但现在我想在Silverlight5中做同样的事情 我正在使用VS 2010,Silverlight5 我想动态添加DataTemplate
答案 0 :(得分:3)
Silverlight中不存在FrameworkElementFactory。如果要在运行时生成DataTemplates,则必须使用XamlReader类。
对于你的情况,你可能会这样做:
ListBox listbox = new ListBox();
DataTemplate template = System.Windows.Markup.XamlReader.Load(
@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
<Grid Width=""3"" Height=""3"">
<Grid.RenderTransform>
<TranslateTransform X=""6"" Y=""6"" />
</Grid.RenderTransform>
<Ellipse Fill=""Red"" />
</Grid>
</DataTemplate>") as DataTemplate;
listbox.ItemTemplate = template;
请注意,您必须在根元素中定义默认命名空间(xmlns = ...)。
值得注意的是,您可以/必须使用此方法以编程方式设置ItemsControl的ItemsPanel。