绑定ReportSettings
到之后,SettingsProperty
我希望能够ReportSettings
通过该Settings
属性进行访问。当我尝试这样做时,我得到一个NullReferenceException
. 有谁可以帮我离开这里吗?
ReportSettings
是一个实现的类INotifyPropertyChanged
。
public MyWindow() {
InitializeComponent();
// Load default template
string defaultTemplateName = "default";
foreach (var reportSettings in SettingsCache.Instance.AllReportSettings) {
if (reportSettings.TemplateName.Equals(defaultTemplateName, StringComparison.CurrentCultureIgnoreCase)) {
var binding = new Binding("SettingsProperty") { Source = reportSettings };
SetBinding(SettingsProperty, binding);
var testDirect = reportSettings.IsVisible; // OK
var testDepProp = Settings.IsVisible; // NullReferenceException!!!
//...
}
}
}
public ReportSettings Settings {
get { return (ReportSettings)GetValue(SettingsProperty); }
set { SetValue(SettingsProperty, value); }
}
public static readonly DependencyProperty SettingsProperty = DependencyProperty.Register(
"Settings", typeof(ReportSettings), typeof(MyWindow),
new PropertyMetadata(null, OnSettingsChanged));
更新:在这个例子中我可以只使用局部变量,但这个例子只是为了简单地说明问题。问题确实发生在构造之后,我访问了未初始化的“设置”。