WPF Prism 中Command绑定的简单应用

来源:互联网 发布:sql nvl函数 编辑:程序博客网 时间:2024/05/18 08:17

Command 命令绑定,在WPF窗体绑定点击事件时,如果后台逻辑不在xaml.cs中写,而是自己定义的ViewModel,就需要用Command来响应点击事件,在xaml.cs中写时,可以用click,但是需要往cs中传递对象当前对象时,就需要用Command了,下面介绍一下我自己做的简单Command绑定。不是自己实现的Icommand接口,而是用的prism中的。

1、前台代码

<Button Content="增加" Width="120" Margin="3 1 3 1" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"                       Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}},Path=DataContext.AddPersonCommand}"                                            CommandParameter="{Binding}"/>
注意:如果你的button在一个集合的对象中就像如图所示

增加和删除按钮是在修改的模板,而后台需要当前行对应的对象来进行处理,则必须加上

CommandParameter="{Binding}"
2、后台代码

 ///命令private ICommand addPersonCommand;        public ICommand AddPersonCommand        {            get { return addPersonCommand; }            set            {                addPersonCommand = value;                OnPropertyChanged("AddPersonCommand");            }        }///生成对象  addPersonCommand = new DelegateCommand<object>(OnAddPerson,CanAddPerson);//点击按钮进行的处理方法        private void OnAddPerson(object obj)        {            var per = obj as Person;            if(per!=null)            {                Person p = new Person();                Persons.Add(p);            }                   }//判断该按钮是否可以点击        private bool CanAddPerson(object obj)        {            return selectedPersonInfo==null?false :true ;        }//根据判断条件来更改是否可以点击 private Person selectedPersonInfo;        public Person SelectedPersonInfo        {            get { return selectedPersonInfo; }            set            {                selectedPersonInfo = value;                if(selectedPersonInfo!=null)                {                    DelegateCommand<object> delegateCommand=addPersonCommand as DelegateCommand<object>;                    delegateCommand.RaiseCanExecuteChanged();                }                OnPropertyChanged("SelectedPersonInfo");            }        }

源码下载地址:http://download.csdn.net/detail/u011097924/9327253


0 0