我正在尝试将ListBox从视图绑定到ViewModel中的一个类。我没有困难将它绑定在主视图中。但是,当我试图在其他XAML视图中执行一些绑定时,我将得到以下错误。这里有什么问题?
AncestorType='OutlookCalendar.Controls.OpenSummaryLine',System.Windows.Data错误:4:无法找到引用'RelativeSource FindAncestor,RelativeSource AncestorLevel=‘1’绑定的源代码。BindingExpression:Path=SummaryLines;DataItem=null;目标元素是'ListBox‘(Name='');目标属性是'ItemsSource’(键入'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" />发布于 2014-08-08 17:23:06
在RelativeSource或ElementName中使用Binding时,您将绑定到对象,而不是绑定到对象的数据上下文。为此,您需要在绑定路径前面加上“DataContext”。试试这个:
ItemsSource="{Binding DataContext.SummaryLines,
RelativeSource={RelativeSource AncestorType={x:Type local:OpenSummaryLine}}}"发布于 2014-08-08 17:40:12
如果源不是相对于(或更准确地说是与相关的RelativeSource Binding的父控件)相关的控件,则不能使用Binding。来自MSDN上的 Property页面:
通过指定绑定源相对于绑定目标位置的位置,获取或设置绑定源。
因此,如果所需的源与相关的Binding与控件无关,您将得到所做的错误,这基本上意味着:
找不到相对于
OpenSummaryLine的ListBox Binding元素。
一个简单的解决方案是将源集合移动到公共父级,其中最有可能的目标是您设置为MainWindow.DataContext属性的对象。如果将SummaryLines属性添加到该对象中,则可以使用RelativeSource Binding从MainWindow中显示的每个控件直接或间接地从UserControl中访问该属性:
<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" />当然,这里使用的local XAML名称空间前缀必须引用MainWindow声明的程序集才能工作。您也可以在您的Binding.Path视图中使用相同的OpenSummaryLine,并且它将数据绑定到同一个集合。
https://stackoverflow.com/questions/25205254
复制相似问题