Q:I am following MVVM pattern. I want to pass property value of a control to "CommandParameter" property of same control . But runtime exception of "Object reference not set to an instance of object" is being faced.
XAML:
<Button
x:Name="btnBrowseFirmware1"
Grid.Row="2"
Grid.Column="1"
Width="135"
Height="35"
Command="{Binding OpenFileDialogCommand}"
CommandParameter="{Binding Name ,ElementName=btnBrowseFirmware1}"
Content="Browse "
Foreground="White"
/>
Viewmodel:
public class ConfigurationParametersViewModel : WorkspaceViewModelBase
{
public ICommand OpenFileDialogCommand { get; private set; }
public ConfigurationParametersViewModel()
: base("ConfigurationParameters", true)
{
OpenFileDialogCommand = new RelayCommand<string>(OpenFileDialogCommandFunc);
}
private void OpenFileDialogCommandFunc(string browseButtonName)
{
OpenFileDialog fileDialog = new OpenFileDialog();
Some Code...
}
}
A:
While changing the binding to CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"
(as Mr.B suggested) will solve your problem, I would recommend not to send UI Element names to the ViewModel. This will "break" the MVVM pattern. Make a command foreach Open File Action. This will also avoid a long if(browserButtonName= "thisOrThat")
clause, which is hard to maintain. This has also more advantages. Just to name one: You could bind this command to KeyBindings
. For example CTRL+O will call the OpenFileCommand.
<Button x:Name="btnBrowseFirmware1"
Grid.Row="2"
Grid.Column="1"
Width="135"
Height="35"
Command="{Binding OpenFileDialogCommand}"
CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"
Content="Browse "
Foreground="White"
/>