WPF MVVM - Command binding inside of an ItemsControl

前端 未结 3 483
抹茶落季
抹茶落季 2021-02-03 12:00

I\'m currently converting a small WPF project to MVVM. I have a List in the ViewModel of the main window that my ItemsControl binds to and uses

3条回答
  •  情话喂你
    2021-02-03 13:04

    You can try to keep your Command in your Model.

    public class MyModel
    {
        public MyModel()
        {
            MyCommand = new DelegateCommand(MyCommandExecute);
        }
    
        public ICommand MyCommandCommand { get; set; }
    
        private void MyCommandExecute()
        {
        }
    }
    

    And then, you must have an ObservableList for the list of your Items in your ViewModel as,

    public class MyViewModel
    {
        public MyViewModel()
        {
            MyStarterCommand = new DelegateCommand(MyCommandExecute);
    
            if (!IsDesignTime)//(bool)DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof(DependencyObject)).Metadata.DefaultValue;
                MyCommand.Execute(null);
        }
    
        private ObservableCollection list;
        private  ICommand MyStarterCommand { get; set; }
    
        public ObservableCollection List
        {
            get { return list; }
            set
            {
                list = value;
                RaisePropertyChanged(() => List);
            }
        }
    
        private void MyStarterCommandExecute()
        {
            List = new ObservableCollection();
    
            //Fill the list here
            List.Add(new MyModel());
        }
    }
    

    Then in XAML you must say;

    
        
            
                

提交回复
热议问题