How to bind to a PasswordBox in MVVM

前端 未结 30 1782
执念已碎
执念已碎 2020-11-22 11:50

I have come across a problem with binding to a PasswordBox. It seems it\'s a security risk but I am using the MVVM pattern so I wish to bypass this. I found som

30条回答
  •  逝去的感伤
    2020-11-22 12:38

    I am using succinct MVVM-friendly solution that hasn't been mentioned yet. First, I name the PasswordBox in XAML:

    
    

    Then I add a single method call into view constructor:

    public LoginWindow()
    {
        InitializeComponent();
        ExposeControl.Expose(this, view => view.Password,
            (model, box) => model.SetPasswordBox(box));
    }
    

    And that's it. View model will receive notification when it is attached to a view via DataContext and another notification when it is detached. The contents of this notification are configurable via the lambdas, but usually it's just a setter or method call on the view model, passing the problematic control as a parameter.

    It can be made MVVM-friendly very easily by having the view expose interface instead of child controls.

    The above code relies on helper class published on my blog.

提交回复
热议问题