【问题标题】:How to create DataTemplate dynamically and assign a StackPanel to it?如何动态创建 DataTemplate 并为其分配 StackPanel?
【发布时间】:2014-07-09 16:15:47
【问题描述】:

假设我想制作以下数据模板:

StackPanel stackPanel = new StackPanel();

Button button1 = new Button();
button1.Click += button1_Click;
Button button2 = new Button();
button2.Click += button2_Click;

stackPanel.Children.Add(button1);
stackPanel.Children.Add(button2);

如何将其转换为 DataTemplate?我尝试创建 DataTemplate 类的实例,但我没有看到任何方法或属性可以让我将上面的堆栈面板设置为 DataTemplate 对象的内容。

编辑: 我正在尝试在 Windows 应用商店应用中执行此操作。

【问题讨论】:

  • 我认为您可以尝试将StackPanel 分配给DataTemplate 对象的VisualTree 属性,但这只是猜测。为什么不直接在 XAML 中构建模板?
  • DataTemplate 对象没有 VisualTree 属性,不幸的是。而且我不能在 XAML 中这样做,原因太复杂,现在无法解释:/ @TonyVitabile
  • 其实根据这个:msdn.microsoft.com/en-us/library/…,确实如此。它继承自FrameworkTemplate
  • 是的,但我正在构建一个 Windows 应用商店应用程序。唯一可用的名为“DataTemplate”的类是:msdn.microsoft.com/en-us/library/windows/apps/…@TonyVitabile

标签: c# windows-8 windows-runtime


【解决方案1】:

The accepted answer to this question 展示了如何在后面的代码中构建DataTemplate

//create the data template
DataTemplate objDataTemplate = new DataTemplate();
objDataTemplate.DataType = typeof(CreditCardPayment);

//set up the stack panel
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackPanel));
spFactory.Name = "myFactory";
spFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal); // Use Oritentation.Vertical if appropriate.

//Your code for creating the buttons goes here.

//set the visual tree of the data template
objDataTemplate.VisualTree = spFactory;

应该可以的。

【讨论】:

  • 不幸的是,Windows 应用商店应用无法访问上述 FrameworkElementFactory 和 DataTemplate 类:/ 这是唯一可用的名为 DataTemplate 的类:msdn.microsoft.com/en-us/library/windows/apps/…
  • 对不起,你的问题原本没有这么说。您为什么不尝试在窗口资源中的 XAML 中使用简单的DataTemplate 构建一个测试应用程序,然后获取对资源的引用并检查它?这将向您展示您必须构建什么,然后您可以返回编写什么代码来生成类似的模板。
  • 这很有意义,将尝试。谢谢! @TonyVitabile
【解决方案2】:

创建一个新的StackPanel,将DataTemplate 对象添加为它的子对象。

StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(objDataTemplate);

您是在寻找这个(尽管您不能这样做),还是我误解了您的问题?

更新: 相反

DataTemplate objDataTemplate = new DataTemplate(typeof(StackPanel));
        FrameworkElementFactory stPanelElement = new FrameworkElementFactory(typeof(StackPanel));
        objDataTemplate.VisualTree = stPanelElement;

希望这会有所帮助。

【讨论】:

  • 我试图做相反的事情,将 StackPanel 分配给 DataTemplate。
  • 如果你同时拥有StackPanelDataTemplate,那你为什么要反其道而行之?
  • 不幸的是,Windows 应用商店应用无法访问提到的 FrameworkElementFactory 和 DataTemplate 类:/ @Debasis
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多