我正在关注MVVM模式。我想将控件的属性值传递给同一控件的“CommandParameter”属性。但是正面临着“对象引用未设置为对象实例”的运行时异常。
WPF:
<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"
/>
视图模型:
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...
}
}
答案 0 :(得分:2)
将绑定更改为CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"
(如Mr.B建议)将解决您的问题,我建议不要将UI元素名称发送到ViewModel。这将“打破”MVVM模式。创建命令foreach Open File Action。这也将避免使用难以维护的长if(browserButtonName= "thisOrThat")
子句。这也有更多的优点。仅举一例:您可以将此命令绑定到KeyBindings
。例如 CTRL + O 将调用OpenFileCommand。
如果你想追求卓越,你甚至可以使用服务来抽象你的OpenFileDialog WPF OpenFileDialog with the MVVM pattern?
答案 1 :(得分:1)
你不能将ElementName用于元素iteself,你应该使用RelativeSource = Self:
<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"
/>