关于 ViewModel 和 View 交互

About ViewModel and View interaction

我有一个关于它是如何工作的问题,目前我正在上大学,我无法向我的教授询问这个问题,希望你们能帮助我。

所以,我在 xaml 中制作了一个登录面板 (出于安全原因,密码的东西有 class,http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html 如果有人感兴趣的话) 我的问题是,每当我在我的 2 个文本框上写东西时,我都希望它进入下一个 Window/Xaml 表格。我尝试在 VkiewModel 中创建一个新的表单实例(Form2 form = new Form2,然后使用 form.show()),但根据教授所说的 MVVM 模式,ViewModels 不应该创建视图。我该如何解决?

xmlns:vm="clr-namespace:SchoolManagement.ViewModels"
xmlns:ff="clr-namespace:SchoolManagement.Extras"
<Window.DataContext>
    <vm:LoginViewModel />
</Window.DataContext>


 <Label Content="Email" HorizontalAlignment="Left" Margin="338,125,0,0" VerticalAlignment="Top"/>
 <TextBox Text="{Binding Email}" HorizontalAlignment="Left" Height="25" Margin="338,155,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="250" TextAlignment="Center" />

 <Label Content="Password" HorizontalAlignment="Left" Margin="338,185,0,0" VerticalAlignment="Top"/>
 <PasswordBox ff:PasswordBoxAssistant.BindPassword="true" ff:PasswordBoxAssistant.BoundPassword="{Binding Path=Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" MaxLength="25" HorizontalAlignment="Left" Margin="338,215,0,0" VerticalAlignment="Top" Width="250"/>

 <Button x:Name="btnLogin" Content="Login" HorizontalAlignment="Left" Margin="513,243,0,0" VerticalAlignment="Top" Width="75" Command="{Binding LoginCommand}" Height="22"/>

如果您打算在没有外部框架的情况下执行此操作,则需要在视图模型中创建一个视图可以订阅的事件。

SomeViewModel.cs

public class GenericViewRequestedEventArgs : EventArgs
{
    public GenericViewModel ViewModel { get; private set; }

    public GenericViewRequestedEventArgs(GenericViewModel viewModel)
    {
        ViewModel = viewModel;
    }
}

public class SomeViewModel : ViewModelBase
{
    private RelayCommand _loginCommand;

    public ICommand LoginCommand
    {
        get
        {
            if (_loginCommand == null)
                _loginCommand = new RelayCommand(x => Login());

            return _loginCommand;
        }
    }

    public EventHandler<GenericViewRequestedEventArgs> GenericViewRequested;

    private void OnGenericViewRequested(GenericViewModel viewModel)
    {
        var handler = GenericViewRequested;
        if (handler != null)
            handler(this, new GenericViewRequestedEventArgs(viewModel));
    }

    private void Login()
    {
        // Do login stuff, authenticate etc.

        // Open new window.
        OnGenericViewRequested(_specificViewModel);
    }
}

SomeWindow.xaml.cs

public partial class SomeWindow : Window
{
    private void OnGenericViewRequested(object sender, GenericViewRequestedEventArgs e)
    {
        GenericWindow window = new GenericWindow(e.ViewModel);
        window.Owner = this;
        window.ShowDialog();
    }

    public SomeWindow()
    {
        InitializeComponent();

        var viewModel = new SomeViewModel();
        viewModel.GenericViewRequested += OnGenericViewRequested;

        this.DataContext = viewModel;
    }
}