Reputation: 49
I am trying to bind a ListBox
from the View to a class in the ViewModel. I have no trouble binding it inside the main View. But when I try to do some binding in the other XAML views, I am getting the below error. What is the problem here?
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='OutlookCalendar.Controls.OpenSummaryLine', AncestorLevel='1''. BindingExpression:Path=SummaryLines; DataItem=null; target element is 'ListBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
<ListBox Grid.Row="6"
Grid.ColumnSpan="3"
Background="White"
Margin="5,0,22,5"
ItemsSource="{Binding SummaryLines,
RelativeSource={RelativeSource AncestorType={x:Type local:OpenSummaryLine}}}"
IsSynchronizedWithCurrentItem="True" />
Upvotes: 0
Views: 3083
Reputation: 69987
You cannot use a RelativeSource Binding
if the source is not relative to (or more accurately, a parent of) the control with the relevant Binding
. From the Binding.RelativeSource
Property page on MSDN:
Gets or sets the binding source by specifying its location relative to the position of the binding target.
Therefore, if your required source has no relation to the control with the relevant Binding
, you will get the error that you did, which basically means:
Cannot find an
OpenSummaryLine
element that is relative to theListBox Binding
.
One simple solution is to move the source collection to a common parent, with the object that you have set as the MainWindow.DataContext
property being the most likely target. If you add a SummaryLines
property into that object, then you can use a RelativeSource Binding
to access it from every control displayed in the MainWindow
, either directly, or indirectly in UserControl
s:
<ListBox Grid.Row="6" Grid.ColumnSpan="3" Background="White" Margin="5,0,22,5"
ItemsSource="{Binding DataContext.SummaryLines, RelativeSource={RelativeSource
AncestorType={x:Type local:MainWindow}}}"
IsSynchronizedWithCurrentItem="True" />
Of course, the local
XAML Namespace Prefix used here would have to reference the assembly that MainWindow
is declared in for this to work. You could use the same Binding.Path
in your OpenSummaryLine
view too and it will data bind to the same collection.
Upvotes: 2
Reputation: 3111
When you use RelativeSource
or ElementName
in a Binding
, you are binding to the object and not to the object's data context. For that you'll need to prefix your binding path with 'DataContext'. Try this:
ItemsSource="{Binding DataContext.SummaryLines,
RelativeSource={RelativeSource AncestorType={x:Type local:OpenSummaryLine}}}"
Upvotes: 1