我想为TextBox编写附加属性或行为,以便当焦点输入语言根据set属性自动更改时
任何人都可以为我提供示例代码来实现这一目标吗?
这是我到目前为止的代码,但是我想基于textBox焦点设置和取消设置语言,所以当TextBox焦点丢失时我想切换到在此类之前选择的inputlanguage这个类改变了它
public static class InputLanguageSwitch
{
#region Dependency properties
/// <summary>
/// language to switch to when input got focus
/// </summary>
public static readonly DependencyProperty KeyboardLanguageProperty = DependencyProperty.Register("KeyboardLanguage", typeof(string), typeof(Localization), new FrameworkPropertyMetadata(null, OnKeyboardLanguageChanged));
#endregion
#region Dependency properties Get/Set methods
/// <summary>
/// Return selected keyboard language
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static string GetKeyboardLanguage(DependencyObject d)
{
return d.GetValue(KeyboardLanguageProperty) as string;
}
/// <summary>
/// Set input language base on keyboard
/// </summary>
/// <param name="d"></param>
/// <param name="value"></param>
public static void SetKeyboardLanguage(DependencyObject d, string value)
{
d.SetValue(KeyboardLanguageProperty, value);
}
#endregion
#region Even processing
/// <summary>
/// action to perform when input language changes
/// </summary>
/// <param name="d">Dependency object</param>
/// <param name="e">DependencyPropertyChangedEventArgs</param>
public static void OnKeyboardLanguageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is TextBoxBase)) return;
var textBox = d as TextBoxBase;
var language = FindKeyboardLanguage((string) e.NewValue);
if (string.IsNullOrEmpty((string) e.NewValue) | ReferenceEquals(language, CultureInfo.InvariantCulture))
{
//textBox.PreviewGotKeyboardFocus -= OnTextBoxPreviewGotKeyboardFocus;
d.ClearValue(InputLanguageManager.InputLanguageProperty);
d.ClearValue(InputLanguageManager.RestoreInputLanguageProperty);
}
else
{
//textBox.PreviewGotKeyboardFocus += OnTextBoxPreviewGotKeyboardFocus;
d.SetValue(InputLanguageManager.InputLanguageProperty, language);
d.SetValue(InputLanguageManager.RestoreInputLanguageProperty, true);
InputLanguageManager.Current.CurrentInputLanguage = language;
}
}
#endregion
/// <summary>
/// Find and return keyboard language if one specified as an argument
/// is installed on machine
/// </summary>
/// <param name="tag">language tag</param>
/// <returns><see cref="CultureInfo"/> for requested language></returns>
public static CultureInfo FindKeyboardLanguage(string tag)
{
CultureInfo result = CultureInfo.InvariantCulture;
if (!string.IsNullOrEmpty(tag))
{
if (InputLanguageManager.Current.AvailableInputLanguages != null)
foreach (CultureInfo c in InputLanguageManager.Current.AvailableInputLanguages)
{
if (c.IetfLanguageTag.ToUpper().StartsWith(tag.ToUpper()))
{
result = c;
}
if (c.IetfLanguageTag.ToUpper() == tag.ToUpper())
{
break; // TODO: might not be correct. Was : Exit For
}
}
}
return result;
}
}