在DataGrid中实现Button Command绑定
Command="{Binding editCommand}" 会默认查找UserList中对象的属性,而你的UserList中对象应该不包括editCommand属性;
可以尝试:
Command="{Binding DataContext.editCommand,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Windows}}}"
<DataGrid ItemsSource="{Binding UserList}" Name="PregnantDataGrid" IsReadOnly="True" AutoGenerateColumns="False" HeadersVisibility="All" > <DataGrid.Columns> <DataGridTextColumn Width="150" Header="姓名" Binding="{Binding realName}" /> <DataGridTextColumn Width="100" Header="手机号" Binding="{Binding phoneNo}" /> <DataGridTemplateColumn Width="60" CanUserResize="False" Header="操作"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <DockPanel HorizontalAlignment="Left" Margin="5,0,0,0"> <Button Content="编辑" Margin="5" Width="80" Command="{Binding DataContext.editCommand,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding}" /> </DockPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>
public class VmUser : ViewModelBase { public VmUser() { EditCommand = new RelayCommand(EditCommandMethod, CanEditExecute); } public RelayCommand EditCommandMethod { get; set; } private void EditCommandMethod(object param) { var obj = param as UserInfo; MessageBox.Alert(obj.UserName); } private bool CanEditExecute(object obj) { return true; } }