Quantcast
Channel: MVVM Light Toolkit
Viewing all articles
Browse latest Browse all 1826

Commented Unassigned: Closures not working with RelayCommand [7721]

$
0
0
I'm using `RelayCommand` with a WPF project (.NET 4.6.1), and if the provided action contains local variables (closures), the command fails silently (the action is not executed and no exception is thrown).

This code fails:

```
public ICommand GenerateCommand { get; private set; }

public MainWindowViewModel(FileDialogPresenter fileDialogPresenter, TextFileProcessor textFileProcessor)
{
GenerateCommand = new RelayCommand(() => GenerateJsonFiles(fileDialogPresenter, textFileProcessor));
}

private void GenerateJsonFiles(FileDialogPresenter fileDialogPresenter, TextFileProcessor textFileProcessor)
{
// do work
}
```

This also fails:

```
public ICommand GenerateCommand { get; private set; }

public MainWindowViewModel(FileDialogPresenter fileDialogPresenter, TextFileProcessor textFileProcessor)
{
Action generateAction = () => GenerateJsonFiles(fileDialogPresenter, textFileProcessor);
GenerateCommand = new RelayCommand(generateAction);
}

private void GenerateJsonFiles(FileDialogPresenter fileDialogPresenter, TextFileProcessor textFileProcessor)
{
// do work
}
```

This works:

```
private readonly FileDialogPresenter _fileDialogPresenter;
private readonly TextFileProcessor _textFileProcessor;

public ICommand GenerateCommand { get; private set; }

public MainWindowViewModel(FileDialogPresenter fileDialogPresenter, TextFileProcessor textFileProcessor)
{
_fileDialogPresenter = fileDialogPresenter;
_textFileProcessor = textFileProcessor;
GenerateCommand = new RelayCommand(GenerateJsonFiles); // no closures
}

private void GenerateJsonFiles()
{
// do work (uses fields instead of arguments)
}
```
Comments: Thanks for your reply, Laurent. I'm sure you've seen this already, but here's a relevant [StackOverflow question](http://stackoverflow.com/questions/25730530/bug-in-weakaction-in-case-of-closure-action) on the topic. If the solutions proposed in the answers aren't feasible to implement, it might help to at least mention the limitations on the action in the XML documentation comments for the `RelayCommand` constructor: Suggestion: ``` /// <summary> /// Initializes a new instance of the RelayCommand class that /// can always execute. /// </summary> /// <param name="execute">The execution logic. Note that closures are not supported due to the use of WeakActions (see http://stackoverflow.com/questions/25730530/).</param> /// <exception cref="ArgumentNullException">If the execute argument is null.</exception> public RelayCommand(Action execute) : this(execute, null) { } ```

Viewing all articles
Browse latest Browse all 1826

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>