0

我已经使用 MVVM 模型大约一周了,我想我已经掌握了现在应该去哪里。请注意其中的“思考”。

我有一个 ViewModel,我的视图(MainWindow)绑定到

_ViewModel = new MainViewModel();
this.DataContext = _ViewModel;

我有一些 ICommands 可以在 ViewModel 和随后的 Model 中工作,我对此很好。

现在我从我在代码隐藏中执行的视图(MainWindow)启动几个窗口,因为它们都是纯粹的视图相关的东西。我正在尝试复制我在 View 中的 ViewModel 中的 ICommand 设置以简化我的生活,或者我是这么认为的。我有以下命令设置:

public ICommand comInitialiseWindows { get; private set; }

private bool _windowsactive = false;
public bool WindowsActive
{
    get { return _windowsactive; }
    set { SetProperty(ref _windowsactive, value); }
}
public bool comInitialiseWindows_CAN()
{
    return !_windowsactive;
}
private void comInitialiseWindows_DO()
{
    ... Code to do the window creation, etc.
}

我在 MainWindow 代码中有这个中继命令:

comInitialiseWindows = new RelayCommand(() => comInitialiseWindows_DO(), comInitialiseWindows_CAN);

如果我把它放在 ViewModel 中,除了创建窗口之外,它还可以作为一种享受,但由于它与 View 相关,我并不感到惊讶。

所以问题是当我点击按钮时代码没有运行。我猜测 XAML 绑定到 ViewModel,但是如果不将每个按钮的绑定设置为代码隐藏中的 MainWindow,我无法解决这个问题。我曾假设以下内容会起作用,但事实并非如此:

<Button x:Name="ribbutLayoutWindows"                                     
    Command="{Binding local:comInitialiseWindows}" 
    IsEnabled="{Binding local:comInitialiseWindows_CAN}"/>

我很确定我只是没有在某处得到什么。或者我试图使普通按钮单击就足够的事情变得过于复杂,因为它只是查看。

有什么建议么?

4

1 回答 1

1

有两种可能:

通过 ViewModel:您可以在 ViewModel 上公开一个属性:

class MainViewModel
{
    ICommand comInitialiseWindows  {get; set;}
}

在您的主窗口中:

MainViewModel vm = this.DataContext as MainViewModel;
vm.comInitialiseWindows  = new RelayCommand(() => comInitialiseWindows_DO(), comInitialiseWindows_CAN);

XAML:

<Button x:Name="ribbutLayoutWindows" Command="{Binding comInitialiseWindows}" />

注意:您不需要绑定IsEnabled属性。WPF 将为您处理该问题并自动调用您的 ICommand 的 CanExecute 方法。

通过 DependencyProperty

在你的代码隐藏中声明这个dependecyProperty:

public ICommand comInitialiseWindows
{
    get { return (ICommand)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

public static readonly DependencyProperty comInitialiseWindowsProperty = 
    DependencyProperty.Register("comInitialiseWindows", typeof(ICommand), typeof(MainWindow), new PropertyMetadata(null));

在代码隐藏中赋值:

comInitialiseWindows = new RelayCommand(() => comInitialiseWindows_DO(), comInitialiseWindows_CAN);

之后,您需要打破 XAML 中的数据上下文。首先,给你的页面起一个名字:

<Window x:Class="Web_Media_Seeker_WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:local="clr-namespace:Web_Media_Seeker_WPF"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="myWindow"
        Title="MainWindow" Height="350" Width="525">

然后按如下方式声明您的绑定:

<Button x:Name="ribbutLayoutWindows" Command="{Binding comInitialiseWindows, ElementName=myWindow}" />
于 2013-05-01T21:51:15.273 回答