【问题标题】:WPF: binding through custom dependency propertyWPF:通过自定义依赖属性绑定
【发布时间】:2019-03-14 09:57:04
【问题描述】:

我有一个TabControl 绑定到一个Dictionary 并且有一个自定义控件,因为它是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中的样子:

<DataGrid Grid.Row="1" ItemsSource="{Binding RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType=UserControl}, Path=Schedules}" AutoGenerateColumns="False" >

到目前为止,这不起作用,当 MyViewer 加载时 Schedules 属性是 null。但即使它有效,我也希望将时间表传递给 ViewModel 而不是后面的代码。一个想法是用MyViewerViewModels 填充字典,但我不想这样做,我只希望主控件知道MyViewer 的详细信息。那么有什么好主意可以解决这个问题吗?

编辑: 上面的命题在更改为ObservableDictionary 后确实有效,但问题仍然存在,如何在ViewModel 中拥有Schedules

【问题讨论】:

  • 你可以使用 tag 属性。将 Schedules 绑定到 Tag(您可能需要一个转换器)并将 TabControl.Tag 属性设置/绑定到您希望 Schedules 成为的值。否则,您将需要创建一个具有 schedules 属性和 tabcontrol 逻辑的自定义控件
  • 所以DataGrid 没有绑定到MyViewerSchedules 属性?您确定该属性已设置,即绑定到 Value 确实有效吗?
  • @mm8,它确实在对字典进行了一些修改后绑定,但我仍然希望在ViewModel 中有时间表,你有什么建议?
  • @Ayoub.A:将DataGrid直接绑定到Value?
  • @mm8,这就是我想要的,将 Value 传递给 MyViewer 的 ViewModel。你是怎么做到的?

标签: c# wpf mvvm binding


【解决方案1】:

如果MyViewer 有它自己的 ViewModel,你不应该做这样的 hack:

   ItemsSource="{Binding RelativeSource={RelativeSource  Mode=FindAncestor, 
   AncestorType=UserControl}, Path=Schedules}"

这样MyViewer 与其他一些控件紧密耦合。

我认为,在这种情况下,MyViewer's ViewModel 应该拥有自己的属性Schedules。您如何使TabControl ViewModel's SchedulesMyViewer ViewModel's Schedules 保持同步?这取决于您的系统,但您可以尝试以下想法:

  • 在添加或删除项目时发送 ViewModel 级别的消息,例如在 MVVM Light 中。 Example in this blog post
  • 尝试在 NgXs 或 Angular 中的 NgRx 中实现某种存储
  • 也许您不需要保持计划同步 - 取决于您的系统? :)

【讨论】:

  • MyViewer 是具有 Schedules 的 UserControl。
  • 我已经更新了我的答案,我之前跳过了一个词:MyViewer 的 ViewModel 应该有它自己的属性
猜你喜欢
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多