Selecting text and caret in a texbox on focus - wpf

public class TextBoxSelectionBehavior : Behavior<TextBox>
{
public static bool GetSelectAllTextOnFocus(TextBox textBox)
{
return (bool)textBox.GetValue(SelectAllTextOnFocusProperty);
}
public static void SetSelectAllTextOnFocus(TextBox textBox, bool value)
{
textBox.SetValue(SelectAllTextOnFocusProperty, value);
}
public static readonly DependencyProperty SelectAllTextOnFocusProperty =
DependencyProperty.RegisterAttached(
"SelectAllTextOnFocus",
typeof(bool),
typeof(TextBoxSelectionBehavior),
new UIPropertyMetadata(false, OnSelectAllTextOnFocusChanged));
private static void OnSelectAllTextOnFocusChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBox;
if (textBox == null) return;
if (e.NewValue is bool == false) return;
if ((bool)e.NewValue)
{
textBox.GotFocus += SelectAll;
textBox.PreviewMouseDown += IgnoreMouseButton;
}
else
{
textBox.GotFocus -= SelectAll;
textBox.PreviewMouseDown -= IgnoreMouseButton;
}
}
private static void SelectAll(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox == null) return;
textBox.SelectAll();
textBox.CaretIndex = textBox.Text.Length;
}
private static void IgnoreMouseButton(object sender,
System.Windows.Input.MouseButtonEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null || textBox.IsKeyboardFocusWithin) return;
textBox.Focus();
e.Handled = true;
}
The textbox in question is an editable cell.
Once the cell is double clicked, i want a selectall of the text as well as a caret blink at the end of the text, on getfocus.
The text is highlighted correctly.
But setting the caret at the end is deselecting the highlighted text.
i cant do both at once. how to accomplish this?
I have tried selection start,length and other approaches.nothing works.

Related

ScrollViewer inside ScrollViewer WPF

In my WPF page I need to scroll vertically and inside (this ScrollViewer) I need several horizontal scrolls. At the beginning i had the problem was that when I pointed with my mouse on the inside ScrollViewer area I cant scroll the page (vertically).I found a post:
https://serialseb.com/blog/2007/09/03/wpf-tips-6-preventing-scrollviewer-from/
it resolved my mouse problem, but now I have the same problem on Touch display. I can't use my finger to vertically scroll on the inside scrollviewer. Anyone has any idea to change the below code to let it work for touch display? Thanks
public class ScrollViewerCorrector
{
public static bool GetFixScrolling(DependencyObject obj)
{
return (bool)obj.GetValue(FixScrollingProperty);
}
public static void SetFixScrolling(DependencyObject obj, bool value)
{
obj.SetValue(FixScrollingProperty, value);
}
public static readonly DependencyProperty FixScrollingProperty =
DependencyProperty.RegisterAttached("FixScrolling", typeof(bool), typeof(ScrollViewerCorrector), new FrameworkPropertyMetadata(false, ScrollViewerCorrector.OnFixScrollingPropertyChanged));
public static void OnFixScrollingPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
{
ScrollViewer viewer = sender as ScrollViewer;
if (viewer == null)
throw new ArgumentException("The dependency property can only be attached to a ScrollViewer", "sender");
if ((bool)e.NewValue == true)
viewer.PreviewMouseWheel += HandlePreviewMouseWheel;
else if ((bool)e.NewValue == false)
viewer.PreviewMouseWheel -= HandlePreviewMouseWheel;
}
private static List<MouseWheelEventArgs> _reentrantList = new List<MouseWheelEventArgs>();
private static void HandlePreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
var scrollControl = sender as ScrollViewer;
if (!e.Handled && sender != null && !_reentrantList.Contains(e))
{
var previewEventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
{
RoutedEvent = UIElement.PreviewMouseWheelEvent,
Source = sender
};
var originalSource = e.OriginalSource as UIElement;
_reentrantList.Add(previewEventArg);
originalSource.RaiseEvent(previewEventArg);
_reentrantList.Remove(previewEventArg);
// at this point if no one else handled the event in our children, we do our job
if (!previewEventArg.Handled && ((e.Delta > 0 && scrollControl.VerticalOffset == 0)
|| (e.Delta <= 0 && scrollControl.VerticalOffset >= scrollControl.ExtentHeight - scrollControl.ViewportHeight)))
{
e.Handled = true;
var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
eventArg.RoutedEvent = UIElement.MouseWheelEvent;
eventArg.Source = sender;
var parent = (UIElement)((FrameworkElement)sender).Parent;
parent.RaiseEvent(eventArg);
}
}
}
}

