我在不同的控件中有多个文本框,它们的PreviewTextInput中需要相同的逻辑。目前,我刚刚将我的自定义PreviewTextInput函数复制到每个控件后面的代码中。
我希望避免复制代码,只需将函数放在一个单一的位置,并将所有不同的文本框绑定到该位置。所以我想我可以使用静态资源,但我不知道我将如何继续这样做。
The *PreviewTextInput* function i would like to access globally:
public void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^-0-9.,]+");
e.Handled = regex.IsMatch(e.Text);
}
我找到了一个我不喜欢的解决方案,因为它需要设置文本框的整个模板。通过在Generic.xml的代码隐藏中添加上面的函数,然后在其xaml文件中:
<ControlTemplate x:Key="NumberValidationTextBox">
<TextBox PreviewTextInput="NumberValidationTextBox"/>
</ControlTemplate>
然后通过设置Template="{StaticResource NumberValidationTextBox}“来绑定。然而,这将取代模板。我只想设置PreviewTextInput。是否有可能为这个偶数函数创建一个静态资源?
编辑:我找到了第二个解决方案,但我仍然不满意:
用可以全局访问的规则定义正则表达式(我做了Generic.cs.xml):
public static Regex numberRegex = new Regex("[^-0-9.,]+");
然后,在每个需要其文本框正则表达式的控件的代码隐藏内部:
public void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
e.Handled = Generic.numberRegex.IsMatch(e.Text);
}
但是,这仍然需要我在每个控件的代码隐藏中添加一个函数。我希望能够通过使用静态资源直接将Generic.cs.xml (最顶层的函数)绑定到控件中来坚持XAML。
我想知道这是否可能,或者我是否应该勉强解决解决方案2。
发布于 2022-09-30 13:59:38
StaticResource
?不是的。但是您可以创建一个附加属性来设置正则表达式:
public static class TextBoxExtensions
{
public static readonly DependencyProperty RegularExpressionProperty =
DependencyProperty.RegisterAttached("RegularExpression",
typeof(string),
typeof(TextBoxExtensions),
new FrameworkPropertyMetadata(OnSet));
public static string GetRegularExpression(TextBox target) =>
(string)target.GetValue(RegularExpressionProperty);
public static void SetRegularExpression(TextBox target, string value) =>
target.SetValue(RegularExpressionProperty, value);
private static void OnSet(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox textBox = (TextBox)d;
textBox.PreviewTextInput += OnPreviewTextInput;
}
private static void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
string regularExpression = GetRegularExpression((TextBox)sender);
if (!string.IsNullOrEmpty(regularExpression))
{
Regex regex = new Regex(regularExpression);
e.Handled = regex.IsMatch(e.Text);
}
}
}
使用:
<TextBox local:TextBoxExtensions.RegularExpression="[^-0-9.,]+"/>
这允许您为每个TextBox
指定一个不同的正则表达式。
https://stackoverflow.com/questions/73905980
复制相似问题