I'm implementing a basic search text box->button, but I also want to have the user be able to hit the Enter/Return key on the keyboard/pad, as per How to enable enter button on keyboard on wp7?
When the RelayCommand gets invoked, I just get a null value for the contents of the search text box.
I'm using MVVM Light.
I have a PhoneApplicationPage that is bound to a ViewModel with the properties:
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;
});
}
}
The View uses the MVVM Light toolkit to invoke the method for KeyDown on the AutoComplete control (it is a Telerik control, but it looks like a TextBox and smells like a 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>
In the invoked code, I just get null when I access the SearchString, which is what the TextBox is bound to - even though I have entered text into it. It's almost as if the SearchTextBox has not sent its data back to the ViewModel for the ViewModel to pick up in the event code.
What am I doing wrong?