【问题标题】:MVVM EventToCommand Parameter is NULLMVVM EventToCommand 参数为 NULL
【发布时间】:2013-03-25 11:22:10
【问题描述】:

我在 Windows Phone 7.1 中使用 MVVM Light Toolkit

ViewModel 的一部分:

public RelayCommand<object> ChangeVATCommand
        {
            get
            {
                return _changeVATCommand
                    ?? (_changeVATCommand = new RelayCommand<object>(
                                          (vat) =>
                                          {

                                          }));
            }
        }

Xaml 的一部分:

    <toolkit:ListPicker  ItemsSource="{Binding VATs}" x:Name="VATs" SelectedIndex="0"  DisplayMemberPath="Name">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <cmd:EventToCommand Command="{Binding ChangeVATCommand, Mode=OneWay}"
                                    CommandParameter="{Binding Path=SelectedItem, ElementName=VATs}"
                />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </toolkit:ListPicker>

当命令运行时,传递给 lambda 的 vat 为空。如果我在 xaml CommandParameter 中将“{Binding ElementName=VATs}”设置为“{Binding ElementName=VATs}”,则 lambda 中的增值税具有具有正确属性 SelectedItem 对象(非空)的 ListPicker。

这是一个错误还是我做错了什么?

更新

总结:

  1. CommandParameter="{Binding Path=SelectedItem, ElementName=VATs}" - 我有 NULL

  2. CommandParameter="{Binding Path=SelectedIndex, ElementName=VATs}" - 工作正常!我有所选大桶的索引

  3. CommandParameter="{Binding ,ElementName=VATs}" - 工作正常!我有 ListPicker 和正确的选定项

【问题讨论】:

  • 谢谢。我为第二个选项工作 -CommandParameter="{Binding Path=SelectedIndex, ElementName=VATs}"

标签: windows-phone-7 mvvm mvvm-light


【解决方案1】:

我宁愿建议将 ListPicker 的 SelectedItem 以两种方式绑定到 VM 上的属性。然后从命令中,您可以轻松访问此属性。

如果您选择此解决方案,您可能甚至不需要命令,您可以直接从 VM 中的 SelectedItem 属性中触发计算。

干杯 洛朗

【讨论】:

  • 当然这是实现我目标的更好方法。更少的代码更少的错误!
【解决方案2】:

不久前我遇到了类似的问题,解决方案是指示相应的VM:

<toolkit:ListPicker  ItemsSource="{Binding VATs}" x:Name="VATs" SelectedIndex="0"  DisplayMemberPath="Name">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand Command="{Binding Path=ViewModelName.ChangeVATCommand, Source={StaticResource Locator}, Mode=OneWay}"
                                CommandParameter="{Binding Path=SelectedItem, ElementName=VATs}"
            />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</toolkit:ListPicker>

请注意,现在绑定引用 ViewModel 并使用 Locator 作为源。

【讨论】:

  • 我做了您的更改,但增值税仍为 NULL。这很奇怪,因为例如 SelectedIndex (CommandParameter="{Binding Path=SelectedIndex, ElementName=VATs}") 属性已正确传递给命令
  • 如果你想收到选中的物品可以试试CommandParameter="{Binding}"
  • CommandParameter="{Binding}" 传递整个视图模型,因为这是触发器/元素的数据上下文。我还是检查了这个......
猜你喜欢
  • 2014-10-06
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2015-09-26
  • 2013-02-25
  • 1970-01-01
相关资源
最近更新 更多