如何在WPF中多次使用同一视图?[duplicate]

hvvq6cgz  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(168)

此问题在此处已有答案

ItemsControl ItemTemplate Binding(1个答案)
5天前关闭。
我有一个用户控件StudentView.xaml,类似于以下内容:

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

我还有一个模型Student.cs,它类似于:

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");}
}

在我的ViewModelMainViewModel中,我有一个Student的集合,如下所示:

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

// Do something here to populate Students

NumOfStudents = Students.Count();

在我的主窗口中,我看到了如下内容:

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

我是WPF的新手,正在寻求帮助。我知道如何将local:StudentView绑定到一个学生。我的问题是,是否有办法使用local:StudentView的次数与使用NumOfStudents的次数一样多。例如,如果我有5个学生,主窗口将显示StudentView5次。

kgsdhlau

kgsdhlau1#

您最需要的可能是ItemsControl。您将ItemsSource属性设置为可观察的集合,并定义ItemTemplate以定义项的呈现方式(StudentView.xaml)。最后,由于您使用的是StackPanel,因此将其定义为ItemsPanelTemplate。

knpiaxh1

knpiaxh12#

你会想做一些像...

<ItemsControl
    ItemsSource="{Binding Students}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:StudentView/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

相关问题