【问题标题】:How to pass property value of a control to "CommandParameter" property of same control in WPF如何将控件的属性值传递给 WPF 中同一控件的“CommandParameter”属性
【发布时间】:2017-02-28 21:55:21
【问题描述】:

我遵循 MVVM 模式。我想将控件的属性值传递给同一控件的“CommandParameter”属性。但是遇到了“Object reference not set to an instance of object”的运行时异常。

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

【问题讨论】:

  • 更改为 CommandParameter="{Binding Name ,RelativeSource={RelativeSource Self}}"
  • 我运行了你的代码,它运行正常,这个异常到底发生在哪里?
  • 我相信异常发生在 .NET 框架层。使用 snop 或查看 Visual Studio 绑定错误来理解它。如果您不介意,请将我的答案标记为您问题的正确答案。
  • @Rom:调试器没有在断点处中断,而是因运行时异常而崩溃。

标签: c# wpf mvvm data-binding


【解决方案1】:

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

如果你想追求卓越,你甚至可以使用服务来抽象你的 OpenFileDialog WPF OpenFileDialog with the MVVM pattern?

【讨论】:

  • 完整答案的完美解释。
【解决方案2】:

您不能将 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"
             />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2010-11-26
    • 2013-01-14
    相关资源
    最近更新 更多