I want to have a PasswordBox and another PasswordBox to repeat the chosen password and a submit button.
This is what i got:
WPF:
<UserControl.Resources>
<converter:PasswordConverter x:Key="PasswdConv"/>
</UserControl.Resources>
<PasswordBox PasswordChar="*" Name="pb1"/>
<PasswordBox PasswordChar="*" Name="pb2"/>
<Button Content="Submit" Command="{Binding ChangePassword}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource PasswdConv}">
<MultiBinding.Bindings>
<Binding ElementName="pb1"/>
<Binding ElementName="pb2"/>
</MultiBinding.Bindings>
</MultiBinding>
</Button.CommandParameter>
</Button>
Converter:
public class PasswordConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
List<string> s = values.ToList().ConvertAll(p => SHA512(((PasswordBox)p).Password));
if (s[0] == s[1])
return s[0];
return "|NOMATCH|";
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Command(ChangePassword):
if ((p as string) != "|NOMATCH|")
{
MessageBox.Show("Password changed");
}
else
{
MessageBox.Show("Passwords not matching");
}
When I set a breakpoint in the converter and in the command I get the following result: As soon as the view loads it jumps into the converter and tries to convert two PasswordBoxes. Both are empty. When I press the Button(It doesn't matter what's in the two PasswordBoxes) it doesn't get into the converter and stops at the command-if. P represents an empty password.
The
Convertmethod will only be called when a source property of the multi binding changes, but you are binding to thePasswordBoxitself and it never changes.And binding to the
Passwordproperty won't work either as thePasswordoBoxraises no change notification when this property changes.It does raise a
PasswordChangedevent though, so you could handle this and set theCommandParameterproperty in this event handler instead of using a converter:XAML:
If you want to be able to reuse this functionality across several views and
PasswordBoxcontrols, you should write an attached behaviour.