2012-01-15 97 views
2

我正在實現一個基本的搜索文本框 - >按鈕,但我也希望讓用戶能夠按下Enter/Return鍵鍵盤/鍵盤按照How to enable enter button on keyboard on wp7?ViewModel中的RelayCommand:調用無法訪問ViewModel中的綁定UI數據

當RelayCommand被調用時,我只是得到一個空值的搜索文本框的內容。

我正在使用MVVM Light。

我有被綁定到視圖模型與所述特性的的PhoneApplicationPage:

public class MainViewModel : ViewModelBase 

{ 

private string _searchString; 

public RelayCommand Search { get; private set; } 
public RelayCommand<KeyEventArgs> SearchTextBoxKeyDown { get; private set; } 

public string SearchString 
{ 
    get { return _searchString; } 
    set 
    { 
     if (_searchString != value) 
     { 
      _searchString = value; 
      RaisePropertyChanged("SearchString"); 
     } 
    } 
} 

public MainViewModel() 
{ 
    if (IsInDesignMode) 
    { 
     // Code runs in Blend --> create design time data. 
    } 
    else 
    { 
     // Code runs "for real" 
     SearchTextBoxKeyDown=new RelayCommand<KeyEventArgs>((e)=> 
     { 
      if (e.Key == Key.Enter) 
      { 
       // SearchString is empty here? 
       Search.Execute(null); 
      } 
     }); 
     Search = new RelayCommand(() => 
     { // invokes Search with SearchString 

     }, 
     () => 
     { 
      bool isEnabled = true; 
      if (string.IsNullOrWhiteSpace(SearchString)) isEnabled = false; 
      return isEnabled; 
     }); 
    } 
} 

觀使用MVVM光工具包來援引的KeyDown該方法在自動完成控制(它是一個Telerik的控制,但它看起來像一個TextBox和氣味像一個TextBox):

   <telerikInput:RadAutoCompleteBox 
        InputScope="Search" 
        Text="{Binding SearchString,Mode=TwoWay}" 
        SuggestionsSource="{Binding MruSearchStrings}"> 
        <i:Interaction.Triggers> 
         <i:EventTrigger EventName="KeyDown"> 
          <cmd:EventToCommand x:Name="searchStringTextBoxKeyDown" Command="{Binding SearchTextBoxKeyDown, Mode=OneWay}" PassEventArgsToCommand="True"> 
          </cmd:EventToCommand> 
         </i:EventTrigger> 
        </i:Interaction.Triggers> 
       </telerikInput:RadAutoCompleteBox> 

在調用的代碼,我只是得到空當我訪問SearchString在,這是什麼,TextBox是必然 - 即使我已進入文本它。就好像SearchTextBox沒有將其數據發送回ViewModel以供ViewModel在事件代碼中使用。

我在做什麼錯?

回答

2

您的ViewModel沒有使用TextBox中的值進行更新,因爲當您按Enter鍵時,您仍然在TextBox中獲得焦點。默認情況下,ViewModel將在您離開TextBox控件後進行更新。但是,您可以通過使用自定義行爲來更改這種情況。這一個對我來說 就像一個魅力:http://zoltanarvai.com/2009/07/22/binding-update-on-textbox-textchanged-event-using-behaviors/

+0

優秀。非常感謝。多了一點XAML瞭解。 – 2012-01-16 22:23:47