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

Edited Issue: RelayCommand fails if delegate contains a non-constant method parameter [7605]

$
0
0
I've come across what I think is a bug in RelayCommand (at least for WPF 4.0):
* If you attempt to construct a RelayCommand with a lambda expression composed entirely of compile-time constants, e.g., __() => DoSomething(2)__, it works as expected.
* However, if the lambda expression contains a method call with a parameter, and the value passed into that parameter is determined at runtime, e.g., __() => DoSomething(number)__, nothing happens when the command is executed.

If you put the code below into a WPF 4.0 project and build it in Debug mode, you will notice that if you click "Do Something", nothing happens, but if you click "Do Something Else", a "2" appears in the output window. (Similarly, if you put a breakpoint in the DoSomething method, it will only be hit if you click "Do Something Else".)

MainWindow.xaml:

```
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
x:Class="WpfApplication1.MainWindow"
Title="MainWindow"
Height="400"
Width="400">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<StackPanel>
<Button Content="Do Something"
Command="{Binding DoSomethingCommand}" />
<Button Margin="0,10,0,0"
Content="Do Something Else"
Command="{Binding DoSomethingElseCommand}" />
</StackPanel>
</Window>
```

MainWindowViewModel.cs

```
namespace WpfApplication1
{
public class MainWindowViewModel : ViewModelBase
{
public ICommand DoSomethingCommand { get; private set; }
public ICommand DoSomethingElseCommand { get; private set; }

public MainWindowViewModel()
{
DoSomethingCommand = GetCommand(2);
DoSomethingElseCommand = new RelayCommand(() => DoSomething(2));
}

private ICommand GetCommand(int number)
{
return new RelayCommand(() => DoSomething(number));
}

private void DoSomething(int number)
{
Debug.Print(number.ToString());
}
}
}
```

Viewing all articles
Browse latest Browse all 1826

Trending Articles