Convention based binding to multiple properties

Feb 22, 2011 at 1:12 AM

Is it possible to created a custom convention that will allow me to wire up multiple properties (even attached properties)? For example, I'd like to automatically wire up the following bindings:

<c:FormPanel >
    <TextBox x:Name="Username" 
             c:FormPanel.LabelText="{Binding UsernameLabelText}" 
             c:FormPanel.HasError="{Binding UsernameHasError}"
             c:FormPanel.IsRequired="{Binding UsernameIsRequired}"/>

It would be great if I could define a convention that was ControlNamePropertyName or even ControlName_PropertyName.


Feb 22, 2011 at 11:26 PM

Something along this line should work (sorry, can't actually test it right now)

//in bootstrapper
ConventionManager.AddElementConvention<TextBox>(TextBox.TextProperty, "Text", "TextChanged")
	.ApplyBinding = (viewModelType, path, property, element, convention) => {
		if(!SetBinding(viewModelType, path, property, element, convention))

		var textBox = (TextBox)element;
		if (...) { //you should check if VM has the required property
			BindingOperations.SetBinding(element, FormPanel.LabelText, new Binding(path + "LabelText"));
		if (...) { 
			BindingOperations.SetBinding(element, FormPanel.HasError, new Binding(path + "HasError"));
		if (...) { 
			BindingOperations.SetBinding(element, FormPanel.IsRequired, new Binding(path + "IsRequired"));

This basically replaces the default convention for the textbox, adding some additional operation after the default conventional binding has taken place.

Feb 24, 2011 at 1:48 PM

Great! I'll give it a try. 

Thank you!