Reputation: 53
I have buttons that act like a keyboard when pressed on it must fill an entry field that is focused. but it doesn't work, because the button press causes the entry to lose focus. can anyone give me a hint to solve this problem?
private void Button_Clicked(object sender, EventArgs e)
{ Button button = (Button)sender;
string pressed = button.Text;
if (this.FirstDigit.IsFocused)
{
this.FirstDigit.Text += pressed;
}and so on ...
Upvotes: 1
Views: 1345
Reputation: 15816
I find it is hard to keep the entry's focus when a button is clicked.
I write a WorkAroud for you, when the entry is Unfocused
, use a previousEntry
to record this entry:
public partial class MainPage : ContentPage
{
public Entry previousEntry;
public MainPage()
{
InitializeComponent();
first.Unfocused += (object sender, FocusEventArgs e) => {
previousEntry = (Entry)sender;
};
second.Unfocused += (object sender, FocusEventArgs e) => {
previousEntry = (Entry)sender;
};
third.Unfocused += (object sender, FocusEventArgs e) => {
previousEntry = (Entry)sender;
};
}
private void Button_Clicked(object sender, EventArgs e)
{
Button button = (Button)sender;
string pressed = button.Text;
if (previousEntry != null)
{
previousEntry.Text += pressed;
}
}
}
And in Xaml:
<StackLayout>
<!-- Place new controls here -->
<Button Text="click me" Clicked="Button_Clicked" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
<Entry x:Name="first" Text="1+" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
<Entry x:Name="second" Text="2+" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
<Entry x:Name="third" Text="3+" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
</StackLayout>
Let me know if it works.
Upvotes: 1