如何将"绑定"值传递给依赖项属性

MyD*_*ons 5 wpf dependency-properties mvvm

我的应用程序有一个MainWindow.在此范围内,有1个控件,a ListBox,绑定到MainWindowViewModel的属性.此属性是UserControl,类型为CriteriaVm

CriteriaVm有一个名为MyString的字符串属性

在标准视图中,我有以下代码

<UserControl x:Class="CompoundInterests.View.CriteriaView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:vm="clr-namespace:CompoundInterests.ViewModel"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="600">

    <UserControl.Resources>
        <ResourceDictionary Source="../Dictionary.xaml" />
    </UserControl.Resources>
    <Grid>
        <Border>
            <Expander Header="{Binding MyString}" >
                <vm:PropertiesVm ThresholdName="{Binding MyString}" />
            </Expander>
        </Border>
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

如您所见,我在两个地方绑定了MyString.扩展器中的绑定工作正常,vm中的绑定:PropertiesVm没有(使用Dependency Properites)."输出"窗口中显示以下错误

System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement.BindingExpression:路径= MyString中; 的DataItem = NULL; target元素是'PropertiesVm'(HashCode = 5991653); target属性是'ThresholdName'(类型'String')

确定错误消息告诉我它正在ProperitesVm中寻找MyString ...我应该在CriteriaVm中寻找MyString.这意味着我需要使用RelativeSource,我认为它是1级和UserControl类型.所以我更新到:

<vm:PropertiesVm ThresholdName="{Binding Path=MyString, RelativeSource={RelativeSource AncestorLevel=1,AncestorType=UserControl,Mode=FindAncestor}}" />
Run Code Online (Sandbox Code Playgroud)

我得到一个稍微不同的问题,但似乎存在相同的潜在错误

System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.UserControl',AncestorLevel ='1''.BindingExpression:路径= MyString中; 的DataItem = NULL; target元素是'PropertiesVm'(HashCode = 24649639); target属性是'ThresholdName'(类型'String')

目前,PropertiesVm只有依赖属性,PropertiesView只是一个空网格.这样我就可以先处理这个错误,然后再担心下一个绑定阶段.

我不明白为什么我收到错误信息或我做错了什么.如果需要,我可以愉快地提供更多代码.现阶段的项目很早,因此,代码最少.

MyD*_*ons 1

答案就在留言里!

System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。BindingExpression:Path=MyString; 数据项=空;目标元素是“PropertiesVm”(HashCode=5991653);目标属性是“ThresholdName”(类型“String”)

据我了解,因为我的 UserControl 继承了 DependencyObject 而不是 UserControl,所以它不是 UIElement ...

因此,我必须将依赖属性移至视图的代码隐藏中,这允许两种方式绑定工作,但将 ViewModel 的数据上下文保留在 ViewModel 中。