如何避免视图布置 [英] How to avoid the View being disposed

查看:146
本文介绍了如何避免视图布置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 ContentControl中 IM我的WPF应用程序,以显示不同的查看的用户。

I'm using a ContentControl im my WPF application to show different Views to the user.

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



按下一个按钮,用户可以切换值 CurrentPageViewModel 到其他的视图模型的对象,并使用的DataTemplate ,开关的帮助下到另一个的查看的。

By pushing a button the user can switch the value of CurrentPageViewModel to another ViewModel object and, with the help of a DataTemplate, switch to another View.

<DataTemplate DataType="{x:Type viewModel:AdministrationViewModel}">
    <view:AdministrationView />
</DataTemplate>
<DataTemplate DataType="{x:Type viewModel:HealthViewModel}">
    <view:HealthView />
</DataTemplate>



到目前为止好。

So far so good.

我的问题开始每当查看的切换。这时老的查看的被丢弃,框架删除/释放的查看的对象。因此,

My problem starts whenever the View is switched. Then the old View is discarded and the Framework deletes/disposes the View object.

网格排序设置都将丢失,更糟的是,一些的查看的值设置为null。 NULL值将被传播到我的视图模型的通过数据绑定,这完全以弄乱了我的视图模型的数据!

Grid sort settings are therefore lost and what's even worse, some of the Views values are set to null. The null values are propagated to my ViewModel by Databinding, which totaly messes up my ViewModel data!

如何防止被删除View对象/丢弃?

推荐答案

最简单,但非常强大的解决方案,以控制你的观点的生活用变频器替代的DataTemplates的:

Simplest but very powerfull solution to control your views' life is using converter instead of datatemplates:

<ContentControl  Content="{Binding CurrentPageViewModel, Converter={StaticResource ViewModelToViewConverter}"/>





public class ViewModelToViewConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null) return null;

       //use naming convention or custom settings here to get view type
        var viewModelType = value.GetType();
        var viewType = ... 

        var view = (FrameworkElement) YourIocContainer.Resolve(viewType);
        view.DataContext = value;
        return view;
    }
    ...
 }

您需要设置你的IoC因此对于特定视图将返回单一实例。国际奥委会也可以让你依赖项injecion到您的看法。取而代之的IoC您可以使用自己的工厂模式的实现。

You need to setup your IoC so for particular view's it will return singleton instance. IoC also allows you dependency injecion into your views. Instead of IoC you may use your own factory pattern implementation.

然而,视图模型的属性不应该乱,当视图是从视觉3断开。有可能是在绑定的另一个问题,你应该打开新的问题为这个

However, ViewModel properties should not be messed, when view is disconnected from visual three. There's probably another issue in bindings and you should open new question for this

这篇关于如何避免视图布置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