Using MultiBinding to Bind Elements

I have a login form that contains a user text field and a password field.

I want the ok button to be enabled only when both fields contain a value.

I have a converter that checks all strings if they are empty or empty.

I put a breakpoint on the first line of the Convert method and only stops when it MenuItem

initializes the afterword, that is, when I change the text it doesn't.

The following example works well, the problem is that multi-connectivity doesn't work when the text changes; it is bound only when the form is initialized:

<!--The following is placed in the OK button-->
<Button.IsEnabled>
    <MultiBinding Converter="{StaticResource TrueForAllConverter}">
        <Binding ElementName="tbUserName" Path="Text"/>
        <Binding ElementName="tbPassword" Path="Password"/>
    </MultiBinding>
</Button.IsEnabled>

      

I think the problem is that you don't get notifications when the source of the remote binding is changed (for example, there is no way to set UpdateTargetTrigger="PropertyChanged"

.

Any ideas?

+2


source to share


3 answers


I would suggest that you look into command binding. The command can automatically enable or disable your login button based on some condition (that is, the username and password are not empty).

public static RoutedCommand LoginCommand = new RoutedCommand();

private void CanLoginExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = !string.IsNullOrEmpty(_userInfo.UserName) && !string.IsNullOrEmpty(_userInfo.Password);
    e.Handled = true;
}

private void LoginExecute(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Loging in...");
    // Do you login here.
    e.Handled = true;
}

      

The XAML command binding would look something like this:

<TextBox Text="{Binding UserName, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="local:LoginWindow.LoginCommand" >Login</Button>

      

To register a command in XAML



<Window.CommandBindings>
    <CommandBinding Command="local:LoginWindow.LoginCommand" CanExecute="CanLoginExecute" Executed="LoginExecute" />
</Window.CommandBindings>

      

Or in code

public LoginWindow()
{
    InitializeComponent();

    CommandBinding cb = new CommandBinding(LoginCommand, CanLoginExecute, LoginExecute);
    this.CommandBindings.Add(cb);
}

      

More readigin here .

+2


source


Try installing UpdateSourceTrigger

on PropertyChanged

and Mode

on TwoWay

. This will cause the property to update as you type. Not sure if this will work with your converter.



0


source


Private Sub tb_Changed(sender As Object, e As RoutedEventArgs) _
        Handles tbUsername.TextChanged, _
                tbPassword.PasswordChanged
    btnOk.IsEnabled = tbUsername.Text.Length > 0 _
              AndAlso tbPassword.Password.Length > 0
End Sub

      

0


source







All Articles