Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 使用ContentControl生成视图(UserControls)_Wpf_Mvvm_Wpf Controls - Fatal编程技术网

Wpf 使用ContentControl生成视图(UserControls)

Wpf 使用ContentControl生成视图(UserControls),wpf,mvvm,wpf-controls,Wpf,Mvvm,Wpf Controls,我有一个UserControl(MainView),它需要在自身内部显示另一个UserControl。根据某些情况,它将显示AView或BView(它们都显示在MainView中的同一位置)。我使用的是ViewModel first方法,因此视图是通过数据模板生成的: public class AView : UserControl { } public class BView : UserControl { } public class AViewModel : ViewModelBase {

我有一个UserControl(MainView),它需要在自身内部显示另一个UserControl。根据某些情况,它将显示AView或BView(它们都显示在MainView中的同一位置)。我使用的是ViewModel first方法,因此视图是通过数据模板生成的:

public class AView : UserControl { }
public class BView : UserControl { }
public class AViewModel : ViewModelBase { }
public class BViewModel : ViewModelBase { }
从资源使用角度来看,这两种方法之间是否存在差异:

1) 只有一个内容控制

<ContentControl Content="{Binding SomeViewModel}" />

private ViewModelBase _someViewModel;
public ViewModelBase SomeViewModel
{
    get {return _someViewModel;}
    set
    {
        if (!ReferenceEquals(_someViewModel, value))
        {
            _someViewModel = value;
            RaisePropertyChange(SomeViewModel);
        }
    }
}

私有视图模型库_someViewModel;
公共ViewModelBase SomeViewModel
{
获取{return\u someViewModel;}
设置
{
如果(!ReferenceEquals(_someViewModel,value))
{
_someViewModel=值;
RaisePropertyChange(SomeViewModel);
}
}
}
通过这种方式,我可以选择将哪个ViewModel(AViewModel或BViewModel)设置为SomeViewModel,DataTemplates将选择要显示的适当视图

2) 放置两个ContentControls,并控制每个控件的可见性(一次只能看到一个)



因此,从资源管理的角度来看,这两个视图之间的切换行为是否会有所不同,或者在这两种情况下,在给定时间内存中只会驻留一个视图?

WPF卸载不可见的对象,因此在任何给定时间,两种方法都只会加载一个视图,但是,第二个方法将在UI中创建两个ContentControl,而第一个方法只创建一个

此外,每当内容视图模型发生更改时,都会增加(很小的)评估
可见性的开销。由于您正在将
内容设置为
ViewModel
,因此
DataTemplate
将以任何方式进行评估,WPF必须通过查找
DataTemplate
来确定如何绘制该ViewModel


就我个人而言,我更喜欢第一个版本。它更易于维护和管理,尤其是当您有两个以上的视图,并且UI中一次只有一个
ContentControl

是的,有两个ContentControl会占用更多的资源,而且,由于您声明所有不可见的对象都将从内存中卸载,这意味着没有必要使用两个ContentControl。
<ContentControl Content="{Binding AViewModel}"
                Visibility="{Binding SomeCondition}" />

<ContentControl Content="{Binding BViewModel}"
                Visibility="{Binding NotSomeCondition}" />