C# WPF Programatically created DataTemplate Dockpanel in Stackpanel has no effect

人盡茶涼 提交于 2020-01-15 08:20:19

问题


I'm trying to dynamically create a datatemplate for a listbox. This is for a Custom UserControl. This UserControl has a DependencyProperty which accepts any types of IEnumerable<>.

This works fine... But the Output is always

  • Property / Value
  • Property / Value

if the objects contains 2 Properties. But i want that the properties are arranged side by side. Like:

Object 1:

  • Porperty / Value Property / Value

Object 2:

  • Property / Value Property / Value

So where am i wrong ? i'm making first a Stackpanel and in the Stackpanel, Dockpanels which contain the Labels.

Here is a little preview how it looks at the moment.

So this is my code to create the 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:


The default orientation of a StackPanel is vertical.

You'll need to set the orientation to horizontal to get the contents to appear side-by-side.

In the code example in the MSDN it states:

<!-- 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. -->

(spelling mistakes are all theirs)

Also the default value of the DockPanel.Dock property is Left, though I'm not sure if that's a factor in this case.

Source



来源:https://stackoverflow.com/questions/4788137/c-sharp-wpf-programatically-created-datatemplate-dockpanel-in-stackpanel-has-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!