DataGrid中的附加属性

时间:2012-08-02 09:11:07

标签: wpf datagrid attached-properties

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

2 个答案:

答案 0 :(得分:1)

好的,这对我有用:

         <DataGridTextColumn.EditingElementStyle>
            <Style TargetType="TextBox">
              <Setter Property="Helper:InputService.NumericOnly" Value="True"/>
            </Style>
          </DataGridTextColumn.EditingElementStyle>

答案 1 :(得分:0)

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

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

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

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