Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
CharInputBehavior.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System.Globalization;
4 using System.Linq;
5 using System.Windows.Controls;
6 using System.Windows.Data;
7 
8 namespace SiliconStudio.Presentation.Behaviors
9 {
10  /// <summary>
11  /// This behavior allows more convenient editing of the value of a char using a TextBox.
12  /// </summary>
13  public class CharInputBehavior : DeferredBehaviorBase<TextBox>
14  {
15  private bool updatingText;
16 
17  protected override void OnAttachedOverride()
18  {
19  AssociatedObject.TextChanged += TextChanged;
20  }
21 
22  protected override void OnDetachingOverride()
23  {
24  AssociatedObject.TextChanged -= TextChanged;
25  }
26 
27  private void TextChanged(object sender, TextChangedEventArgs e)
28  {
29  if (updatingText)
30  return;
31 
32  char newChar = default(char);
33  foreach (var change in e.Changes.Where(change => change.AddedLength > 0))
34  {
35  newChar = AssociatedObject.Text[change.Offset + change.AddedLength - 1];
36  }
37  if (newChar != default(char))
38  {
39  updatingText = true;
40  AssociatedObject.Text = newChar.ToString(CultureInfo.InvariantCulture);
41  updatingText = false;
42  }
43 
44  // Update the binding source on each change
45  BindingExpression expression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
46  if (expression != null)
47  expression.UpdateSource();
48  }
49  }
50 }
This behavior allows more convenient editing of the value of a char using a TextBox.