命令绑定不起作用 - MVVM Light RelayCommand 和 XAML 问题

Command binding not working - MVVM Light RelayCommand and XAML issues

我有一个列表框:

<ListBox Grid.Row="1"
            x:Name="TestCasesList"
            ItemsSource="{Binding TestCases}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Button Command="{Binding Path=DataContext.ButtonClickCommand_DisplayFailureDetails, ElementName=TestCasesList}"
                        CommandParameter="{Binding Failures}">
...

我在我的 DataContext 中添加了一个视图模型:

<Window x:Class="blah.UI.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:design="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
    Name="Window">

我有一个视图模型 RelayCommand:

    ButtonClickCommand_DisplayFailureDetails = new RelayCommand<List<Failure>>( (param) => Execute_ButtonClickCommand_DisplayFailureDetails(param) );


    public RelayCommand<List<Failure>> ButtonClickCommand_DisplayFailureDetails
    {
        get;
        private set;
    }

    private void Execute_ButtonClickCommand_DisplayFailureDetails( List<Failure> failures )
    {
        Failures = new ObservableCollection<Failure>(failures);
    }

按钮没有触发我的命令,有什么原因吗?

尝试更改命令绑定,如下所示:

<Button Command="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=DataContext.ButtonClickCommand_DisplayFailureDetails}" ...> 

通过这种方式,您可以获得 window 的 DataContext 属性,它是用您的 ViewModel 实例设置的。