[英]Binding attached property to IEnumerable
我在C#中使用新的WPF Viewer for Crystal Reports。 當我使用MVVM時,我真的很想綁定要顯示的數據源,而不是在加載的事件中這樣做。 因此,我想為源實現一個附加屬性-但是綁定不起作用,甚至沒有調用Getter方法。 關於綁定附加屬性的其他帖子也無濟於事,我不確定自己在做什么不同。 有人可以幫忙嗎? 這是附加屬性的簡化代碼:
public static class CrystalReportsAttached {
public static readonly DependencyProperty SourceProperty =
DependencyProperty.RegisterAttached(
"Source",
typeof(IEnumerable),
typeof(CrystalReportsAttached),
new UIPropertyMetadata(new ObservableList<Participant>() as IEnumerable, SourceChanged));
public static void SetSource(DependencyObject target, IEnumerable value) {
target.SetValue(SourceProperty, value);
}
public static IEnumerable GetSource(DependencyObject target) {
return (IEnumerable)target.GetValue(SourceProperty);
}
private static void SourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
CrystalReportsViewer reportViewer = d as CrystalReportsViewer;
if (reportViewer != null) {
MyCrystalReport report = new MyCrystalReport();
report.SetDataSource(d.GetValue(SourceProperty) as IEnumerable);
reportViewer.ViewerCore.ReportSource = report;
}
}
}
其中MyCrystalReport
是rpt報告文件的包裝器。
如果我現在這樣綁定到源,它將無法正常工作:
<my:CrystalReportsViewer prop:CrystalReportsAttached.Source="{Binding MyList, Mode=OneWay}"/>
我試圖以相同的方式綁定DataGrid
的ItemsSource
,並且可以正常工作,因此路徑名或類似名稱似乎沒有錯誤。
任何幫助是極大的贊賞。 非常感謝!
使用依賴項屬性,您可以確定的是,當屬性更改時,將調用屬性更改的回調,而如果調用getter,則實際上將更改基礎屬性。 這可能看起來很奇怪,但是您的getter和setter只是訪問該基礎屬性,因此,如果XAML解析器調用target.GetValue(SourceProperty)
它將獲得正確的信息而無需調用您的getter。
真正的問題是您的屬性更改后的回調函數會被調用嗎?
要接收對集合的更改,源集合必須實現INotifyCollectionChanged。
您可以使用ObservableCollection,在線查找自定義的通知集合,或使用您編寫的實現內部集合和INotifyCollectionChanged接口的類包裝現有集合。
如果初始綁定失敗,請檢查是否已將DataContext(設置為View-Model),VM上的屬性名稱正確以及該屬性具有公共getter。
編輯:
這部分是錯的:
new UIPropertyMetadata(new ObservableList<Participant>() as IEnumerable, SourceChanged));
您正在將相同的列表實例設置為所有控件的默認值。 而是在構造函數中設置默認值(在DP注冊表行中輸入null)。
我終於找出問題所在:
似乎由於某些原因, CrystalReportViewer
的DataContext被覆蓋。 因此,綁定在所有其他上下文(例如,在DataGrid
)中都有效,但在這里不起作用。 我通過使用上面default.kramer提到的監聽工具發現了問題。 我可以通過將綁定更改為
<my:CrystalReportsViewer prop:CrystalReportsAttached.Source="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.Participants, Mode=OneWay}"/>
因此它確實可以訪問UserControl
的DataContext
(通常應與特定控件的DataContext
相同,但不適用於CrystalReportsViewer
),並且它現在可以正常工作。
感謝大家的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.