1

我正在使用附加属性将文本框和文本块的输入限制为数字或字母。现在我想将此附加属性应用于 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;
    }
  }
}
4

2 回答 2

1

好的,这对我有用:

         <DataGridTextColumn.EditingElementStyle>
            <Style TargetType="TextBox">
              <Setter Property="Helper:InputService.NumericOnly" Value="True"/>
            </Style>
          </DataGridTextColumn.EditingElementStyle>
于 2012-08-08T14:07:50.293 回答
0

您的属性实现只需要在 aTextBox或上设置TextBlock。我建议您在代码中放置一个断点并检查它实际设置的控件类型 - 我怀疑您会发现它是您的单元格的父容器,而不是文本控件本身。

编辑:根据您的评论,您可能希望在绑定中包含以下内容:

Binding="{Binding Path=Max, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

这将导致绑定在每次属性更改时刷新,其中大多数输入控件的默认设置是在控件失去焦点时触发。

于 2012-08-02T09:36:57.670 回答