WPF绑定祖先

时间:2010-04-20 11:58:21

标签: wpf binding

我遇到绑定问题。我想使用UserControl(来自codeplex的Intellibox),但我只在输出窗口中收到错误消息。 基本上我有

window grid ... stuff ... usercontrol (self written) ... stuff ... usercontrol (IntelliBox)   

在“输出”窗口中,我得到以下内容:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 
  'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', 
  AncestorLevel='1''. BindingExpression:Path=ShowResults; DataItem=null; 
  target element is 'Popup' (Name='IntelliboxPopup1'); 
  target property is 'IsOpen' (type 'Boolean')  

IntelliBox控件中的绑定定义如下:

{Binding Path=ShowResults, RelativeSource={RelativeSource FindAncestor, 
 AncestorType={x:Type UserControl}}}

我想有一个问题,导致使用usercontrols嵌套 - 如何修复此错误?

谢谢!

1 个答案:

答案 0 :(得分:2)

我有两个问题。首先,这是你为自己使用而编写的Binding,还是在你正在使用的UserControl中开箱即用的东西?第二,你是想尝试绑定到Intellibox,还是你的“自编”UserControl?

假设它是你为自己使用而编写的Binding(我不知道Intellibox,所以我不知道从哪里开始修复它),你可以尝试一些解决方案。

首先,绑定到祖先时,请尝试使用确切的祖先类型。例如,如果您绑定到Intellibox,请使用AncestorType={x:Type Intellibox}。否则使用AncestorType={x:Type <YourType>}。你的绑定将不那么模糊。

其次,也许在这种情况下最好的答案是通过在目标上设置x:Name="BindSource (or whatever)"并使用Binding语法绑定到您想要的名称控件:

{Binding Path=ShowResults,
         ElementName=BindSource}

- HTH, 多尘