WPF:修剪所有文本框 [英] WPF: Trim all textboxes
问题描述
我最近要求我的应用程序中的所有文本框在离开文本框时都应自动修剪文本.我不能/不想通过将转换器或事件添加到每个文本框,或者通过在我的视图模型中为每个绑定编写/重写属性来做到这一点.首先,它会非常混乱和重复,其次,我已经有许多文本框的转换器,而且afaik,如果不编写多转换器就无法连接多个转换器.
I recently got a requirement that all the textboxes in my application should automatically trim the text when leaving the textbox. I can't/don't want to do this by adding converters or events to every single textbox, or by writing/rewriting the properties in my viewmodel for every single binding. First, it will be very messy and repetetive, second, I already have converters for many of my textboxes, and afaik, you can't connect multiple converters without writing a multiconverter.
由于您不能在每次击键时应用修剪,修剪必须发生在 unfocus 事件之后但在绑定到我的视图模型之前.
Since you can't apply the trim at every key stroke, the trim must occur after the unfocus event but before the binding operation to my viewmodel.
这样做的最佳方法是什么?编写我自己的文本框类?某种控制模板/触发器?我对这些选项不够熟悉,无法知道哪条路径最简单.
What is the best way of doing this? Writing my own textbox class? Some kind of controltemplate/triggers? I'm not familiar enough with those options to know which path will be easiest.
我已经在 App.xaml 中为我的所有文本框设置了一个样式,当 IsReadOnly 设置为 true 时,这使它们看起来像 IsEnabled=false,因此这可能会使事情复杂化.
I already have a style set up in App.xaml for all my textboxes which makes them look like IsEnabled=false when IsReadOnly is set to true, so that might complicate things.
推荐答案
MVVM 方式将使用 Behaviors:
using System.Windows.Controls;
using System.Windows.Interactivity;
public class TrimTextBoxBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.LostFocus += AssociatedObject_LostFocus;
}
private void AssociatedObject_LostFocus(object sender, System.Windows.RoutedEventArgs e)
{
AssociatedObject.Text = AssociatedObject.Text.Trim();
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.LostFocus -= AssociatedObject_LostFocus;
}
}
然后在您的 XAML 中:
Then in your XAML:
<UserControl ...
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:Your.Namespace;assembly=Your.Assembly">
<TextBox>
<i:Interaction.Behaviors>
<local:TrimTextBoxBehavior />
</i:Interaction.Behaviors>
</TextBox>
注意您需要替换local
XML 命名空间声明中的Your.Namespace
和Your.Assembly
.此外,您需要将 System.Windows.Interactivy 添加到您的项目.
Notice that you need to replaceYour.Namespace
and Your.Assembly
in the local
XML namespace declaration. Also, you need to add System.Windows.Interactivy to your project.
这篇关于WPF:修剪所有文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!