【问题标题】:Open a new window in WPF using MVVM [duplicate]使用 MVVM 在 WPF 中打开一个新窗口 [重复]
【发布时间】:2018-01-23 05:48:34
【问题描述】:

我是 MVVM 的新手。我有一个窗口 Demo.xaml,它有菜单,在菜单下我有子菜单。我想打开子菜单窗口,即使用 MVVM 方法单击子菜单时的 Test.Xaml。 我制作了一个测试窗口对象,但它没有显示“显示”属性。 我也尝试过使用委托命令,但我失败了。 我怎样才能做到这一点?

【问题讨论】:

  • 当您说 MVVM 方法时,您的意思是 ViewModel 应该能够生成一个新窗口吗?

标签: wpf mvvm


【解决方案1】:

解决问题的最常见 MVVM 方法是将子菜单项的“Command”绑定到 ViewModel 中实现 ICommand 的属性。然后,在命令的执行中,您可以打开您选择的窗口。

【讨论】:

    【解决方案2】:

    您需要使用 ICommand - 在使用 MVVM 时使用 RelayCommand 是最佳做法。

    请参阅下面的示例:

    MainWindow.xaml

    <MenuItem Header="Settings" Command="{Binding CmdOpenSetting}" >                    
        <MenuItem.Icon>
            <Image Source="..\Resources\if_Gnome-Preferences-System.png" Height="16" Width="16" Margin="0,0,-5,0" />
        </MenuItem.Icon>
    </MenuItem>
    

    MainWindow.xaml.cs

    public MainWindow()
    {
        InitializeComponent();
    
        //Singelton not needed
        MainWindowViewModel.Instance = new MainWindowViewModel();
        this.DataContext = MainWindowViewModel.Instance;
    
        //Also works
        this.DataContext = new MainWindowViewModel();
    }
    

    MainWindowViewModel.cs

    private RelayCommand _commandOpenSettings;
    
    public ICommand CmdOpenSetting
    {
        get
        {
            if(_commandOpenSettings.IsNull())
            {
                _commandOpenSettings = new RelayCommand(param => OpenSettings());
            }
            return _commandOpenSettings;
        }
    }
    

    注意你可能需要根据你对RelayCommand的实现来调整CmdOpenSetting

    Example RelayCommand

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多