Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

wpf - Difference between {Binding PropertyName} and {Binding Path=PropertyName}

I've seen both styles used in the same project, and I wonder if there's any semantic difference between them, or if any would be recommended over the other and why.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a significant difference here which you will run into as soon as you have a complex property path with typed parameters.

Conceptually they are equivalent as they both end up setting the Binding.Path, one via the parameterized Binding constructor, the other directly via the property. What happens internally is very different though as the Binding.Path is not just a string which in both cases would be passed on to the property, it is a PropertyPath.

When XAML is parsed, type converters are used to turn strings into the types expected by properties. So when you use Path= a PropertyPathConverter will be instantiated to parse the string and return a PropertyPath. Now here is the difference:

(In the case of the Binding constructor the Object[] will be empty)

How does this matter?

If you for example have multiple indexers in a class e.g. one that expects a string and one that expects an int and you try to cast the value to target the latter, the cast will not work:

{Binding [(sys:Int32)0]}

The PropertyPath is lacking the ITypeDescriptorContext because the public constructor is invoked so the type System.Int32 cannot be resolved from the string sys:Int32.

If you use Path= however the type converter will be used instead and the type will be resolved using the context, so this will work:

{Binding Path=[(sys:Int32)0]}

(Aren't implementation details fun?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...