Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - binding to an explicitly implemented interface property from code behind/attached behaviour

I am trying to set up a binding to an explicitly implemented interface property from code-behind. The reason for the code-behind binding is that the path to the bound property can only be determined at run-time.

In the XAML, it is possible to bind thusly (example in MainWindow.xaml):

<TextBox Text="{Binding (local:IViewModel.Property)}"/>

and in fact, binding in the code behind works in a similar way (from MainWindow.xaml.cs):

var binding = new Binding("(local:IViewModel.Property)");

since WPF is able to pick up the namespace mapping.

My question is, how do I form a binding like this when the namespace mapping is not present (for example, in an attached behaviour)?

Many thanks in advance!

like image 785
mickeyt Avatar asked Oct 12 '12 07:10

mickeyt


People also ask

How does binding work in WPF?

Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface.

What is two way binding WPF?

Two way binding is used when we want to update some controls property when some other related controls property change and when source property change the actual control also updates its property.

Which class is used for data binding in WPF?

WPF data binding supports data in the form of CLR objects and XML. To provide some examples, your binding source may be a UIElement, any list object, a CLR object that is associated with ADO.NET data or Web Services, or an XmlNode that contains your XML data.


1 Answers

You would specify a full PropertyPath:

var propertyInfo = typeof(IViewModel).GetProperty("Property");
var propertyPath = new PropertyPath("(0)", propertyInfo);
var binding = new Binding
{
    Path = propertyPath
};

For details on the syntax passed to PropertyPath above, see PropertyPath.Path.

like image 91
Kent Boogaart Avatar answered Nov 13 '22 09:11

Kent Boogaart