簡體   English   中英

WPF:通過自定義依賴項屬性進行綁定

[英]WPF: binding through custom dependency property

我有一個綁定到DictionaryTabControl ,並且有一個自定義控件,因為它是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 SchedulesMyViewer ViewModel's Schedules保持同步? 這取決於您的系統,但是您可以嘗試以下方法:

  • 添加或刪除項目時,發送MVVM Light中的ViewModel級消息。 此博客文章中的示例
  • 嘗試實現某種存儲,例如在Angular中的NgXs或NgRx中
  • 也許您不需要保持時間表同步-取決於您的系統? :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM