Вам необходимо ValueConverter
или прикрепленное поведение, которое вы применяете через Style
ко всем TextBox
элементам управления.Третьим вариантом будет расширение TextBox
и переопределение TextBoxBase.OnTextChanged(TextChangedEventArgs)
.
TextTrimBehavior
:
public class TextTrimBehavior : DependencyObject
{
#region IsEnabled attached property
public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached(
"IsEnabled", typeof(bool), typeof(TextTrimBehavior), new PropertyMetadata(false, TextTrimBehavior.OnAttached));
public static void SetIsEnabled(DependencyObject attachingElement, bool value)
{
attachingElement.SetValue(TextTrimBehavior.IsEnabledProperty, value);
}
public static bool GetIsEnabled(DependencyObject attachingElement)
{
return (bool) attachingElement.GetValue(TextTrimBehavior.IsEnabledProperty);
}
#endregion
private static void OnAttached(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is TextBox attachedTextBox))
{
return;
}
if ((bool) e.NewValue)
{
attachedTextBox.LostFocus += TextTrimBehavior.TrimText;
}
else
{
attachedTextBox.LostFocus -= TextTrimBehavior.TrimText;
}
}
private static void TrimText(object sender, RoutedEventArgs e)
{
if (sender is TextBox textBox)
{
textBox.Text = textBox.Text.Trim();
}
}
}
TextBox
Стиль:
<Style TargetType="TextBox">
<Setter Property="behaviors:TextTrimBehavior.IsEnabled"
Value="True" />
</Style>
Поскольку ключ Style
не имеет ключа, он будет применяться неявно ко всем элементам управления TextBox
в области действия.Чтобы сделать стиль глобальным, вы должны поместить его в App.xaml ResourceDictionary
.
Расширение неявного стиля с помощью Style.BasedOn
:
<Style x:Key="ExplicitStyle" TargetType="TextBox"
BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Background"
Value="YellowGreen" />
</Style>