2014-02-19 37 views
2

我有一個綁定到一個屬性在我看來模型的文本框和一個按鈕如下Windows Phone TextBox的提升命令RaiseCanExecuteChanged TextChanged?

<TextBox Text="{Binding UserName, Mode=TwoWay}" /> 

<Button Content="Log In" Command="{Binding LoginCommand}"/> 

我的用戶名屬性:

private string userName; 
     public string UserName 
     { 
      get 
      { 
       return this.userName; 
      } 
      set 
      { 
       SetProperty(ref userName, value); 
       ((DelegateCommand)(this.LoginCommand)).RaiseCanExecuteChanged(); 
      } 
     } 

login命令:

LoginCommand = new DelegateCommand(User_Login, Can_Login); 

Can_Login方法:

private bool Can_Login(object arg) 
     { 
      if (!string.IsNullOrEmpty(UserName)) 
       return true; 
      return false; 
     } 

我的問題是,登錄按鈕始終啓用,直到用戶名文本框不爲空,已失去焦點

我想要做的是讓用戶一旦在TextBox中立即鍵入一些文本而不讓TextBox失去焦點,就可以啓用該按鈕。

有沒有解決這個問題的方法?

回答

4

試着玩UpdateSourceTrigger綁定的屬性。 TextBox在默認情況下將其設置爲LostFocus事件,因此在此情況下在該事件之後調用了RaiseCanExecuteChanged。在WPF中,我們可以將它設置爲PropertyChanged。通過該設置RaiseCanExecuteChanged會立即改變文本屬性值後得到提升,而無需等待LostFocus事件:

<TextBox Text="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> 

不幸的是,PropertyChanged不是在Silverlight for Windows Phone支持可用。我們需要使用Explicit和提高結合UpdateSource事件手動在TextChanged引發的事件:

<TextBox Text="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=Explicit}" 
     TextChanged="OnTextChanged"/> 

//in code-behind 
private void OnTextChanged(object sender, TextChangedEventArgs e) 
{ 
    TextBox textBox = sender as TextBox; 
    BindingExpression bindingExpr = textBox.GetBindingExpression(TextBox.TextProperty); 
    //Manually call UpdateSource 
    bindingExpr.UpdateSource(); 
} 

注意,代碼隱藏在這種情況下是罰款(從MVVM蓬的視圖),因爲它只是在做一些UI /綁定相關的任務,而不是數據相關的任務。

參考文獻:

+1

非常感謝,它的工作對我來說,也許包裹在一個自定義的控制這一功能將使它更容易 –

相關問題