Question

I'm using an MDI solution (see http://wpfmdi.codeplex.com/) and MVVM.

I use one RelayCommand to bind the toolbar and/or menu to the Main ViewModel, like:

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

However, in the child window, to bind a button to the same functionality I need another RelayCommand which is almost equal except it calls the methods EditSelectedItem and CanExecuteEditSelectedItem directly. It would look like:

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

I need about 10 and in the future maybe 50 or more of such commands so I like to do it the right way now. Is there a way to prevent this or a better way to do this?

Était-ce utile?

La solution

You can remove the first command from the main viewmodel, because the command in the child viewmodel is more than enough.

Just use the binding like this in the xaml markup:

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

Also if I understand your code correctly, it has the stipulation that if the CurrentChildViewModel property is null than the command will be disabled. If you need such behavior, you should add this converter to your code and slightly rewrite the binding:

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}}" />
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top