Silverlight DataForm DataField vs PasswordBox

Cristian Merighi () 0.00

Get rid of the improperly autogenerated TextBox DataField when you need a PasswordBox instead.
This article is obsolete. Some functionalities might not work anymore. Comments are disabled.

First thing to be said: sometimes I barely understand the lack of some implementations in scenarios that seem to me pretty comprehensible and easy to define. Other times I get stunned, amazed by some solutions of genius.

I'm talking about Microsoft products. These are days of massive - almost overwhelming - upheavals in terms of innovations and strategical decisions, it's difficult to give priorities and to schedule what to learn, what to do, where to invest!

Usually, your timely every-day low-profile issue (related to one of the technologies you already master) comes in help to wash your brain up with more urgent dilemmas: why the heck not to fix that stupid bug?!

The bug I'm talking about (actually more an oversight) is relevant to the loved/hated DataForm that comes with the Silverlight Toolkit.
Why the heck - and two! - my DataField doesn't properly render a PasswordBox, given that my model explicitly declares a property of that DataType?

Tha answer is easy: not considered. DataType metaattribute doesn't even get involved in the DataField generation procedure. Please refer to the <private bool GenerateField(Type propertyType, string propertyName, BindingMode bindingMode, Panel panel)> method in the System.Windows.Controls.DataForm class (use ILSpy or equivalent to inspect).

how to react against this unfairness? Thanks to ILSpy I figured out: inject some proper code as the AutoGeneratingField event rises:

  1. private void loginDataForm_AutoGeneratingField(object sender, DataFormAutoGeneratingFieldEventArgs e)
  2. {
  3.     if (e.PropertyName == LoginInfoViewModel.PASSWORD_FIELD)
  4.     {
  5.         // take care of the bindings already set in
  6.         // System.Windows.Controls.DataForm //-> private bool GenerateField(Type propertyType, string propertyName, BindingMode bindingMode, Panel panel)
  7.         var binding = e.Field.Content.GetBindingExpression(TextBox.TextProperty).ParentBinding;
  8.         // the idea is to "switch" the current TextBox control
  9.         // replacing it with a PasswordBox
  10.         var pbox = new PasswordBox();
  11.         pbox.SetBinding(PasswordBox.PasswordProperty, binding);
  12.         e.Field.Content = pbox;
  13.     }
  14. }

Hope it helped.

Take care. Bye.




Cristian Merighi facebook twitter google+ youtube

Latest articles

Top rated


Where am I?


Cristian Merighi facebook twitter google+ youtube

I'm now reading