I’ve created a UserControl with an ItemContext DependencyProperty. This property contains the name of the property of my DataContext object the Control’s text property should bind to.
I cannot figure out how to do this in XAML. I tried several steps, I’m quite near but couldn’t find it.
Something like this:
<TextBox Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type me:UserControl}}, Path=ItemContext}" />
But here the contents of “ItemContext” is bound directly to the Text Property which I don’t want. The contents of “ItemContext” let’s say “Property1” is the name of the property in my DataContext I’d like to bind to.
In code it works like this:
this.txtValue0.SetBinding(TextBox.TextProperty, new Binding(this.ItemContext) { Mode = BindingMode.TwoWay });
Does someone have an idea?
Thanks
It sounds as though what you’re trying to pass an external value into the
Pathproperty of aBindingobject. That is, ifItemContext‘s value is “Blob”, you want to bind toDataContext.Blob(not display the value “Blob”).That’s easy to do in code, because you can reference the value directly (you pass
this.ItemContextto your binding as a one-time value). In markup, however, you can’t do this. Instead, you’re trying to bind a value to thePathof theBinding, but you can’t (because it’s not a DependencyProperty).I’d suggest that a much easier solution would be to create a different property on your UserControl: instead of passing in “the name of the thing you want to bind to,” why not just pass in the value of the thing?
I’m imagining that your current code looks like this:
… and instead you should make it look like this:
… so the value is resolved externally of the control. Within the control, you can use @dowhilefor’s solution to bind to the value.
Hope that makes sense!