wpf - 获取 WPF 资源中 DataContext 更改的通知

标签 wpf binding collectionviewsource

我在 WPF 绑定(bind)方面遇到了一个恼人的问题。基本上,我在 UserControl 的资源中声明了一个 FrameworkElement,但是当父 UserControl 的 DataContext 更改时,该项目似乎没有收到通知。

基本上,在我的 UserControl 中,我在 ItemsControl 的 ItemTemplate 中有一个弹出窗口。在该 Popup 中,我需要绑定(bind)到父 View 的 ViewModel 中的某些内容,因此我想出了一个我认为很聪明的技巧。根据 CollectionViewSource 的提示,我想我只需将父级的 View 模型绑定(bind)到资源,然后使用该资源从 DataTemplate 访问 ViewModel,如下所示:

    <UserControl.Resources>
        <cont:ViewModelSource Source="{Binding}" x:Key="ParentViewModel"/>
    </UserControl.Resources>

这样以后我就可以像这样使用它:

CommandParameter="{Binding ViewModel.OpenEntity, Source={StaticResource ParentViewModel}}"

这一切似乎都有效,除了,当 UserControl 的 DataContext 重置时,ViewModelSource 上的 DataContext 不会重置。现在,我正在简单地完成这项工作:在 UserControl 的 DataContextChanged 事件的代码隐藏中设置资源的 DataContext。

我在 Reflector 中查看了 CollectionViewSource 是如何做到这一点的,但它似乎没有做任何特别的事情。

有人知道为什么会发生这种情况或者我该如何解决它?

最佳答案

我遇到了同样的问题,并找到了解决方案。

首先,我尝试将 ViewModel 设置为根元素的 DataContext。错了。

然后我尝试将 ViewModel 设置为资源并将根元素的绑定(bind)源设置为资源。错了。

最后,我创建了一个 IValueConverter 将模型(即控件的 DataContext)转换为 ViewModel。然后我将根元素的 DataContext 与转换器绑定(bind)。

<UserControl.Resources>

    <local:PersonToControllerConverter x:Key="PersonToControllerConverter"/>

    <!--<local:PersonController x:Key="controller"
        Value="{Binding}"
        Parent="{Binding Path=DataContext,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"
        />-->

</UserControl.Resources>



<Border x:Name="root" BorderBrush="Black" BorderThickness="2" >
    <Border.DataContext>
        <MultiBinding Converter="{StaticResource PersonToControllerConverter}">
            <Binding/>
            <Binding Path="DataContext" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}"/>
        </MultiBinding>
    </Border.DataContext>

    <!--DataContext="{Binding Source={StaticResource controller}}">-->

    <!--<Border.DataContext>
        <local:PersonController
                    Value="{Binding}"
                    Parent="{Binding Path=DataContext,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"
                    />
    </Border.DataContext>-->

我认为,当 DataContext 破坏元素中的绑定(bind)时,当根元素上的 datacontext 发生更改时,它会停止在破坏的绑定(bind)上。

关于wpf - 获取 WPF 资源中 DataContext 更改的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2813500/

相关文章:

wpf - 我可以使用箭头键而不是 Tab 导航进出 wpf 组合框吗?

WPF 与 StringFormat 绑定(bind)

c# - 如何在 WPF 中动态更改 DataGridTextColumn 绑定(bind)上的转换器?

c# - 将 ObservableCollection 过滤到多个列表框

c# - 如何将文本 block 与属性绑定(bind)

c# - 将 itemscontrol 绑定(bind)到列表,这是父数据上下文中的一个属性

c# - 更改集合时触发方法

wpf - 为什么 Label 和 TextBox 的绑定(bind)结果不同?

linq - x :Bind type can't be found

c# - Windows phone 8.1 滤镜合集查看源码