Creating a functional Double Control

I have a custom control called DoubleNumericBox that validates and accepts user input like 23,00, 0,9, 23.900,01, 34... etc.
The problem starts when I try to binding something to it. The binding is not reliable enough, some times the control won't display the new value, but if I set the DataContext one more time it will set the value, etc.
So, I must be doing something very wrong with my custom properties and events.
Custom Properties/Events
Value : Double
MinValue : Double
MaxValue : Double
ValueChanged : Event
Expected Behaviour
Validate typed keys: Numbers, Commas and Points (Decimal separator and digit grouping glyph). My culture uses Comma as decimal separator.
Validate the whole text if (return to the latest Value if number not valid):
Text pasted.
Lost Focus.
Validate Min/Max limit.
Accept binding from Text or Value, and validate the binding value.
Code
public class DoubleNumericBox : TextBox
{
Variables:
public readonly static DependencyProperty MinValueProperty;
public readonly static DependencyProperty ValueProperty;
public readonly static DependencyProperty MaxValueProperty;
Properties:
public double MinValue
{
get { return (double)GetValue(MinValueProperty); }
set { SetCurrentValue(MinValueProperty, value); }
}
public double Value
{
get { return (double)GetValue(ValueProperty); }
set
{
SetCurrentValue(ValueProperty, value);
RaiseValueChangedEvent();
}
}
public double MaxValue
{
get { return (double)GetValue(MaxValueProperty); }
set { SetCurrentValue(MaxValueProperty, value); }
}
Event:
public static readonly RoutedEvent ValueChangedEvent;
public event RoutedEventHandler ValueChanged
{
//Provide CLR accessors for the event
add { AddHandler(ValueChangedEvent, value); }
remove { RemoveHandler(ValueChangedEvent, value); }
}
public void RaiseValueChangedEvent()
{
var newEventArgs = new RoutedEventArgs(ValueChangedEvent);
RaiseEvent(newEventArgs);
}
Constructor/Override:
static DoubleNumericBox()
{
MinValueProperty = DependencyProperty.Register("MinValue", typeof(double), typeof(DoubleNumericBox), new FrameworkPropertyMetadata(0D));
ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(DoubleNumericBox), new FrameworkPropertyMetadata(0D, ValueCallback));
MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(double), typeof(DoubleNumericBox), new FrameworkPropertyMetadata(Double.MaxValue));
ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(DoubleNumericBox));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
PreviewTextInput += DoubleNumericBox_PreviewTextInput;
ValueChanged += DoubleNumericBox_ValueChanged;
TextChanged += DoubleNumericBox_TextChanged;
LostFocus += DoubleNumericBox_LostFocus;
AddHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler(PastingEvent));
}
Events:
private static void ValueCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as DoubleNumericBox;
if (textBox == null) return;
//textBox.Text = String.Format("{0:###,###,##0.0###}", textBox.Value);
textBox.RaiseValueChangedEvent();
}
private void DoubleNumericBox_ValueChanged(object sender, RoutedEventArgs e)
{
var textBox = sender as DoubleNumericBox;
if (textBox == null) return;
ValueChanged -= DoubleNumericBox_ValueChanged;
TextChanged -= DoubleNumericBox_TextChanged;
if (Value > MaxValue)
Value = MaxValue;
else if (Value < MinValue)
Value = MinValue;
textBox.Text = Text = String.Format("{0:###,###,##0.0###}", Value);
ValueChanged += DoubleNumericBox_ValueChanged;
TextChanged += DoubleNumericBox_TextChanged;
}
private void DoubleNumericBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
if (String.IsNullOrEmpty(textBox.Text)) return;
if (IsTextDisallowed(textBox.Text)) return;
ValueChanged -= DoubleNumericBox_ValueChanged;
var newValue = Convert.ToDouble(textBox.Text);
if (newValue > MaxValue)
Value = MaxValue;
else if (newValue < MinValue)
Value = MinValue;
else
{
Value = newValue;
}
ValueChanged += DoubleNumericBox_ValueChanged;
}
private void DoubleNumericBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (String.IsNullOrEmpty(e.Text))
{
e.Handled = true;
return;
}
//Only Numbers, comma and points.
if (IsEntryDisallowed(sender, e.Text))
{
e.Handled = true;
}
}
private void PastingEvent(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
var text = (String)e.DataObject.GetData(typeof(String));
if (IsTextDisallowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
private void DoubleNumericBox_LostFocus(object sender, RoutedEventArgs e)
{
TextChanged -= DoubleNumericBox_TextChanged;
Text = String.Format("{0:###,###,##0.0###}", Value);
TextChanged += DoubleNumericBox_TextChanged;
}
Methods:
private bool IsEntryDisallowed(object sender, string text)
{
var regex = new Regex(#"^[0-9]|\.|\,$");
if (regex.IsMatch(text))
{
return !CheckPontuation(sender, text);
}
//Not a number or a Comma/Point.
return true;
}
private bool IsTextDisallowed(string text)
{
var regex = new Regex(#"^((\d+)|(\d{1,3}(\.\d{3})+)|(\d{1,3}(\.\d{3})(\,\d{3})+))((\,\d{4})|(\,\d{3})|(\,\d{2})|(\,\d{1})|(\,))?$");
return !regex.IsMatch(text); //\d+(?:,\d{1,2})?
}
private bool CheckPontuation(object sender, string next)
{
var textBox = sender as TextBox;
if (textBox == null) return true;
if (Char.IsNumber(next.ToCharArray()[0]))
return true;
if (next.Equals("."))
{
var textAux = textBox.Text;
if (!String.IsNullOrEmpty(textBox.SelectedText))
textAux = textAux.Replace(textBox.SelectedText, "");
//Check if the user can add a point mark here.
var before = textAux.Substring(0, textBox.SelectionStart);
var after = textAux.Substring(textBox.SelectionStart);
//If no text, return true.
if (String.IsNullOrEmpty(before) && String.IsNullOrEmpty(after)) return true;
if (!String.IsNullOrEmpty(before))
{
if (before.Contains(',')) return false;
if (after.Contains("."))
{
var split = before.Split('.');
if (split.Last().Length != 3) return false;
}
}
if (!String.IsNullOrEmpty(after))
{
var split = after.Split('.', ',');
if (split.First().Length != 3) return false;
}
return true;
}
//Only one comma.
if (next.Equals(","))
{
return !textBox.Text.Any(x => x.Equals(','));
}
return true;
}
}
Can you guys help me out to make this custom control work better?
So a couple of gotchas I see in your code:
Do not use += / -= to hook up events in WPF controls, it can and will break routed events, use Addhandler / RemoveHandler instead.
I removed the unhooking and rehooking of events and used a member level flag instead for change loop issues. Here is the code I came up with, seem to bind fine to Value field.
A side note, you failed to account for multiple "." entry in your textbox so a user could type 345.34.434.23 which would not be prevented. I know to check this because I wrote a WPF FilterTextBox years ago and this came up in my testing.
public class DoubleNumericBox : TextBox
{
public readonly static DependencyProperty MinValueProperty;
public readonly static DependencyProperty ValueProperty;
public readonly static DependencyProperty MaxValueProperty;
public bool _bIgnoreChange = false;
public double MinValue
{
get { return (double)GetValue(MinValueProperty); }
set { SetCurrentValue(MinValueProperty, value); }
}
public double Value
{
get { return (double)GetValue(ValueProperty); }
set
{
SetCurrentValue(ValueProperty, value);
RaiseValueChangedEvent();
}
}
public double MaxValue
{
get { return (double)GetValue(MaxValueProperty); }
set { SetCurrentValue(MaxValueProperty, value); }
}
public static readonly RoutedEvent ValueChangedEvent;
public event RoutedEventHandler ValueChanged
{
//Provide CLR accessors for the event
add { AddHandler(ValueChangedEvent, value); }
remove { RemoveHandler(ValueChangedEvent, value); }
}
public void RaiseValueChangedEvent()
{
var newEventArgs = new RoutedEventArgs(ValueChangedEvent);
RaiseEvent(newEventArgs);
}
static DoubleNumericBox()
{
MinValueProperty = DependencyProperty.Register("MinValue", typeof(double), typeof(DoubleNumericBox), new FrameworkPropertyMetadata(0D));
ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(DoubleNumericBox), new FrameworkPropertyMetadata(0D, ValueCallback));
MaxValueProperty = DependencyProperty.Register("MaxValue", typeof(double), typeof(DoubleNumericBox), new FrameworkPropertyMetadata(Double.MaxValue));
ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(DoubleNumericBox));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
AddHandler(TextBox.PreviewTextInputEvent, new TextCompositionEventHandler(DoubleNumericBox_PreviewTextInput));
AddHandler(TextBox.TextChangedEvent, new TextChangedEventHandler(DoubleNumericBox_TextChanged));
AddHandler(TextBox.LostFocusEvent, new RoutedEventHandler(DoubleNumericBox_LostFocus));
AddHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler(PastingEvent));
}
private static void ValueCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as DoubleNumericBox;
if (textBox == null) return;
//textBox.Text = String.Format("{0:###,###,##0.0###}", textBox.Value);
textBox.DoubleNumericBox_ValueChanged();
}
private void DoubleNumericBox_ValueChanged()
{
if (Value > MaxValue)
Value = MaxValue;
else if (Value < MinValue)
Value = MinValue;
if (!_bIgnoreChange)
this.Text = Text = String.Format("{0:###,###,##0.0###}", Value);
}
private void DoubleNumericBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) return;
if (String.IsNullOrEmpty(textBox.Text)) return;
if (IsTextDisallowed(textBox.Text)) return;
//ValueChanged -= DoubleNumericBox_ValueChanged;
_bIgnoreChange = true;
Value = Convert.ToDouble(textBox.Text);
//if (newValue > MaxValue)
// Value = MaxValue;
//else if (newValue < MinValue)
// Value = MinValue;
//else
//{
// Value = newValue;
//}
_bIgnoreChange = false;
//ValueChanged += DoubleNumericBox_ValueChanged;
}
private void DoubleNumericBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (String.IsNullOrEmpty(e.Text))
{
e.Handled = true;
return;
}
//Only Numbers, comma and points.
if (IsEntryDisallowed(sender, e.Text))
{
e.Handled = true;
}
}
private void PastingEvent(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
var text = (String)e.DataObject.GetData(typeof(String));
if (IsTextDisallowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
private void DoubleNumericBox_LostFocus(object sender, RoutedEventArgs e)
{
//TextChanged -= DoubleNumericBox_TextChanged;
Text = String.Format("{0:###,###,##0.0###}", Value);
//TextChanged += DoubleNumericBox_TextChanged;
}
private bool IsEntryDisallowed(object sender, string text)
{
var regex = new Regex(#"^[0-9]|\.|\,$");
if (regex.IsMatch(text))
{
return !CheckPontuation(sender, text);
}
//Not a number or a Comma/Point.
return true;
}
private bool IsTextDisallowed(string text)
{
var regex = new Regex(#"^((\d+)|(\d{1,3}(\.\d{3})+)|(\d{1,3}(\.\d{3})(\,\d{3})+))((\,\d{4})|(\,\d{3})|(\,\d{2})|(\,\d{1})|(\,))?$");
return !regex.IsMatch(text); //\d+(?:,\d{1,2})?
}
private bool CheckPontuation(object sender, string next)
{
var textBox = sender as TextBox;
if (textBox == null) return true;
if (Char.IsNumber(next.ToCharArray()[0]))
return true;
if (next.Equals("."))
{
var textAux = textBox.Text;
if (!String.IsNullOrEmpty(textBox.SelectedText))
textAux = textAux.Replace(textBox.SelectedText, "");
//Check if the user can add a point mark here.
var before = textAux.Substring(0, textBox.SelectionStart);
var after = textAux.Substring(textBox.SelectionStart);
//If no text, return true.
if (String.IsNullOrEmpty(before) && String.IsNullOrEmpty(after)) return true;
if (!String.IsNullOrEmpty(before))
{
if (before.Contains(',')) return false;
if (after.Contains("."))
{
var split = before.Split('.');
if (split.Last().Length != 3) return false;
}
}
if (!String.IsNullOrEmpty(after))
{
var split = after.Split('.', ',');
if (split.First().Length != 3) return false;
}
return true;
}
//Only one comma.
if (next.Equals(","))
{
return !textBox.Text.Any(x => x.Equals(','));
}
return true;
}
}

Wpf Textbox Spellcheck issue with Custom Dictionary

I have got spell checking issues with the custom dictionary in a Wpf application in that it does not recognize I∆n.
If I add a behavior to try and deal with I∆n, DoSpellCheck() works when you type or paste text into the Textbox but does not work when textBox_Loaded(object sender, RoutedEventArgs e) is called.
Any help would appreciated.
public class TextBoxExtendedSpellCheckBehavior : Behavior
{
private static Key[] _nonInputKeys = new Key[] { Key.Left, Key.Up, Key.Right, Key.Down, Key.Tab, Key.Delete, Key.Back, Key.Escape, Key.Enter };
protected override void OnAttached()
{
if (AssociatedObject is TextBox)
{
TextBox textBox = AssociatedObject as TextBox;
textBox.PreviewKeyUp += OnTextBox_PreviewKeyUp;
textBox.LostFocus += OnTextBox_LostFocus;
textBox.TextChanged += OnTextChanged;
textBox.Loaded += textBox_Loaded;
}
base.OnAttached();
}
void textBox_Loaded(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
DoSpellCheck(textBox);
}
}
protected override void OnDetaching()
{
if (AssociatedObject is TextBox)
{
TextBox textBox = AssociatedObject as TextBox;
textBox.PreviewKeyUp -= OnTextBox_PreviewKeyUp;
textBox.LostFocus -= OnTextBox_LostFocus;
textBox.Loaded -= textBox_Loaded;
}
base.OnDetaching();
}
private static void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (sender is TextBox)
{
TextBox textBox = sender as TextBox;
if (textBox != null && textBox.IsLoaded == true)
{
DoSpellCheck(textBox);
}
}
}
private bool IsInputKey(Key key)
{
return !_nonInputKeys.Contains(key);
}
private void OnTextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (sender is TextBox && IsInputKey(e.Key))
{
TextBox textBox = sender as TextBox;
DoSpellCheck(textBox);
}
}
private void OnTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
{
TextBox textBox = sender as TextBox;
DoSpellCheck(textBox);
}
}
public static void DoSpellCheck(TextBox textBox)
{
const string iDelta = "I∆n";
int index = textBox.Text.IndexOf(iDelta);
if (index > 0)
{
int iStart = textBox.GetSpellingErrorStart(index);
if (iStart > -1)
{
SpellingError spellingError = textBox.GetSpellingError(iStart);
if (spellingError != null)
{
spellingError.IgnoreAll();
}
}
}
}
}

