简体   繁体   English

在WPF中将DataPresenter与DataTemplate一起使用时销毁视图

[英]Destroy view while using ContentPresenter in wpf with DataTemplate

I'm currently using a ContentPresenter to display different views in a UserControl like this : 我目前正在使用ContentPresenter在这样的UserControl中显示不同的视图:

 <ContentPresenter Content="{Binding ContentSourceVm}"/>

Each values set to ContentSourceVm are mapped to DataTemplates: 设置为ContentSourceVm的每个值都映射到DataTemplates:

 <DataTemplate DataType="{x:Type adminViewModel:AdminAccountViewModel}">
    <administration:AdminAccountView/>
 </DataTemplate>
 <DataTemplate DataType="{x:Type adminViewModel:AdminCalibrationViewModel}">
    <administration:AdminCalibrationView/>
 </DataTemplate>

When I set a new VM to ContentSourceVm, the view is correctly changed but unfortunately the first view is not freed even after a certain amount of time. 当我将新的VM设置为ContentSourceVm时,视图已正确更改,但不幸的是,即使经过一定时间,第一个视图也无法释放。 (the destructor of the previous view is not called) (未调用前一个视图的析构函数)

What is the best practice to manage this? 管理此问题的最佳做法是什么?

I've look for solution using DataTemplateSelector but without success. 我一直在寻找使用DataTemplateSelector的解决方案,但没有成功。 I've seen some example which send the type of the view using the messenger to free the view associatated to the view model during the dispose of this one but I do not want to create strong relation between my VM and my View. 我已经看到了一些示例,该示例在处理该视图的过程中使用Messenger来发送视图的类型以释放与视图模型相关联的视图,但是我不想在VM和View之间建立牢固的关系。

Thanks! 谢谢!

in ViewModel,before you change the view model with new view models,dispose the current one : 在ViewModel中,在使用新视图模型更改视图模型之前,请处置当前模型:

private _contentSourceVm;
prop ContentSourceVm
{
  get
   {
     return _contentSourceVm;
   }
  set
   {
     IDisposable disp=_contentSourceVm as IDisposable ;
     if(disp!=null)
     {
      disp.Dispose();
     }
     _contentSourceVm=value;
     OnpropertyChnaged();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM