如何将ListView DataTemplate中的按钮绑定到ViewModel中的命令? (MVVMLight)

时间:2015-01-29 20:11:12

标签: c# windows-phone-8 mvvm binding mvvm-light

我有一个包含以下代码的列表视图:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox x:Name="allToDoItemsListBox" 
             ItemsSource="{Binding AllToDoItems,Mode=OneWay}" 
             Margin="12,0,12,0" 
             Width="440" 
             ItemTemplate="{StaticResource ToDoListBoxItemTemplate}" />
</Grid>

datatemplate如下:

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="ToDoListBoxItemTemplate">

        <Grid HorizontalAlignment="Stretch" Width="420">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="100" />
            </Grid.ColumnDefinitions>

            <CheckBox 
                IsChecked="{Binding IsComplete, Mode=TwoWay}" 
                Grid.Column="0" VerticalAlignment="Top"/>

            <TextBlock 
                Text="{Binding ItemName}" 
                FontSize="{StaticResource PhoneFontSizeLarge}" 
                Foreground="Gray"
                Grid.Column="1" Grid.ColumnSpan="2" 
                VerticalAlignment="Top" Margin="-36, 12, 0, 0"/>

            <Button                                
                Grid.Column="3"
                x:Name="deleteTaskButton"
                BorderThickness="0"                                                                  
                Margin="0, -18, 0, 0"
                Command="{Binding Path=DeleteCommand}" CommandParameter="{Binding}"/>

            <Image 
                Source="/Images/appbar.delete.rest.png"
                Height="75"
                Width="75"/>
        </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

我试图绑定Button Command&#34; DeleteCommand&#34;到ViewModel中的ICommand但它失败了我该怎么办?

ViewModel中的代码是:

 public ICommand DeleteCommand { get; private set; }

在ViewModel构造中:

 DeleteCommand = new RelayCommand<object>(Delete);

删除方法:

private void Delete(object obj)
{
    ToDoItem newToDoItem = obj as ToDoItem;
    DeleteToDoItem(newToDoItem);
}

我需要将项目传递给DeleteToDoItem()方法作为参数,当按下列表中每个项目的相应删除按钮但命令不在此处触发我该怎么办?

1 个答案:

答案 0 :(得分:2)

在ViewModel中,您希望将ToDoItem传递给删除命令。

DeleteCommand = new RelayCommand<ToDoItem>(DeleteToDoItem);

您的DataTemplate的DataContext与ListView不同。

<Button Command="{Binding ElementName=allToDoItemsListBox, 
                          Path=DataContext.DeleteCommand}" 
        CommandParameter="{Binding}" />

应该这样做。