Home > OS >  WPF password binding with passwordboxassistant through code
WPF password binding with passwordboxassistant through code

Time:01-20

I'm trying to create a login screen but I want to do everything through code. So generating the full UI through C#. But I'm working with MVVM model and I have data binding on my username but this doesn't work on the standard PasswordBox so I found a namespace online which makes a workarround, it's called PasswordBoxAssistant from FunctionalFun.UI. In the xaml I can create a passwordbox with the assistant but I'm making my UI through code and I'm not able to find how to use the PasswordBoxAssistant like that. So I have this: enter image description here And want the same thing but in my C# enter image description here But like you see in my code, I don't have access to it. No idea if the xaml will only be to access it with everything is compile or why I can't use it in my C#. Anybody that can help me implement this or point me to a direction?

CodePudding user response:

It seems PasswordBoxAssistant is an attached property similar to PassWordHelper here:

https://gist.github.com/alamsal/fcefce4fb2d2d70fb2d91ee12741a35f

You attach such properties as described here:

https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/ms749011(v=vs.100)#attached-properties-in-code

Hence something like

 PasswordBoxAssistant.SetBindPassword(yourPasswordBox, true);

Would add that to a variable yourPasswordBox.

You then need to create a binding on the BoundPassword dependency property of course.

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-create-a-binding-in-code?view=netframeworkdesktop-4.8

The property you are binding as target is the PasswordBoxAssistant dependency property.

Bindings are a bit fiddly in code. I have used the approach rarely.

A rough example:

Binding myBinding = new Binding();
// myBinding.Source = ViewModel; Datacontext is default, you probably don't need source.
myBinding.Path = new PropertyPath("SomeStringPropertyInDatacontext");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
yourPasswordBox.SetBinding(PasswordBoxAssistant.BoundPasswordProperty, myBinding);
  • Related