开发者

Are WPF Binding paths normalized under the hood?

I just wonder if it makes any difference, if I repeat the subpath to some property in each binding or if I bind the DataContext and only state the relative paths in the bindings.

Examples:

Absolute Paths:

<UserControl x:Name="uc"/>
  <StackPanel>
    <TextBox Text="{Binding ViewModel.Prop1, ElementName=uc}" />
    <TextBox Text="{Binding ViewModel.Prop2, ElementName=uc}" />
  </StackPanel>
</UserControl/>

Relative Paths:

<UserControl x:Name="uc"/>
  <StackPanel DataContext="{Binding ViewModel, ElementName=uc}">
    <TextBox Text="{Binding Prop1}" />
    <TextBox Text="{Binding Prop2}" />
  </StackPanel>
</UserControl/>

I do know that both bind the same properties, but I'm interested in what's really happening behind the scenes, because maybe this can influence performance in situations where there are much more than 2 bindings. Will the variant with absolute paths result in more "event traffic", because each of the text-bindings observes the ViewModel-property and its specific property? Or will it be exactly the same? I could imagine some BindingManager resolving all binding paths, s.th. both variants end up in exactly the 开发者_JAVA百科same IL.

If the structure of the binding hierarchy does have an influence: Is there any positive effect (beside code style preferences) of using the 'slower' approach with full paths in each binding?


Once the binding object is instantiated, it doesn't matter how elaborate the markup was that created it; the object contains a reference to the source property, and how that reference was found is no longer relevant. So the only performance impact of doing it one way over the other is going to be when the binding itself is instantiated.

Not only is not repeating yourself going to perform (imperceptibly) better, it's the right way to do it. The DRY principle is just as applicable to XAML as it is to any other kind of software development.


There are some differences between the two approaches but two factors that I can think of will reduce the difference between them:

  • the target of the binding must ultimately take into account all the property change events all along the path using either approach
  • the binding path evaluation is just one part of the much larger binding subsystem

This is probably similar to to the differences between re-evaluating property paths in a programming language like C#. Using a temporary variable might help performance and it might not.

As a result, I would suggest organizing both XAML and C# with the goals of readability and maintainability instead of performance, at least in this respect. You will find repeating the base data context tedious if you have to do it too often and it will make the XAML look cluttered. That's a good situation to use the properties indirectly through a new data context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