Я создаю страницу входа для устройства киоска, используя WPF. На странице есть 3 текстовых поля и клавиатура (созданные с помощью кнопок). Для выполнения действия, когда мы нажимаем кнопку на клавиатуре, хотим отобразить текст в соответствующем текстовом поле.
Необходимость: как найти текущее фокусированное текстовое поле.
код с использованием:
void buttonElement_Click(object sender, RoutedEventArgs e)
{
// create variable for holding string
String sendString = "";
try
{
// stop all event handling
e.Handled = true;
Button btn = ((Button)sender);
// set sendstring to key
if (btn.Content.ToString().Length == 1 && btn.CommandParameter.ToString() != btn.Content.ToString())
{
sendString = btn.Content.ToString();
}
else
{
sendString = btn.CommandParameter.ToString();
}
// sendString = ((Button)sender).CommandParameter.ToString();
int position = txtAuto.SelectionStart;
// if something to send
if (!String.IsNullOrEmpty(sendString))
{
// if sending a string
if (sendString.Length > 1)
{
switch (sendString)
{
case "Del":
if (position != txtAuto.Text.Length)
{
txtAuto.Text = txtAuto.Text.Remove(position, 1);
txtAuto.SelectionStart = position;
}
break;
case "BACKSPACE":
if (position != 0)
{
txtAuto.Text = txtAuto.Text.Remove(position - 1, 1);
txtAuto.SelectionStart = position;
}
break;
case "Clear":
txtAuto.Text = string.Empty;
break;
case "ENTER":
popup.IsOpen = false;
// lbSuggestion.ItemsSource = null;
this.FetchSearchResult(txtAuto.Text.Trim());
if (lbResult.Items.Count != 0)
{
lbResult.ScrollIntoView(lbResult.Items[0]);
}
break;
}
}
else
{
txtAuto.Text = txtAuto.Text.Insert(txtAuto.SelectionStart, sendString);
txtAuto.SelectionStart = position + 1;
}
// set keyboard focus
System.Windows.Input.Keyboard.Focus(this.txtAuto);
// set normal focus
this.txtAuto.Focus();
}
}
catch (Exception)
{
// do nothing - not important for now
Console.WriteLine("Could not send key press: {0}", sendString);
}
}
Этот код хорошо работает для одного текстового поля, как заставить его работать для других текстовых полей.