在父控件中延迟加载用户控件

时间:2012-05-01 01:12:27

标签: wpf

我有一些方案,我有一些用户控件让我们说:

  1. CreateStudents
  2. CreateTeachers
  3. 每个User控件都有自己的View模型。 datacontext在初始化中设置。

    我有一个主UI,可以加载上述用户控件。因此设置datacontext工作正常。

    问题陈述 我有另一个用户控件“CreateClass”,它是一组选项卡。从这里我可以转到上面两个用户cotrols(隐藏标签)。

    datacontext由CreateClassViewModel“CreateStudentManager”和“CreateTeacherManager”中的两个属性设置。

    这很好但问题是当我默认打开CreateClass UI时,其他用户控件也会加载(我猜因为它们有默认构造函数)。

    因为当我打开CreateClass时,我不希望加载其他控件。只有在明确地从Create Class UI调用它们时才应加载它们。

    如何实现这一目标?

    下面的

    是一个“CreateStudent”的样本

    <TabItem Header="Students" Visibility="{Binding IsStudentVisible, Converter={StaticResource BooleanToVisibilityConverter}}" >
                    <Grid>
                        <local:UCCreateStudent DataContext="{Binding CreateStudentManager}"/>
                    </Grid>
                </TabItem>
    
    • 吉里贾

2 个答案:

答案 0 :(得分:0)

最简单的方法是在代码中执行,即。在所需的事件触发器上将local:UCCreateStudent项添加到网格。给网格命名(例如x:Name =“MyGrid”),然后是

 void OnTrigger(...)
 {
      UCCreateStudent NewStudent = new UCCreateStudent();
      // extra code for setting the datacontext and any other layout properties
      MyGrid.Children.Add(NewStudent);
 }

答案 1 :(得分:0)