我有一个包含以下代码的 ListView :
<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>
数据模板如下:
<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>
我尝试将按钮命令“DeleteCommand”绑定(bind)到 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()方法,但命令不在这里触发,我该怎么办?
最佳答案
在 ViewModel 中,您希望将 ToDoItem
传递给删除命令。
DeleteCommand = new RelayCommand<ToDoItem>(DeleteToDoItem);
并且您的 DataTemplate 的 DataContext 与 ListView 的不同。
<Button Command="{Binding ElementName=allToDoItemsListBox,
Path=DataContext.DeleteCommand}"
CommandParameter="{Binding}" />
应该可以了。
关于c# - 如何将 ListView DataTemplate 中的按钮绑定(bind)到 ViewModel 中的命令? (MVVMLight),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28223693/