我正在使用附加属性将文本框和文本块的输入限制为数字或字母。现在我想将此附加属性应用于 datagridtextcolumn。我尝试了以下方法:
<DataGridTextColumn Header="Max" Width="50"
Binding="{Binding Path=Max, Mode=TwoWay"
Helper:InputService.NumericOnly="True">
和这样的:
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="Helper:InputService.NumericOnly" Value="True"/>
</Style>
</DataGridTextColumn.ElementStyle>
但它不起作用。我该怎么做?
我的 InputService 包含 NumericOnly 属性:
public static readonly DependencyProperty NumericOnlyProperty = DependencyProperty.RegisterAttached(
"NumericOnly",
typeof(bool),
typeof(InputService),
new UIPropertyMetadata(false, OnNumericOnlyChanged));
public static bool GetNumericOnly(DependencyObject d)
{
return (bool)d.GetValue(NumericOnlyProperty);
}
public static void SetNumericOnly(DependencyObject d, bool value)
{
d.SetValue(NumericOnlyProperty, value);
}
private static void OnNumericOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool isNumericOnly = (bool)e.NewValue;
if (d is TextBox)
{
var textBox = (TextBox)d;
if (isNumericOnly)
{
textBox.PreviewTextInput += BlockNonDigitCharacters;
textBox.PreviewKeyDown += ReviewKeyDown;
}
else
{
textBox.PreviewTextInput -= BlockNonDigitCharacters;
textBox.PreviewKeyDown -= ReviewKeyDown;
}
}
else if (d is TextBlock)
{
var textBlock = (TextBlock)d;
if (isNumericOnly)
{
textBlock.PreviewTextInput += BlockNonDigitCharacters;
textBlock.PreviewKeyDown += ReviewKeyDown;
}
else
{
textBlock.PreviewTextInput -= BlockNonDigitCharacters;
textBlock.PreviewKeyDown -= ReviewKeyDown;
}
}
}
private static void BlockNonDigitCharacters(object sender, TextCompositionEventArgs e)
{
foreach (char ch in e.Text)
{
if (Char.IsDigit(ch))
{
e.Handled = true;
}
}
}