2011-05-23 17 views
3

我有一個小問題,但已經找到了不少,不同而且大多含糊不清,答案:如何在不使用DataContext的情況下綁定到Silverlight中的本地屬性?

我有以下用戶控件,我試圖綁定到該控件(事件)內的公共屬性。每個人都說我必須使用數據上下文,但是,我並不想這麼做......我只想綁定到控件的 XAML內的屬性...

要求是綁定必須是2種方式,所以ui中的任何更改都會反映在綁定的屬性(或集合)中。該集合中的每個Event對象也以與此控件相同的方式實現INotifyPropertyChanged ...

任何想法都將不勝感激!

public partial class EventEditorWindow : UserControl, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    public ObservableCollection<Event> events; 
    public ObservableCollection<Event> Events 
    { 
     get { return this.events; } 
     set 
     { 
      if(this.events != value) 
      { 
       this.events = value; 
       this.RaisePropertyChanged("Events"); 
      } 
     } 
    } 

    private void RaisePropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      this.VerifyPropertyName(propertyName); 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

    [Conditional("DEBUG")] 
    [DebuggerStepThrough] 
    public void VerifyPropertyName(string propertyName) 
    { 
     var currentObjectType = this.GetType(); 

     if (currentObjectType.GetProperty(propertyName) == null) 
     { 
      throw new ArgumentException("Property not found", propertyName); 
     } 
    } 
} 

謝謝, Bleepzter。

回答

1

在構造函數中,設置DataContext = this。這將有效地使你的代碼在你的DataContext後面。 AFAIK,你不能完全避免東西的DataContext。

+0

謝謝!我會馬上嘗試。當我以編程方式更新集合時,是否也必須添加該行代碼? – bleepzter 2011-05-23 20:15:49

+1

否 - 您的PropertyChanged事件將處理該問題 – ColinE 2011-05-23 20:17:04

+1

您不應該,不。另外,如果您只是從集合中添加/刪除項目,則無需實施INotifyPropertyChanged。 observableCollection已經負責通知添加/刪除/清除。 – 2011-05-23 20:18:46

1

你可以使用的RelativeSource,所以你不需要的DataContext:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type EventEditorWindow }}, Path=Events} 

我用this cheat sheet不時。

編輯糟糕,這是WPF語法。看到這個職位看看this post to solve it in Silverlight

+0

謝謝你的這張備忘單。當我試圖實現AncestorType = {x:type ...}時,我得到了錯誤的類「相對資源沒有實現AncestorType」...但我發現綁定備忘單非常有用! – bleepzter 2011-05-24 02:25:37

相關問題