2010-04-27 31 views
1

XAML {Binding}構造非常方便,因爲它自動處理所有PropertyChanged問題。當您通過.NET數據結構將對象路徑傳遞給對象時,它確實給人印象深刻,並且所有內容都會自動爲您更新。如何在C#中創建類似路徑綁定的XAML

我想在C#中使用相同的東西。我想有一個財產來自另一個財產的價值。示例

class Foo 
{ 
    public Bar Bar = new Bar(); 
    public string ItGetter 
    { 
     get 
     { 
      return Bar.Baz.It; 
     } 
    } 
} 

class Bar 
{ 
    public Baz Baz = new Baz(); 
} 

class Baz 
{ 
    public string It { get { return "You got It!"; } } 
} 

如果您在Foo上調用ItGetter,則會從Baz獲得It值。這很好,除非它沒有失效 - 即,如果它改變了,那麼ItGetter上將沒有改變通知。此外,如果Foo.Bar或Bar.Baz引用被更改,您也不會獲得更改noficiations。

我可以在屬性上添加適當的IChangeNotify代碼,但我的問題是:如何編寫ItGetter屬性,以便在路徑中的任何引用或It值更改時調用其PropertyChanged事件?我希望我不必在路徑中的所有項目上手動設置屬性更改的事件....

感謝您的任何幫助!

埃裏克

回答

1

你可以看看dependancy properties。它們允許您定義WPF屬性系統中由元數據堆棧和詳細值解析系統支持的屬性。

重要的是,他們允許他們允許您註冊屬性更改的事件,並允許您使值取決於其他的東西。

大約有諸如'Demystifying dependency properties' by Josh Smith'Dependency Properties' by Christian Mosers

你也可能需要閱讀Dependency Property Callbacks and Validation

+0

請參閱我的回答(Eric),下面是該解決方案的完整代碼。 – Eric 2010-04-29 16:33:00

1

以下是完整的代碼,做什麼,我一直在尋找,使用依賴屬性,西蒙一些其他的好artcile提到:

// This class exists to encapsulate the INotifyPropertyChanged requirements 
public class ChangeNotifyBase : DependencyObject, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    protected void OnPropertyChanged(string property) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(property)); 
    } 
} 

public class Foo : ChangeNotifyBase 
{ 
    public Foo() 
    { 
     Bar = new Bar(); 
     var binding = new Binding("Bar.Baz.It"); 
     binding.Source = this; 
     binding.Mode = BindingMode.TwoWay; 
     BindingOperations.SetBinding(this, ItGetterProperty, binding); 
    } 

    /// <summary> 
    /// The ItGetter dependency property. 
    /// </summary> 
    public bool ItGetter 
    { 
     get { return (bool)GetValue(ItGetterProperty); } 
     set { SetValue(ItGetterProperty, value); } 
    } 
    public static readonly DependencyProperty ItGetterProperty = 
     DependencyProperty.Register("ItGetter", typeof(bool), typeof(Foo)); 

    // Must do the OnPropertyChanged to notify the dependency machinery of changes. 
    private Bar _bar; 
    public Bar Bar { get { return _bar; } set { _bar = value; OnPropertyChanged("Bar"); } } 
} 

public class Bar : ChangeNotifyBase 
{ 
    public Bar() 
    { 
     Baz = new Baz(); 
    } 
    private Baz _baz; 
    public Baz Baz { get { return _baz; } set { _baz = value; OnPropertyChanged("Baz"); } } 
} 

public class Baz : ChangeNotifyBase 
{ 
    private bool _it; 
    public bool It { get { return _it; } set { _it = value; OnPropertyChanged("It"); } } 
} 

如果你現在就註冊上ItGetter事件,你會得到通知,如果這些事情發生變化: Baz.It Foo.Bar(即更改引用) Bar.Baz「」

如果您將對象引用(Foo.Bar或Bar.Baz)設置爲null,則ItGetter的值更改爲false。

+0

不錯的埃裏克+1。很高興看到有人花時間回來並貢獻自己的成果。這真的是這樣的精神,謝謝。 – 2010-04-29 20:46:39

相關問題