从另一个类c#wpf访问主窗口公共对象(Observable Collection)

时间:2016-12-09 13:56:10

标签: c# .net wpf

我对这些项herehere

有一个类似的问题

现在编辑问题以包含更多信息

我有一个wpf c#(EDIT解决方案,其中包含3个项目。项目是项目调用CH_CustomerOutlook并引用第二个项目DAL项目,第三个是CustomLibrary结束编辑)CH_CustomerOutlook项目具有正常的主窗口这是一个DataGrid,带有我自己类型的公共可观察集合,名为Outlooks

对于Class CustomerOutlook(编辑是在DAL项目中)我已经设置了INotifyPropertyChanged并且在NotifyPropertyChanged方法的句柄中我想在主窗口中访问此Observable集合Outlook并在类方法中使用它来更新DataGrid上的总计

任何帮助都会非常感谢

代码是

public partial class MainWindow : Window
{
    public static ProjectSettings Settings = new ProjectSettings();
    // define new observable collection for data grid
    public static ObservableCollection<SysproDAL.CustomerOutlook> OutlookCol = new ObservableCollection<SysproDAL.CustomerOutlook>();

    public MainWindow()
    {
        InitializeComponent();
        Settings.SetFromFile(Settings);
    }

~Customer outlook类代码是

public  class CustomerOutlook: INotifyPropertyChanged
{
     //For CustomerOutlook static non changing propetties
   public string Status { get; set; }



    //For Return Merchandise  changing propetties
    private DateTime entrydate;
    public DateTime EntryDate { get { return this.entrydate; }
                    set
                    {
                            if(this.entrydate != value)
                            {
                                    this.entrydate = value;
                                    this.NotifyPropertyChanged("EntryDate");
                            }
                    } } 
//more properties defines etc



    public event PropertyChangedEventHandler PropertyChanged;


    public void NotifyPropertyChanged(string propName)
            {
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
                    this.Status = "u";
                    if (propName == "M1")
                    { 
                        //Want to Access  public observable collection "Outlooks" from main Window
                        //The call method UpdateTotals (Outlooks);
                    }
                }
            }

 public static void UpdateTotals(ObservableCollection<CustomerOutlook> Col)
            { 
                var item = Col.FirstOrDefault(i => i.Status == "T");
                if (item != null)
                {
                    item.M1 = Col.Sum(x => x.M1);
                    item.M2 = Col.Sum(x => x.M2);
                    item.M3 = Col.Sum(x => x.M3);
                }


            }

1 个答案:

答案 0 :(得分:0)

单个CustomerOutlook对象没有对它可能所在的父集合的引用。但是由于您已在MainWindow类中将ObservableCollection字段定义为static,因此您可以直接从CustomerOutlook类访问它,如下所示:

UpdateTotals(MainWindow.OutlookCol);