添付のプロパティを使用して、テキストボックスとテキストブロックへの入力を数値またはアルファベットに制限しています。次に、この添付プロパティを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;
}
}
}