前台代码
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding StudentDatas}" Margin="0,100,0,0">
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Width="100" Binding="{Binding Name}"/>
<DataGridTextColumn Header="年龄" Width="100" Binding="{Binding Age}"/>
<DataGridTemplateColumn Header="操作" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<!--
这种写法错误,无法找到对应的命令,此处的CheckCommand是对应的当前DataContext中找,而当前的DataContext是StudentData
<Button Content="查看" Command="{Binding CheckCommand}" CommandParameter="aa"/>
-->
<!--正确写法,指定RelativeSource相对数据源,DataGrid的DataContext是DataGridWindowViewModel -->
<Button Content="查看" Width="80" Height="30"
Command="{Binding DataContext.CheckCommand,RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" CommandParameter="aa"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
后台代码
/// <summary>
/// DataGridWindow.xaml 的交互逻辑
/// </summary>
public partial class DataGridWindow : Window
{
private DataGridWindowViewModel _viewModel = null;
public DataGridWindow()
{
InitializeComponent();
_viewModel = new DataGridWindowViewModel();
this.DataContext = _viewModel;
}
}
ViewModel:
namespace BindingWpfApp.Views
{
public class DataGridWindowViewModel
{
public ObservableCollection<StudentData> StudentDatas { get; set; }
public DelegateCommand CheckCommand { get; set; }
public DataGridWindowViewModel()
{
StudentDatas = new ObservableCollection<StudentData>();
StudentDatas.Add(new StudentData { Name = "小明", Age = 18 }); ;
StudentDatas.Add(new StudentData { Name = "小红", Age = 17 });
CheckCommand = new DelegateCommand();
CheckCommand.ExecuteAction = new Action<object>(OnCheck); ;
}
private void OnCheck(object value)
{
Console.WriteLine("--");
}
}
}
Model:
namespace BindingWpfApp.Models
{
public class StudentData : NotifycationObject
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
this.RaisePropertyChanged("Name");
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
this.RaisePropertyChanged("Age");
}
}
}
}