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

时间:2015-07-01 02:23:33

标签: c# xaml command mvvm-light

我有一个列表框:

<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);
    }

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

1 个答案:

答案 0 :(得分:1)

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

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

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