MVVM默认按钮比TextBox提交文本更快地到ViewModel

时间:2010-12-22 08:00:13

标签: wpf mvvm f#

当我使用DefaultButton输入登录密码(编辑登录+ Tab ,编辑密码+ 输入)时,X.Password属性仍未更改。那么当我使用DefaultButton时如何提交密码?

member X.Password
    with get()      = password
    and set value   = 
        password <- value
        X.OnPropertyChanged "Password"

member X.LoginCommand =
    new RelayCommand ((fun canExecute -> true), (fun action ->
            X.SelectedAccount <-
                match
                    X.Accounts
                    |> Seq.filter (fun acc -> 
                        acc.Name        = login && 
                        acc.Password    = password) with
                    | s when Seq.isEmpty s -> 
                        X.ConvertButtonEnabled <- false
                        ignore <| MessageBox.Show(sprintf 
                            "User %s doesn't exist or password incorrect password" X.Login) 
                        {Name=""; Role=""; Password=""; ExpenseLineItems = []}
                    | s -> 
                        X.ConvertButtonEnabled <- true
                        X.LoginExpander <- false
                        Seq.head s

            X.Login     <- ""
            X.Password  <- "" ))

XAML:

            <Button Content="Login" Command="{Binding LoginCommand}" Height="23" HorizontalAlignment="Left" Margin="79,71,0,0" Name="LoginButton" VerticalAlignment="Top" Width="75" IsDefault="True" />
            <TextBox Text="{Binding Login}" Height="28" HorizontalAlignment="Left" Margin="61,6,0,0" Name="Login" VerticalAlignment="Top" Width="142" />
            <TextBox Text="{Binding Password}" Height="26" HorizontalAlignment="Left" Margin="61,34,0,0" Name="Password" VerticalAlignment="Top" Width="142" />

VMBase

type ViewModelBase() =
    let propertyChangedEvent = new DelegateEvent<PropertyChangedEventHandler>()
    interface INotifyPropertyChanged with
        [<CLIEvent>]
        member x.PropertyChanged = propertyChangedEvent.Publish

    member x.OnPropertyChanged propertyName = 
        propertyChangedEvent.Trigger([| x; new PropertyChangedEventArgs(propertyName) |])

中继命令

type RelayCommand (canExecute:(obj -> bool), action:(obj -> unit)) =
    let event = new DelegateEvent<EventHandler>()
    interface ICommand with
        [<CLIEvent>]
        member x.CanExecuteChanged = event.Publish
        member x.CanExecute arg = canExecute(arg)
        member x.Execute arg = action(arg)

1 个答案:

答案 0 :(得分:6)

绑定设置(默认情况下)仅在TextBox失去焦点时更新。按Enter键时,TextBox不会失去焦点。你可以通过告诉文本框一旦更改就更新绑定值来解决这个问题,如下所示:

   <TextBox Text="{Binding Login, UpdateSourceTrigger=PropertyChanged}"/>
   <TextBox Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}"/>