【问题标题】:C# WPF Programatically created DataTemplate Dockpanel in Stackpanel has no effectC# WPF 在 Stackpanel 中以编程方式创建的 DataTemplate Dockpanel 没有效果
【发布时间】:2011-01-24 22:51:16
【问题描述】:

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

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

  • 属性/价值
  • 属性/价值

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

对象 1:

  • 财产/价值财产/价值

对象 2:

  • 属性/值 属性/值

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

这里有一个小预览它现在的样子。

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

    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;

【问题讨论】:

    标签: c# wpf custom-controls datatemplate frameworkelement


    【解决方案1】:

    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

    【讨论】:

    • 但是stackpanel中的dockpanel不应该把它们并排排列吗?
    • @Mark - 你也没有设置Dock 属性(或者我错过了那一点?)
    • 否,因为当我通常不设置 Dock 属性时,我在 Dockpanel 中的项目是并排排列的?我试过 _childOneForDock.SetValue(DockPanel.DockProperty, Dock.Left);和 _childTwoForChild.SetValue(DockPanel.DockProperty, Dock.Right);这没有任何影响:(
    • @Mark 我知道这已经很晚了,但是您是否尝试设置 dockPanel.LastChildFill = true; 以使您的第二个孩子完全正确?
    猜你喜欢
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2011-05-20
    • 2014-07-04
    • 2011-05-18
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多