1

I want to check the value of the ViewModel when my UserControl is going to unload. I want to do it using getting the variable value directly from the DataContext, the problem is that in the Unloaded event, the DataContext is equals to null. Is there a way to get the value from my ViewModel?

I'm trying somethin like this:

public MyView()

    {
        InitializeComponent();
        Unloaded += (a, b) =>
        {
            var dc = DataContext as MyViewModel;
            if (dc.IsChanged == true)
                Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("ARE YOU SHURE YOU WANT TO EXIT WITHOUT SAVING CHANGES?", "WARNING", MessageBoxButton.OKCancel, MessageBoxImage.Warning)), System.Windows.Threading.DispatcherPriority.Normal);
        };
    }
Paul Miranda
  • 738
  • 17
  • 39
  • 2
    It seems very late in the life-cycle. What do you do if they user selects cancel? Just curios – Rob Goodwin Jul 01 '20 at 18:42
  • @RobGoodwin You are right. Is there a way to handle this early in the life cycle to check if the user selected cancel? – Paul Miranda Jul 01 '20 at 19:20
  • 1
    This is really a question of how things are implemented. Without knowing exactly what you are doing, I would typically have a user control contained in some view which as a view model associated with it. You are changing some state that causes you to want to close the parent of the user control. That decision point seems to be the easiest place to query the user for the information you are after before destroying things. Granted this is just how I might go about things with limited knowledge of what you are doing for real. – Rob Goodwin Jul 01 '20 at 19:23
  • @RobGoodwin Thank you :) This will give me and idea on how to handle this situation – Paul Miranda Jul 01 '20 at 21:34

2 Answers2

1

Keep a reference to the last non-null value of the DataContext property:

private MyViewModel viewModel;

public MyView()
{
    InitializeComponent();

    DataContextChanged += (s, e) =>
    {
        if (DataContext is MyViewModel vm)
        {
            viewModel = vm;
        }
    };

    Unloaded += (s, e) =>
    {
        if (viewModel != null && viewModel.IsChanged)
        {
            ...
        }
    };
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
-1

try the Closing event instead and to be more MVVM friendly i suggest you this answer

MVVM Wpf Closing Window

Redouane
  • 3
  • 2