C # WPF MVVM Window OnLoad Binding

My code looks like this ...

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
    }
}

My ViewModel looks like this:

class MainWindowViewModel : INotifyPropertyChanged
{
    public MainWindowViewModel()
    {
        bool flag = Application.Current.MainWindow.IsInitialized;

        if (flag)
        {
            // Do something...
        }

    }

I think my question is ... Does this fit the MVVM pattern? The only way to do this is How to run a command when loading a window in wpf

I do not know why, but I do not want to use mvvm-light or any other boilerplate code.

+4
source share
5 answers

Access to the user interface component from ViewModel is a violation of the MVVM pattern.

Application.Current.MainWindow.IsInitialized violates this pattern.

User behavior is more consistent with MVVM. So, I would suggest going with the approach that you mentioned as a reference in your question.


ViewModel. ViewModel? Application.Current null, unit test, .

MVVM , - , , .

+4

"" MVVM . , VIew - MVVM, ViewModel - , -.

ViewModel View - , View.

, , . , , ViewModel, VM . # 5 async/await .

+1

, / , , . . . , .

, , . . , / . , .

, , , . , , . , "" , " " . , , / /etc.

, , . 100% MVVM, FrameworkElement , , .

, . IViewModel :

public interface IViewModel : INotifyPropertyChanged
{
    void Load();
    void Unload();
}

:

ViewModelBehavior.LoadUnload="True"

, XAML - , , .

+1

, , , .

MVVM-Light, caliburn micro. MVVM. Caliburn micro . , - MVVMy..

0

, MVVM , , Application.Current null, MainViewModel UnitTests. NullPointerException .

You should consider using an event Initializedif you want to make sure that something is already initialized. But you create ViewModelafter you called InitializeComponent- I would just leave the check.

0
source

All Articles