【发布时间】:2010-11-30 18:24:33
【问题描述】:
以下哪些 TextBlocks 的绑定会消耗更多性能:
<Window
x:Name="Me"
x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
Title="MainWindow">
<StackPanel>
<TextBlock Text="{Binding Title, ElementName=Me}"/>
<TextBlock Text="{Binding Title, RelativeSource={RelativeSource AncestorType={x:Type src:MainWindow}}}"/>
</StackPanel>
</Window>
我确信当 TextBlocks 处于具有许多兄弟姐妹和祖先的高嵌套级别时,我的问题可能会有所不同。
注意事项
(仅基于个人想法,我可能在每个特定的地方都错了!):
-
ElementName:- 可能会搜索当前元素并将其与更多控件进行比较,包括其所有子元素、兄弟姐妹、叔叔和叔叔,包括祖先(可能存在所有已注册名称的 HashTable?)
- 获取控件的
Name属性应该比调用GetType花费更少的性能。 - 比较字符串比比较类型更便宜,尤其是当您知道大多数控件甚至没有设置
Name时。
-
FindAncestor:- 只会遍历祖先,而不是兄弟姐妹“叔叔”、“堂兄弟”等。
- 最有可能使用
GetType来确定祖先类型; GetType 比简单的Name属性 getter 花费更多的性能(可能 DP 不同?)
【问题讨论】:
-
偏离性能主题的注释(但仍然是
ElementName与RelativeSource):请记住,ElementName是'早期绑定',而 @987654333 @ 是 'late-binding',这可能会导致意想不到的结果,如我的这个问题所示:stackoverflow.com/questions/18419041/…
标签: wpf binding performance relativesource elementname