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

标签 c# wpf custom-controls datatemplate frameworkelement

我正在尝试为列表框动态创建数据模板。这是针对自定义用户控件的。此 UserControl 有一个 DependencyProperty,它接受任何类型的 IEnumerable<>

这工作正常......但输出总是

  • 属性(property)/值(value)
  • 属性(property)/值(value)

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

对象 1:

  • 属性(property)/值(value)属性(property)/值(value)

对象 2:

  • 属性/值(value)属性/值(value)

那么我哪里错了?我首先制作一个 Stackpanel,然后在 Stackpanel 中制作包含标签的 Dockpanel。

这是它目前的一个小预览。 enter image description here

所以这是我创建数据模板的代码:

    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;

最佳答案

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

关于C# WPF 在 Stackpanel 中以编程方式创建的 DataTemplate Dockpanel 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4788137/

相关文章:

c# - 如何进行服务器端 C# SQL 验证

c# - .NET 多维数组打印

c# - 如何在 C# 中从另一个启动应用程序?

c# - CS0672 : Member `Foo.OnSelected()' overrides obsolete member `Baz.OnSelected()'

wpf - XAML 与代码中的非中断空间

c# - 为什么我的触发器以空白控件结束?

WPF:指针下的颜色

winforms - 如何覆盖 UserControl 类以绘制自定义边框?

delphi - 判断一个点是否在多边形内?

custom-controls - 如何在JavaFX中获取鼠标的位置?