C#WPF以编程方式创建的DataTemplate Dockpanel和Stackpanel无效

时间:2011-01-24 22:51:17

标签: c# wpf custom-controls datatemplate frameworkelement

我正在尝试为列表框动态创建数据窗口。这适用于Custom UserControl。此UserControl具有 DependencyProperty ,可接受任何类型的 IEnumerable<>

这很好用......但输出总是

  • 财产/价值
  • 财产/价值

如果对象包含2个属性。但我希望这些属性并排排列。像:

对象1:

  • Porperty / Value Property / Value

对象2:

  • 物业/价值物业/价值

那我错在哪里?我首先在Stackpanel和Stackpanel中制作包含标签的Dockpanels。

这是一个关于当下情况的预览。enter image description here

所以这是我创建datatemplate的代码:

    DataTemplate _NewData = new DataTemplate();
    FrameworkElementFactory _template = new FrameworkElementFactory(typeof(StackPanel));

                foreach (var _FProperty in view.CurrentItem.GetType().GetProperties())
                {
                    FrameworkElementFactory _firstTemplateChild = new FrameworkElementFactory(typeof(DockPanel));

                    FrameworkElementFactory _childOneForDock = new FrameworkElementFactory(typeof(Label));

                    _childOneForDock.SetValue(Label.ContentProperty, _FProperty.Name);
                    _firstTemplateChild.AppendChild(_childOneForDock);
                    FrameworkElementFactory _childTwoForChild = new FrameworkElementFactory(typeof(Label));
                    _childTwoForChild.SetBinding(Label.ContentProperty, new Binding(_FProperty.Name));
                    _firstTemplateChild.AppendChild(_childTwoForChild);
                    _template.AppendChild(_firstTemplateChild);
                }
                _NewData.VisualTree = _template;
                ListBoxInPopUp.ItemTemplate = _NewData;

1 个答案:

答案 0 :(得分:2)

StackPanel的默认方向是垂直的。

您需要将方向设置为水平,以使内容并排显示。

MSDN中的代码示例中声明:

<!-- The items under this StackPanel are stacked Vertically. Note that Orientation 
     has a default value of "Vertical" but in this example the property is explicitely
     set for clarity. -->

(拼写错误全是他们的)

同样,DockPanel.Dock属性的默认值为Left,但我不确定这是否是这种情况的一个因素。

Source

相关问题