ObservableCollection as DependencyProperty - how to add / remove items in CollectionChanged event?

I have the following code:
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.RegisterAttached("ItemsSource", typeof (ObservableCollection<BaseViewModel>),
typeof (MultiSelectComboBoxUserControl),
new FrameworkPropertyMetadata(null, OnItemsSourceChanged));
public static ObservableCollection<BaseViewModel> GetItemsSource(DependencyObject obj)
{
return (ObservableCollection<BaseViewModel>) obj.GetValue(ItemsSourceProperty);
}
public static void SetItemsSource(DependencyObject obj, ObservableCollection<BaseViewModel> value)
{
obj.SetValue(ItemsSourceProperty, value);
}
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue != null)
{
var coll = (INotifyCollectionChanged) e.OldValue;
coll.CollectionChanged -= ItemsSource_CollectionChanged;
}
if (e.NewValue != null)
{
var coll = (ObservableCollection<BaseViewModel>) e.NewValue;
coll.CollectionChanged += ItemsSource_CollectionChanged;
}
}
private static void ItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Here I'd like to update my ObservableCollection - ItemsSource
}
How can I achieve this (updating ItemsSource)? I can't access it because it's a dependency property and event handler is a static method. Any tips very welcome.
The object that you receive as the sender parameter is the ObservableCollection. If you plan on changing the collection (such as adding or removing items) you may also need to detach the event handler before making changes.
private static void ItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
ObservableCollection collection = sender as ObservableCollection<BaseViewModel>;
if (collection != null)
{
collection.CollectionChanged -= ItemsSource_CollectionChanged;
//Update ObservableCollection
collection.CollectionChanged += ItemsSource_CollectionChanged;
}
}
I wouldn't change my ItemsSource instance at all. I would simply create my ObservableCollection instance and clear, add items when updating.
Ok, it simple!
Old code:
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgse)
{
if (e.OldValue != null)
{
var coll = (INotifyCollectionChanged) e.OldValue;
coll.CollectionChanged -= ItemsSource_CollectionChanged;
}
if (e.NewValue != null)
{
var coll = (ObservableCollection<BaseViewModel>) e.NewValue;
coll.CollectionChanged += ItemsSource_CollectionChanged;
}
}
New Code:
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgse)
{
(YouCustomControl) control = (YouCustomControl)d;
if (e.OldValue != null)
{
var coll = (INotifyCollectionChanged) e.OldValue;
coll.CollectionChanged -= control.ItemsSource_CollectionChanged;
}
if (e.NewValue != null)
{
var coll = (ObservableCollection<BaseViewModel>) e.NewValue;
coll.CollectionChanged += control.ItemsSource_CollectionChanged;
}
}
private void ItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
}

