【发布时间】:2015-10-23 14:48:42
【问题描述】:
我的应用程序有一个主窗口。其中有 1 个控件,一个 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>
如您所见,我在 2 个地方绑定了 MyString。 Expander 中的绑定工作正常,vm:PropertiesVm 中的绑定没有(它使用依赖属性)。输出窗口中显示以下错误
System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。绑定表达式:路径=我的字符串;数据项=空;目标元素是“PropertiesVm”(HashCode=5991653);目标属性是“阈值名称”(类型“字符串”)
好的,错误消息告诉我它正在 ProperitesVm 中寻找 MyString ...我应该在 CriteriaVm 中寻找 MyString。这意味着我需要使用我认为的RelativeSource,它上升了1 级并且是UserControl 类型。所以我更新为:
<vm:PropertiesVm ThresholdName="{Binding Path=MyString, RelativeSource={RelativeSource AncestorLevel=1,AncestorType=UserControl,Mode=FindAncestor}}" />
我遇到了一个稍微不同的问题,但似乎存在相同的潜在故障
System.Windows.Data 错误:4:无法找到与引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.UserControl',AncestorLevel='1''的绑定源。绑定表达式:路径=我的字符串;数据项=空;目标元素是“PropertiesVm”(HashCode=24649639);目标属性是“阈值名称”(类型“字符串”)
目前,PropertiesVm 只有依赖属性,PropertiesView 只是一个空网格。这样我就可以先处理这个错误,然后再担心下一阶段的绑定。
我不明白为什么我会收到错误消息或我做错了什么。 如果需要,我可以很乐意提供更多代码。这个阶段的项目还很早,所以代码最少。
【问题讨论】:
-
1.将 [BindableAttribute(true)] 属性添加到 ThresholdName 属性
标签: wpf mvvm dependency-properties