MVVMCross Behaviors和InvokeCommandAction

时间:2014-06-04 08:39:21

标签: mvvm windows-runtime mvvmcross portable-class-library

我对MVVMCross和MVVM架构比较陌生。

我正在努力让我的CodeBehind尽可能干净,所以我在点击一个项目时一直使用Interactivity:Interaction.Behaviors来触发命令:

<views:MvxStorePage.Resources>
        <core:Theme x:Key="Theme"/>
        <b:NameScopeBinding  x:Key="ModuleGridView" Source="{Binding ElementName=ModuleGridView}" />
</views:MvxStorePage.Resources>
...
<GridView x:Name="ModuleGridView" >
...
<Interactivity:Interaction.Behaviors>
     <Core:EventTriggerBehavior EventName="SelectionChanged">
          <Core:InvokeCommandAction Command="{Binding SelectModuleCommand}" CommandParameter="{Binding Source.SelectedItem, Source={StaticResource ModuleGridView}}" />
     </Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
...
</GridView>

在我的ViewModel中:

MvxCommand<object> _selectModuleCommand;
        public ICommand SelectModuleCommand
        {
            get
            {
                _selectModuleCommand = _selectModuleCommand ?? new MvxCommand<object>((obj) => SelectModule(obj));
                return _selectModuleCommand;
            }
        }

        private void SelectModule(object module)
        {
            var test = 1;
        }

问题是传递给SelectModule的对象是ItemClickedEventArgs类型,这在我的ViewModel所在的PCL核心项目中是不可用的。所以我无法访问该对象的ItemClicked属性。

我尝试过使用'InvokeCommandAction'

 <Core:InvokeCommandAction Command="{Binding SelectModuleCommand}" CommandParameter="{Binding Source.SelectedItem.ClickedItem, Source={StaticResource ModuleGridView}}" />

但它没有效果,我仍然将ItemClickedEventArgs作为我的命令的参数

1 个答案:

答案 0 :(得分:5)

使用InvokeCommandAction的InputConverter属性解决

<interactivity:Interaction.Behaviors>
                            <icore:EventTriggerBehavior EventName="ItemClick">
                                <icore:InvokeCommandAction Command="{Binding SelectModuleCommand}" InputConverter="{StaticResource ItemClickedConverter}" />
                            </icore:EventTriggerBehavior>
                        </interactivity:Interaction.Behaviors>

ItemClickedConverter:

public class ItemClickedConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var args = value as ItemClickEventArgs;

            if (args != null)
                return args.ClickedItem;

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            string language)
        {
            throw new NotImplementedException();
        }
    }