Search code examples
mvvmcontrolsobservablecollectionstackpanel

Programmatically populate a stackpanel with an observablecollection of user controls using MVVM


I have an observablecollection of type frameworkelement that I would like to display in a stackpanel or something similar. Every item in the observablecollection is a usercontrol that I have created. I'm pretty new to WPF and I don't have any idea how to do this. An example would be much appreciated


Solution

  • I'm borrowing rhe1980's answer a bit here, but the point is that the code in the codebehind will actually be in a viewmodel.

    View:

    <Window x:Class="Sandbox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    Name="mainWindow">
    <Grid>
    <StackPanel>
        <ItemsControl ItemsSource="{Binding Path=MyCollection}"/>                           
    </StackPanel>         
    </Grid>
    

    CodeBehind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MyViewModel();
        }
    }
    

    ViewModel:

        public class MyViewModel: INotifyPropertyChanged
    {
    
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (!string.IsNullOrEmpty(propertyName))
            {
                if (this.PropertyChanged != null)
                    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
            this.OnObjectChanged();
        } 
    
       private ObservableCollection<FrameworkElement> _myCollection;
       public ObservableCollection<FrameworkElement> MyCollection
        {
            get
            {
                return _myCollection;
            }
            set
            {
                _myCollection = value;
                OnPropertyChanged("MyCollection");
            }
        }     
    }