ReportSettings
을 SettingsProperty
에 바인딩하면 ReportSettings
을 Settings
속성을 통해 액세스 할 수 있습니다. 그렇게하려고하면 NullReferenceException
이 나옵니다. 누구나 나를 도울 수 있습니까?바인딩 후 DependencyProperty가 null 인 이유는 무엇입니까?
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));
업데이트 : 이 예에서는 그냥 로컬 변수를 사용할 수 있지만 예를 들어 그냥 문제의 쉬운 그림입니다. 문제는 실제로 건설 이후에 발생합니다. 여기서 초기화되지 않은 '설정'에 액세스합니다.
좋은 제안이이 문제를 해결했습니다. – mola
코드에서 다른 문제에 대한 해결책을 제시하고 제안했기 때문에 제가 할 수만 있다면 투표 할 수 있었을 것입니다 ... – mola