contentControl 的 Content 属性绑定到 ContentControlVM 属性,只要 ContentControlVM 具体的实例变化,contentControl 就会更新成对应的 DataTemplate
这样的好处是不需要用 TemplateSelector
public class MainVM
{
public object ContentControlVM { get; set; }
public MainVM()
{
ContentControlVM = new TestVM2();
}
}
public class TestVM1
{
}
public class TestVM2
{
}
注意 DateTemplate 千万不要写成这样:
完全是两种意思,这样写不能生成页面元素。
附,
使用本文中方法 利用 Datatemplate 给 ContentControl 赋值的作法,也有弊端:
如果 TestVM1 或 TestVM2 对应的 DataTemplate 内容较多,这样每次重新加载 UI 会导致页面切换卡顿,解决方法:
可以使用多个 ContentControl 来展示各个页面:
注:虽然这样每个页面的构造函数不会执行,但是页面里的各个控件的类似 Loaded 之类事件还是会执行的。



