积极答复者
有关wpf样式中出现绑定异常问题

问题
-
大侠们好;
遇到一个奇怪的问题,程序运行起来不会有什么问题,但是在展现数据的时候会非常慢,然后看到输出里面有以下错误信息:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'TreeViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
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 'TreeViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')
请问大侠们,为什么程序编译和执行都没有问题,仅仅影响性能而已?这种错误如何查找和修改呢?
答案
-
不是的,其实有很多时候多会出现这个错误信息啊,比如ComboboxItem是在Popup中呈现,WPF的Popup是有自己独立的VisualTree的,你的ComboBoxItem的默写属性如果按照上面的方式去写,relativeresource是遍历不到想要的VisualTree的所以就会有绑定错误,但是对你的程序是没有影响的,这类情况更多的是出现在TreeView中,比如一个TreeViewItem还没有展开的时候,里面的Item是根本不在VisualTree里面的,你用RelativeSource进行绑定是无效的,但是当你展开这个Item,这个RelativeSource就会找到相应的Item啊,这样就是开始的时候报错 后来就正常了,也是不会有影响的,有时候虚拟化也会影响到绑定的工作,不过不会对快慢有太大的影响
Sheldon _Xiao[MSFT]
MSDN Community Support | Feedback to us
Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 xxyxxb2080 2011年12月22日 1:04
全部回复
-
这样类似的问题我有碰到过,程序编译或者运行都不会报错,只会影响性能。我之前的解决方法是将出现异常的绑定修改或者删除。例如:<Setter Property="HorizontalContentAlignment"Value="{Binding Path=HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>我会把这个设置删除,或者修改为<Setter Property="HorizontalContentAlignment"Value="Center"/>;但是这次不好使!
-
首先你说慢,然后找到了这个错误信息,这两件事情是没关系的,那个错误信息你可以忽略,比如在默认template里面,有时候你会看到:
<Setter Property="HorizontalContentAlignment"
Value="{Binding Path=HorizontalContentAlignment,RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
这样的代码也会导致那个错误,这个是不会影响速度的。
关于你的速度问题,你需要分享更多的信息了。(比如虚拟化)
Sheldon _Xiao[MSFT]
MSDN Community Support | Feedback to us
Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
不是的,其实有很多时候多会出现这个错误信息啊,比如ComboboxItem是在Popup中呈现,WPF的Popup是有自己独立的VisualTree的,你的ComboBoxItem的默写属性如果按照上面的方式去写,relativeresource是遍历不到想要的VisualTree的所以就会有绑定错误,但是对你的程序是没有影响的,这类情况更多的是出现在TreeView中,比如一个TreeViewItem还没有展开的时候,里面的Item是根本不在VisualTree里面的,你用RelativeSource进行绑定是无效的,但是当你展开这个Item,这个RelativeSource就会找到相应的Item啊,这样就是开始的时候报错 后来就正常了,也是不会有影响的,有时候虚拟化也会影响到绑定的工作,不过不会对快慢有太大的影响
Sheldon _Xiao[MSFT]
MSDN Community Support | Feedback to us
Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 xxyxxb2080 2011年12月22日 1:04