【发布时间】:2018-04-17 06:11:14
【问题描述】:
我有一个自定义用户控件,它具有如下依赖属性:
public static readonly DependencyProperty PagesProperty =
DependencyProperty.Register("Pages", typeof(IEnumerable<MyContentPage>), typeof(UC_ApplicationWindow),
new PropertyMetadata(new List<MyContentPage>()));
public IList<MyContentPage> Pages
{
get => (IList<MyContentPage>)GetValue(PagesProperty);
set => SetValue(PagesProperty, value);
}
我在另一个项目中使用它:
<graphicElements:UC_ApplicationWindow>
<graphicElements:UC_ApplicationWindow.Pages>
<x:Array Type="{x:Type graphicElements:MyContentPage}">
<graphicElements:MyContentPage>
<graphicElements:MyContentPage.Content>
<StackPanel>
<ContentControl DataContext="{Binding DataContext, ElementName=gd_Main}">
...some content
</ContentControl>
...other content
</StackPanel>
</graphicElements:MyContentPage.Content>
</graphicElements:MyContentPage>
<graphicElements:MyContentPage>
<graphicElements:MyContentPage.Content>
<StackPanel>
<ContentControl DataContext="{Binding DataContext, ElementName=gd_Main}">
...some content
</ContentControl>
...other content
</StackPanel>
</graphicElements:MyContentPage.Content>
</graphicElements:MyContentPage>
</x:Array>
</graphicElements:UC_ApplicationWindow.Pages>
</graphicElements:UC_ApplicationWindow>
基本上在内容的一部分中,我试图从父网格 (gd_Main) 的上下文中提取 DataContext,而不是从向下传递给它的页面中提取。我的 ElementName 绑定有效...对于数组中的第一个元素。对于数组中的所有其他元素,我得到这个:
Cannot find source for binding with reference 'ElementName=gd_Main'. BindingExpression:Path=DataContext; DataItem=null; target element is 'ContentControl' (Name=''); target property is 'DataContext' (type 'Object')
我错过了什么?为什么它会正确绑定第一项而不是其余项?有没有更好的方法来解决这个问题?
【问题讨论】:
-
我不完全确定,但名称范围可能存在问题。要解决此问题,您可以尝试使用 Source={x:Reference gd_Main} 而不是 ElementName
-
嗯,嗯,这有点工作......我试图绑定的元素在 gd_Main 内部,所以当我将它更改为引用时,它会给我循环引用错误。我在 gd_Main 内创建了一个虚拟网格(因此它是包含我要绑定的控件的顶级元素的同级元素)并将名称移到该网格中。这行得通,它得到了正确的上下文,但它似乎非常笨拙......似乎必须有更好的方法。
标签: wpf xaml data-binding