绑定到interface属性,绑定时表示null

时间:2011-04-26 09:42:12

标签: c# .net wpf binding null

我必须将GUI绑定到界面:

public interface IMain
{
  public CTopObject MyObject { get; }
  public CInsideObject MidObj { get; }
  public CInsideObject MyCollectionObject { get; }
}

Objects definitions:

public class CMain
{
  public CTopObject MyObject { get { return this.myObject; }
  public CInsideObject MidObj { get { return this.MyObject.SomeObject; } }
  public CInsideObject MyCollectionObject 
  { get 
    { 
      if(this.MyObject.Thedict.Contains(0))
        return this.MyObject.TheDict[0]; 
      else
        return default(CInsideObject);

    } 
  } //0 is ofcourse an example
}

public class CTopObject
{
  private string someString;
  public string SomeString
  {
    get { return this.someString; }
    set
    {
      this.someString = value;
      if(this.PropertyChanged!=null) this.PropertyChanged(this, "SomeString");
    }  
  } 
  private ObservableDictionary int, CInsideObject> theDict; //how to open bracket on stackoverflow? ;)
  public ObservableDictionary int, CInsideObject> TheDict
  {
    get { return this.theDict; }
  }
  private CInsideObject someObject;
  public CInsideObject SomeObject
  {
    get { return this.someObject; }
  }

  //There is constructor. After that, there is init method,
  //that creates new thread. The thread updates SomeString,
  //representing object state. After thread raise specified event 
  //callback method begin to initialize SomeObject and 
  //after callback from SomeObject it adds some objects to 
  //TheDict, and initialize them.
}

public class CInsideObject : INotifyPropertyChanged
{
  private string someString;
  public string SomeString
  {
    get { return this.someString; }
    set
    {
      this.someString = value;
      if(this.PropertyChanged!=null) this.PropertyChanged(this, "SomeString");
    }  
  }    

   //There is constructor, and init method that creates new thread. 
   //This thread updates SomeString that represents actual state of object.
}

现在在我的应用程序main.xaml.cs文件中,我有字段

private IMain theMain;
然后我将窗口的DataContext设置为IMain字段:

theMain = new CMain(... some args ...);
this.DataContext = this.theMain;
...initialize theMain...

在XAML中看起来像这样:

Label Content="{Binding Path=MyObject.SomeString}" Name="label1"/>
Label Content="{Binding Path=MyMidObj.SomeString}" Name="label2"/>
Label Content="{Binding Path=MyCollectionObject.SomeString}" Name="label3"/>
像我写的那样初始化主要是在主应用程序线程之外的其他线程中。但是,在每个“状态对象”中都有SomeString属性,它调用NotifyPropertyChanged事件。每当线程更改对象状态时,SomeString都会更新。 Window GUI有一些标签代表适当对象的SomeString。

我不知道为什么当TopObject的SomeString发生变化时,只有MyObject of IMain接口才更新绑定标签。 MidObj和MyCollectionObject的标签以某种方式为空。

对不起我的英语,我希望我的问题不是混淆;)
由于

1 个答案:

答案 0 :(得分:0)

如果将绑定设置为:

会发生什么
Label Content="{Binding Path=MyObject.SomeObject.SomeString}" Name="label2"/>
Label Content="{Binding Path=MyObject.TheDict}" Name="label3"/>