Passing a Date Value from one Windows From to Another Form in C#

前端 未结 4 1105
轮回少年
轮回少年 2021-01-16 16:33

I am working on a very complex project and I am very very new to the windows Project.
I have 2 Forms :

  • ViewSchedule.cs
  • Sch
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-16 17:00

    You should give Scheduler an explicit data source and use events to notify it of changes to the underlying dates. A good idea would be giving the data source its own interface:

    interface IFromToDateProvider : INotifyPropertyChanged
    {
        DateTime From { get; }
        DateTime To { get; }
    }
    

    Then have ViewSchedule implement this interface:

    class ViewSchedule : IFromToDateProvider
    {
        DateTime _from;
    
        public DateTime From
        {
            get { return _from; }
            set
            {
                if (_from == value) return;
    
                _from = value;
                OnPropertyChanged("From");
            }
        }
    
        DateTime _to;
    
        public DateTime To
        {
            get { return _to; }
            set
            {
                if (_to == value) return;
                _to = value;
                OnPropertyChanged("To");
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    Make sure to update the values of from and to using the properties so the event gets fired. Alternately, you can make From and To computed properties that just grab the value from the Calendars you mention; once again, make sure to fire OnPropertyChanged when the underlying calendar values change. If you're using MonthCalendar, you can do this by listening to its DateChanged event.

    Then, have your Scheduler take a IFromToDateProvider as a constructor parameter and listen to its PropertyChanged event:

    class Scheduler
    {
        readonly IFromToDateProvider _provider;
        public Scheduler(IFromToDateProvider provider)
        {
            _provider = provider;
            _provider.PropertyChanged += provider_PropertyChanged;
        }
    
        void provider_PropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
        {
            // update display with new values in _provider.From and/or 
            // _provider.To in this event handler
        }
    }
    

    This is assuming that ViewSchedule creates a Scheduler instance. If it's vice versa, just have Scheduler listen to the event after it creates the ViewSchedule. If neither, just set it as a property; the essential part is that you end up with Scheduler listening to the PropertyChanged event of a ViewSchedule.

提交回复
热议问题