ICommand not working in datagrid celltemplate

て烟熏妆下的殇ゞ 提交于 2019-12-12 05:37:41

问题


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 _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.


回答1:


please take a look at this post

You need a DataContextProxy to fire Commands inside a DataGridCell. The ElementBinding won't work.



来源:https://stackoverflow.com/questions/5999352/icommand-not-working-in-datagrid-celltemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!