My application has MainWindow. Inside this there is 1 control, ListBox , binding to the MainWindowViewModel property. This property is a UserControl of type CriteriaVm
CriteriaVm has one string property MyString
Inside the criteria view, I have the following code
<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>
As you can see, I bind MyString in 2 places. Binding in Expander works fine, i.e. in vm: PropertiesVm is not used (which uses Dependency Properites). In the output window
The following error is displayed:
System.Windows.Data error: 2: Cannot find a FrameworkElement or FrameworkContentElement control for the target element. BindingExpression: Path = MyString; DataItem = NULL; the target element is "PropertiesVm" (HashCode = 5991653); target is "ThresholdName" (type "String")
OK, the error message tells me that he is looking for MyString in ProperitesVm ... I have to look for MyString in CriteriaVm. This means that I need to use a RelativeSource, which, it seems to me, is above level 1 and of type UserControl. So I updated:
<vm:PropertiesVm ThresholdName="{Binding Path=MyString, RelativeSource={RelativeSource AncestorLevel=1,AncestorType=UserControl,Mode=FindAncestor}}" />
I get a slightly different problem, but it seems that the same basic error exists
Error System.Windows.Data: 4: Cannot find source for binding with reference "RelativeSource FindAncestor, AncestorType =" System.Windows.Controls.UserControl ", AncestorLevel = '1' '. BindingExpression: Path = MyString; DataItem = NULL; target element is "Properties VM" (HashCode = 24649639); target is "ThresholdName" (type "String")
Currently, PropertiesVm has only dependency properties, PropertiesView is just an empty grid. This means that I can handle this error first and worry about the next binding step later.
I do not understand why I am getting an error message or what I am doing wrong. I can happily provide more code if necessary. The project at this stage is very early, as such, a minimal code.