Silverlight DataForm DataField vs PasswordBox
Cristian Merighi ()

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 ...next!
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:
C#
- private void loginDataForm_AutoGeneratingField(object sender, DataFormAutoGeneratingFieldEventArgs e)
- {
- if (e.PropertyName == LoginInfoViewModel.PASSWORD_FIELD)
- {
- // take care of the bindings already set in
- // System.Windows.Controls.DataForm //-> private bool GenerateField(Type propertyType, string propertyName, BindingMode bindingMode, Panel panel)
- var binding = e.Field.Content.GetBindingExpression(TextBox.TextProperty).ParentBinding;
- // the idea is to "switch" the current TextBox control
- // replacing it with a PasswordBox
- var pbox = new PasswordBox();
- pbox.SetBinding(PasswordBox.PasswordProperty, binding);
- e.Field.Content = pbox;
- }
- }
Hope it helped.
Take care. Bye.