One of my blog readers sent me an email regards how to create Binding to an object via XAML, where Path is unknown at design time.
For example, you want to bind to Source.Property property, where Property is provided by another property.
public partial class Window1 : Window
{
public Window1()
{
Path = "Name";
Person = new Person()
{
Name = "Tomer Shamam"
};
DataContext = this;
InitializeComponent();
}
public string Path { get; private set; }
public Person Person { get; private set; }
...
}
<TextBox Text="{Binding Path=???}" />
As you may guess correctly, we can’t bind to dynamic resolved path, unless you create the binding from code and explicitly specify the path (which is not always possible, and not recommended by design).
To solve this problem, I’ve just created a custom Binding object called BindingEx. BindingEx has two new properties: SourcePath and PathOrigin.
SourcePath – The path to the source object.
PathOrigin – The path to the dynamic resolved path.
Using BindingEx the markup above should be look like this:
<TextBox Text="{t:BindingEx SourcePath=Person, PathOrigin=Path}" />
As you can see, the Window1 instance is in the DataContext so we don’t have to specify source (but we can if we want to). SourcePath indicates that the binding should look for the source object in the Person property (which belongs to Window1 in this case), and PathOrigin points to the Path property (which also belongs to Window1 instance). This is where binding should extract the path to be bound to.
You may download my custom binding from here. Note that I didn’t check all the possible cases (there are many), so use it at your own risk.