询问者
请问出现XAML绑定失败,怎么查原因?

问题
-
WPF项目,调试的时候VS显示如下错误:
同时控制台还会输出大量这种信息:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
我找遍了整个项目的所有文件,都没有找到对应的代码(例如查找HorizontalContentAlignment,VerticalContentAlignment等等),请问这种问题应该怎么解决?
da jia hao!
- 已编辑 liubin 2020年11月18日 3:56
全部回复
-
你好,
你的项目中有为MenuItem自定义的ControlTemplate代码吗?像这样的:
<Setter Property="Control.HorizontalContentAlignment"> <Setter.Value> <Binding Path="HorizontalContentAlignment" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}" /> </Setter.Value> </Setter> <Setter Property="Control.VerticalContentAlignment"> <Setter.Value> <Binding Path="VerticalContentAlignment" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=1}" /> </Setter.Value> </Setter>
如果有的话,你可以把它改为在Style中直接设置试试:
<Style TargetType="MenuItem"> <Setter Property="HorizontalContentAlignment" Value="Left"/> <Setter Property="VerticalContentAlignment" Value="Center"/> </Style>
因为看不到你的代码,所以没办法确切分析你的问题。如果不是我上边说的问题导致的,你可以在Onedrive、github给我一个可以重现问题的demo吗?(PS:其中不要包含你的隐私信息)
谢谢
Daisy Tian
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com. -
你好,
很高兴你的问题解决了,VerticalContentAlignment 是 Menu的属性,应该是你的MenuItem外部没有包Meun,所以系统没有办法找到MenuItem 父控件 Meun 的 VerticalContentAlignment/HorizontalContentAlignment属性.
如果要查控件的默认模板,以Meun为例:在Visula Studio 中找到Document Outline>右击Menu>选择Edit Template > 点击Edit a copy...就可以查看控件的默认模板。
谢谢
Daisy Tian
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.