[英]WPF: binding through custom dependency property
我有一個綁定到Dictionary
的TabControl
,並且有一個自定義控件,因為它是ContentTemplate
。 自定義控件具有自定義依賴項屬性Schedules
並且它的DataContext
綁定到ViewModel
,如下所示:
主控:
<TabControl Grid.Row="1" ItemsSource="{Binding Schedules}">
<TabControl.ContentTemplate>
<DataTemplate>
<TabControl >
<TabItem Header="Scheduled flights">
<views:MyViewer Schedules="{Binding Value}"/>
</TabItem>
</TabControl>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
在MyViewer
,我還有一個DataGrid
,希望它綁定從TabControl
傳遞的Schedules
,但與此同時MyViewer
為其分配了ViewModel
。 這就是MyViewer
中的MyViewer
:
<DataGrid Grid.Row="1" ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=Schedules}" AutoGenerateColumns="False" >
到目前為止,這是行不通的,當加載MyViewer
時, Schedules
屬性為null
。 但是,即使它可行,我也希望將Schedules傳遞給ViewModel
而不是后面的代碼。 一種想法是使用MyViewer
ViewModels
填充Dictionary,但我不希望這樣做,我只希望Main控件了解MyViewer
詳細信息。 那么有什么好主意解決這個問題嗎?
編輯:上面的命題更改為ObservableDictionary
后,確實可以工作,但問題仍然存在,如何在ViewModel
擁有Schedules
如果MyViewer
擁有自己的ViewModel,那么您不應該這樣做:
ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=UserControl}, Path=Schedules}"
通過這種方式, MyViewer
與其他控件緊密結合。
我認為,在這種情況下, MyViewer's ViewModel
應該具有自己的屬性Schedules
。 如何使TabControl ViewModel's Schedules
和MyViewer ViewModel's Schedules
保持同步? 這取決於您的系統,但是您可以嘗試以下方法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.