繁体   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