找不到绑定命令错误

Binding Command Not found Error

我没有为此使用任何特定的库。我在页面中有一个 Listview,点击它我想调用一个名为 DemoCommand 的命令,但是当我将我的 ViewModel 绑定到页面时,它显示错误命令未找到。我的 Xaml 代码是。

<Grid DataContext="{Binding OrdersObject}">
    <ListView Grid.Row="1" ItemsSource="{Binding data.orders}" SelectionChanged="ListView_SelectionChanged" ItemTemplate="{StaticResource DueOrderTemplate}" ItemContainerStyle="{StaticResource StretchItemStyle}">
        <Interactivity:Interaction.Behaviors>
            <Core:EventTriggerBehavior EventName="SelectionChanged">
                <Core:InvokeCommandAction CommandParameter="{Binding}" Command="{Binding DemoCommand}"/>
            </Core:EventTriggerBehavior>
        </Interactivity:Interaction.Behaviors>
    </ListView>
</Grid>

我的绑定码是

var OrdersObj = new ViewModels.OrdersVM();

            await OrdersObj.GetOrders("cancel");
            this.DataContext = OrdersObj;

我的视图模型代码是

class OrdersVM
{
    public Models.DueOrderM OrdersObject { get; set; }

    async public Task<Boolean> GetOrders(string order_type)
    {
       OrdersObject=//from API
    }
    RelayCommand<Models.OOrderM> _demoCommand;

    public RelayCommand<Models.OOrderM> DemoCommand
    {
        get
        {
            if (_demoCommand == null)
            {
                _demoCommand = new RelayCommand<Models.OOrderM>((itemParam) =>
                {
                    System.Diagnostics.Debug.WriteLine(itemParam);
                });
            }
            return _demoCommand;
        }
        set { _demoCommand = value; }
    }

}

  1. 我会设置 DataContext 而不是 'code behind' 而是 XAML

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    mc:Ignorable="d" 
    DataContext="{Binding ViewModel, Source={StaticResource ViewModelLocator}}"
    d:DataContext="{Binding ViewModel, Source={StaticResource ViewModelLocator}}"
    
  2. 您将 OrdersObject 设置为 DataContext 到网格,所以尝试 RelativeSources 这样您的命令绑定可以 看到 再次查看 ViewModel。

在查看了几个有效的示例 none 之后,我能够自己解决问题 我自己得到了解决方案,据此我只需要更改我的 Xaml 代码。更新后的代码是

<ListView x:Name="lstItem" Grid.Row="1" ItemsSource="{Binding OrdersObject.data.orders}" ItemTemplate="{StaticResource DueOrderTemplate}" ItemContainerStyle="{StaticResource StretchItemStyle}">
        <Interactivity:Interaction.Behaviors>
            <Core:EventTriggerBehavior EventName="SelectionChanged">
                <Core:InvokeCommandAction CommandParameter="{Binding SelectedItem, ElementName=lstItem}" Command="{Binding DemoCommand}"/>
            </Core:EventTriggerBehavior>
        </Interactivity:Interaction.Behaviors>
    </ListView>

我注意到的重要事情是在命令参数中命名 listview 并且需要使用 x:Name 分配它然后它起作用否则它不起作用。希望对我这样的人有帮助。