我有一個小問題,但已經找到了不少,不同而且大多含糊不清,答案:如何在不使用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。
謝謝!我會馬上嘗試。當我以編程方式更新集合時,是否也必須添加該行代碼? – bleepzter 2011-05-23 20:15:49
否 - 您的PropertyChanged事件將處理該問題 – ColinE 2011-05-23 20:17:04
您不應該,不。另外,如果您只是從集合中添加/刪除項目,則無需實施INotifyPropertyChanged。 observableCollection已經負責通知添加/刪除/清除。 – 2011-05-23 20:18:46