Attached Properties in DataGrid
-
24-06-2021 - |
Question
I am using an attached property to limit the input into textboxes and textblocks to either numeric or alphabetic. Now I would like to apply this attached property to a datagridtextcolumn. I tried the following:
<DataGridTextColumn Header="Max" Width="50"
Binding="{Binding Path=Max, Mode=TwoWay"
Helper:InputService.NumericOnly="True">
and something like this:
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="Helper:InputService.NumericOnly" Value="True"/>
</Style>
</DataGridTextColumn.ElementStyle>
But it does not work. How do I do it right?
My InputService contains the NumericOnly property:
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;
}
}
}
Solution
Ok, this it what works for me:
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="Helper:InputService.NumericOnly" Value="True"/>
</Style>
</DataGridTextColumn.EditingElementStyle>
OTHER TIPS
Your property implementation expects only to be set on a TextBox
or TextBlock
. I would suggest that you put a breakpoint in your code and check what type of control it's actually being set on - I suspect you'll find it's the parent container of your cell, rather than the text control itself.
EDIT: based on your comment, you probably want to include the following in your binding:
Binding="{Binding Path=Max, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
This will cause the binding to refresh every time the property changes, where the default for most input controls is to fire when a control loses focus.