TextBox AttachedProperty to Select All text not working as expected?

I have an attached property called "SelectAllOnFocus". Values of true/false.
public static class TextBoxProps
{
private static void MyTextBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
((TextBox)sender).Text = string.Empty;
}
}
public static void SetSelectAllOnFocus(DependencyObject dependencyObject, bool selectAllOnFocus)
{
if (!ReferenceEquals(null, dependencyObject))
{
dependencyObject.SetValue(SelectAllOnFocus, selectAllOnFocus);
}
}
public static bool GetSelectAllOnFocus(DependencyObject dependencyObject)
{
if (!ReferenceEquals(null, dependencyObject))
{
return (bool)dependencyObject.GetValue(SelectAllOnFocus);
}
else
{
return false;
}
}
private static void OnSelectAllOnFocus(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool selectAllOnFocus = (bool)e.NewValue == true;
var theTextBox = d as TextBox;
if (selectAllOnFocus && theTextBox != null)
{
theTextBox.PreviewMouseDown -= MyTextBoxMouseEnter; theTextBox.PreviewMouseDown += MyTextBoxMouseEnter;
}
}
private static void MyTextBoxMouseEnter(object sender, MouseEventArgs e)
{
((TextBox)sender).SelectAll();
e.Handled = false;
}
public static readonly DependencyProperty SelectAllOnFocus
= DependencyProperty.RegisterAttached("SelectAllOnFocus", typeof(bool), typeof(TextBoxEscapeProperty),
new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnSelectAllOnFocus)));
}
What happens is the following:
The PreviewMouseDown event gets triggered.
The MyTextBoxMouseEnter method gets called.
The SelectAll() Method gets called.
When I do a "watch" on ((TextBox)sender).SelectedText, the value is correct (meaning whatever is in the textbox is showing up as selectedText).
The textbox itself is unchanged. No text is selected.
This is part of a general WPF style. All textboxes in the application should receive this property and it's associated behavior.
I'm stumped. Any ideas?
Thanks
What happens if you call ((TextBox)sender).UpdateLayout(); immediately after the SelectAll command? Or maybe you need to set the Keyboard focus to the text box.
It might be a better option to use something like this, which works if the text box is being selected with the mouse or the keyboard. (You'll need to modify it to check your "SelectAllOnFocus" property)
In your App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
// Select the text in a TextBox when it receives focus.
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(SelectivelyIgnoreMouseButton));
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText));
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent, new RoutedEventHandler(SelectAllText));
base.OnStartup(e);
}
void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
{
// Find the TextBox
DependencyObject parent = e.OriginalSource as UIElement;
while (parent != null && !(parent is TextBox))
parent = VisualTreeHelper.GetParent(parent);
if (parent != null)
{
var textBox = (TextBox)parent;
if (!textBox.IsKeyboardFocusWithin)
{
// If the text box is not yet focused, give it the focus and
// stop further processing of this click event.
textBox.Focus();
e.Handled = true;
}
}
}
void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}

Resources