Search code examples
wpfdatacontextstackpanel

WPF add StackPanel child control from DataContext by XAML


I want WPF read C# Object's properties. And convert these properties name to WPF's Label controls.


Solution

  • The StackPanel does NOT generate items. It's only a Panel, whose function is Layout only.

    You're looking for an ItemsControl:

    <ItemsControl ItemsSource="{Binding}">
       <!-- ... -->
    </ItemsControl>
    

    which, by default will have a StackPanel as it's ItemsPanel.

    Notice also that setting the DataContext to a single instance of a class will NOT make the ItemsControl create any elements. You need to set the ItemsSource property to an IEnumerable (for example a List<MyClass> or the like).

    //Window Constructor
    public MainWindow()
    {
        DataContext = New List<MyClass>
                      {
                          //.. Items here
                      };
    }
    

    And no, WPF does not automatically read Attributes from properties. You can create a ViewModel which does that, or hard-code the display names in XAML.