ICommand在数据网格单元格模板中不起作用 [英] ICommand not working in datagrid celltemplate

查看:13
本文介绍了ICommand在数据网格单元格模板中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的主页面.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>

在后面的代码中,我已将datacontext设置为viewModel实例。

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);
            }
        }
    }
}

为什么我不能在ViewModel中命令添加学生触发?有什么主意吗?如果我把它放在数据网格之外,它绝对可以正常工作。

推荐答案

请查看this post

您需要DataConextProxy来在DataGridCell内激发命令。ElementBinding不起作用。

这篇关于ICommand在数据网格单元格模板中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