2012-02-12 62 views
1

我正在使用MDI解决方案(请参阅http://wpfmdi.codeplex.com/)和MVVM。防止在MVVM/MDI应用程序中几乎重复的RelayCommands

我用一个RelayCommand到工具栏和/或菜单绑定到主视图模型,如:

ICommand _editSelectedItemCommand; 
    public ICommand EditSelectedItemCommand 
    { 
     get 
     { 
      return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => CurrentChildViewModel.EditSelectedItem(), 
       param => ((CurrentChildViewModel != null) && (CurrentChildViewModel.CanExecuteEditSelectedItem)))); 
     } 
    } 

然而,在子窗口,一个按钮绑定到相同的功能,我需要另一个RelayCommand这除了直接调用方法EditSelectedItem和CanExecuteEditSelectedItem之外几乎是相等的。它看起来像:

ICommand _editSelectedItemCommand; 
    public ICommand EditSelectedItemCommand 
    { 
     get 
     { 
      return _editSelectedItemCommand ?? (_editSelectedItemCommand = new RelayCommand(param => EditSelectedItem(), 
       param => CanExecuteEditSelectedItem)))); 
     } 
    } 

我需要大约10和将来可能50个以上这样的命令,所以我想现在要做的正确方法。 有没有办法阻止这种或更好的方式来做到这一点?

回答

2

您可以从主视图模型中删除第一个命令,因为子视图模型中的命令已经绰绰有余。

就这样使用绑定在XAML标记:

<Button Command="{Binding CurrentChildViewModel.EditSelectedItemCommand}" 
     Content="Button for the main view model" /> 

另外,如果我正确地理解你的代码,它如果CurrentChildViewModel属性为null比命令将被禁用的规定。 如果你需要这样的行为,你应该将这个转换器添加到您的代码,并稍微改写结合:

public class NullToBooleanConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return value != null; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 

XAML:

<Application.Resources> 
    <local:NullToBooleanConverter x:Key="NullToBooleanConverter" /> 
</Application.Resources> 
<!-- your control --> 
<Button Command="{Binding CurrentChildViewModel.EditSelectedItemCommand}" 
     IsEnabled="{Binding CurrentChildViewModel, Converter={StaticResource NullToBooleanConverter}}" /> 
+0

对不起它花了一点时间来检查它是否工作(我我只是WPF的初学者,所以我花了一些时间来改变这里和那里的东西)。您的解决方案效果很好,我还了解了更多关于转换器的信息。感谢您花时间解决问题! – 2012-02-13 02:03:45

+0

我测试了它,它的工作原理,谢谢。然而,对于几种方法,我需要一个更复杂的IsEnabled功能,我应该调用IsEnabled = {Binding CurrentChildViewModel.CanExecuteSelectedItem}并实现该功能内部的逻辑和/或在这种情况下是否需要转换器?提前致谢。 – 2012-02-14 09:22:20

+0

我在http://stackoverflow.com/questions/9274498/relaycommands-from-view-to-child-view添加了一个额外的问题...我很新,所以我不知道这是'正常的工作方式'。 – 2012-02-14 09:39:40