This is my MainPage.xaml :-
<sdk:DataGrid Margin="17,17,20,76" AutoGenerateColumns="False" ItemsSource="{Binding Students}">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding StudName}" Header="Student Name">
</sdk:DataGridTextColumn>
<sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button CommandParameter="{Binding}" Command="{Binding Path=DataContext.AddCommand,ElementName=root}"
Content="Add Student" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
In code behind I have set the datacontext to viewmodel instance.
This is my viewmodel :-
using SampleApp.Misc;
using SampleApp.Model;
using SampleApp.Web;
using System.Collections.ObjectModel;
using SampleApp.Commands;
namespace SampleApp.VM
{
public class MainPageViewModel : ViewModelBase
{
private StudentModel _model = new StudentModel();
public MainPageViewModel()
{
_model.GetStudentAsyncComplete += _model_GetStudentAsyncComplete;
_model.GetStudentAsync();
}
private RelayCommand<Student> _addCommand = null;
public RelayCommand<Student> AddCommand
{
get
{
if (_addCommand == null)
{
_addCommand = new RelayCommand<Student>(student =>
{
}, student => student != null);
}
return _addCommand;
}
}
private ObservableCollection<Student> _students;
public ObservableCollection<Student> Students
{
get { return开发者_C百科 _students; }
set
{
_students = value;
RaisePropertyChanged("Students");
}
}
void _model_GetStudentAsyncComplete(object sender, EntityResultArgs<Web.Student> e)
{
if (e.Error == null)
{
Students = new ObservableCollection<Student>(e.Results);
}
}
}
}
Why isn't my command of AddStudent firing in ViewModel? Any idea? If I place it outside Datagrid it works absolutely fine.
please take a look at this post
You need a DataContextProxy to fire Commands inside a DataGridCell. The ElementBinding won't work.
精彩评论