如何将控件的属性值传递给commandparameter;WPF中相同控件的属性

本文关键字:属性 控件 WPF commandparameter 值传 | 更新日期: 2023-09-27 18:13:38

我遵循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"
             />

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...
    }
}

如何将控件的属性值传递给commandparameter;WPF中相同控件的属性

虽然将绑定更改为CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"(如Mr.B所建议的)将解决您的问题,但我建议不要将UI元素名称发送到ViewModel。这将"打破"MVVM模式。为每个打开文件操作创建一个命令。这也将避免长if(browserButtonName= "thisOrThat")条款,这是难以维护。这也有更多的好处。仅举一个例子:您可以将此命令绑定到KeyBindings。例如CTRL+O将调用OpenFileCommand。

如果你想追求卓越,你甚至可以使用一个服务来抽象你的OpenFileDialog WPF OpenFileDialog与MVVM模式?

元素本身不能使用ElementName,而应该使用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"
             />