What is the best approach for creating binding at runtime?
In my application I want to create binding during runtime, and each object has to have a separate binding.
For example: I have two copies of a UserControl and each copy has property Text and it has to be bound to different data source.
And as Dependency property is static it won't allow to have a DP per instance, only one per class.
So I wonder what is the best ap开发者_开发技巧proach to achieve it?
For dynamically working with data binding, check out the BindingOperations static class.
As far as using DPs, I'm not sure what you're asking. The DP itself is static, but the value of a DP is associated per-instance. Otherwise, how could multiple TextBox instances have different Text values? The bindings are specific to each instance, as well.
Are the two different data sources different types? Or are they two different instances of the same type?
I ask because the solution you're requesting - creating a binding at runtime - may be unnecessarily complex. You wouldn't normally need to create the bindings at runtime to solve the problem you've described. From what you've said so far about the problem, it sounds like a much simpler solution should work.
It's extremely common to have multiple instances of a particular user control, and for each instance to be bound to a different source object. You can do this with normal data binding expressions in Xaml. The trick is to rely on the DataContext to determine which particular each user control uses as its source. For example:
<my:MyUserControl DataContext="{Binding Path=Source1}" />
<my:MyUserControl DataContext="{Binding Path=Source2}" />
That'll create two instances of a custom user control, MyUserControl, and any bindings in the first one will attach to whatever object was in Source1, while the second will use Source2. So if MyUserControl.xaml contains something like this:
<TextBlock Text="{Binding Path=Name}" />
then that will bind to the Name property of two different source objects in the two different user control instances.
This addresses your stated requirement that each user control "has to be bound to different data source."
精彩评论