Q:如何将style中的控件的属性传递给函数(MVVMLight)?

50 篇文章 2 订阅

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"
             />

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值