我的代码是这样的...
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
}
我的 ViewModel 看起来像这样......
class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
bool flag = Application.Current.MainWindow.IsInitialized;
if (flag)
{
// Do something...
}
}
我想我的问题是……这是否符合 MVVM 设计模式?唯一的其他方法是 How to fire a Command when a window is loaded in wpf
我不知道为什么,但我不想使用 mvvm-light 或任何其他样板代码..
最佳答案
Accessing UI component from ViewModel is violation of MVVM pattern.
Application.Current.MainWindow.IsInitialized
打破了这种模式。
自定义行为更符合 MVVM。因此,我建议采用您在问题中作为链接提到的方法。
访问 UI 组件会破坏 ViewModel 的可测试性。你会如何为你的 ViewModel 类编写测试用例?当您尝试通过单元测试对其进行测试时,Application.Current
将为 null
,它会抛出空引用异常。
One of the main motive of MVVM was to seperate UI logic from business logic so that business logic can be tested separately without worrying about its consumer which is view.
关于C# WPF MVVM 窗口加载绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20690219/