This question already has an answer here:
- Binding the Path Property of a Binding 5 answers
How can I achieve something like following
<CheckBox Content="{Binding Caption}">
<CheckBox.IsChecked>
<Binding Path="{Binding PropertyName}"
Source="{Binding Source}" />
</CheckBox.IsChecked>
</CheckBox>
Where
public class ViewModel
{
public string Caption { get; } = "Test";
public string PropertyName { get; } = nameof(Test.Property);
public object Source { get; } = new Test();
}
public class Test
{
public bool Property { get; set; } = false;
}
Idea is to supply Path
and Source
(unknown at design time) for the binding via properties.
Currently this throw exception at <Binding Path=
line
A 'Binding' cannot be set on the 'Path' property of type 'Binding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
The names of the source properties must be known at compile-time for you to be able set up the binding in XAML:
As the error message tells you, you cannot bind something to the Path property of a Binding.
If you don't know the names of the properties to bind to at design time, you could set up the bindings programmatically:
There is no way to do this in pure XAML though. Remember that XAML is a markup language.
I'll go with behaviors. Below behavior will get Source and Path and update the binding accordingly for IsChecked Property. You can extend this to meet your need. for now this is limited to IsChecked Property, you can write generic code to support all properties.
And Xaml usage,
SelectedPath is from model,and that's where i store the Property Name.
Note: you will need Interactivity assembly.
A bit late answer after seeing @WPFUser one, but it supports any property and I personally do not like Blend dependencies:
The usage is:
Target
can be any dependency property of the control. It's given as a plain string, not sure how I can improve this to get intellisense assistance when entering it.ToDo: binding is not removed if
Target
is changed (it will reflect changes made toSource
orProperty
though), no support for multiple dynamic bindings (e.g. to different properties of control).