Reputation: 507
I am trying to get the following: inside my page I have a textbox and button. When the user presses "Enter" on the keyboard it should do the same as clicking the button.
my code looks roughly as follows:
<Page x:Class="MyApp.Pages.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
.....
DataContext="{Binding Page1VM, Source={StaticResource Locator}}">
<Page.InputBindings>
<KeyBinding
Key="Enter"
Command="{Binding Btn_ConfirmCommand}" />
</Page.InputBindings>
<Grid>
<Grid >
<TextBox Text="{Binding SelectedID}" />
<Button Command="{Binding Btn_ConfirmCommand}"/>
</Grid>
</Grid>
Inside ViewModel:
public Page1VM()
{
Btn_ConfirmCommand = new RelayCommand(Btn_ConfirmMethod);
}
...
void Btn_ConfirmMethod()
{
MessageBox.Show(SelectedID);
}
public string SelectedID
{
get{return selectedID;}
set
{
Set(() => SelectedID, ref selectedID, value);
RaisePropertyChanged("SelectedID");
}
}
The problem: When I write some content inside the textbox and click the button the messagebox prints the content, but if I press enter key is prints an empty string
Upvotes: 1
Views: 52
Reputation: 169200
Set the UpdateSourceTrigger
of the Binding
to PropertyChanged
:
<TextBox Text="{Binding SelectedID, UpdateSourceTrigger=PropertyChanged}" />
This should cause the source property to get updated on each key stroke. The default value is LostFocus
.
Upvotes: 3