Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - How to avoid the View being disposed

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

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

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.

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!

How can I prevent the View object to be deleted/discarded?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
    ...
 }

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...