-2

I have a user control StudentView.xaml that is something like this:

<Grid>
 <TextBlock Text="{Binding StudentName}"/>
 <TextBlock Text="{Binding StudentID}"/>
</Grid>

I also have a model Student.cs that is something like this:

private string _StudentName = null;
public string StudentName{
 get => _StudentName;
 set {_StudentName = value; OnPropertyChange("StudentName");}
}

private string _StudentID = null;
public string StudentID{
 get => _StudentID ;
 set {_StudentID = value; OnPropertyChange("StudentID");}
}

In my ViewModel MainViewModel I have a collection of Student's like this:

ObservableCollection<Student> Students = new ObservableCollection<Student>();

// Do something here to populate Students

NumOfStudents = Students.Count();

In my main window, I have something like this:

<StackPanel>
 <local:StudentView/>
</StackPanel>

I am very new to WPF and seeking for help. I know how to bind local:StudentView to one student. My question is that is there a way to use local:StudentView as many as time as NumOfStudents. For example, if I have 5 students, the main window will display StudentView 5 times.

Jtastic
  • 7
  • 5

2 Answers2

0

What you most likely want is a ItemsControl. You will set the ItemsSource property to your observable collection and define a ItemTemplate to define how the items should be rendered (StudentView.xaml). Finally, since you are using a StackPanel, that will be defined as your ItemsPanelTemplate.

Tarazed
  • 1,707
  • 1
  • 7
  • 22
0

You'll want do something like...

<ItemsControl
    ItemsSource="{Binding Students}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:StudentView/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Clemens
  • 123,504
  • 12
  • 155
  • 268
Alex King
  • 26
  • 1