【问题标题】:How to create numeric Textbox Custom Control with dependency Property in WPF?如何在 WPF 中创建具有依赖属性的数字文本框自定义控件?
【发布时间】:2015-08-10 04:56:26
【问题描述】:

我想在 WPF 中为具有依赖属性的数字文本框创建一个自定义控件,在我的解决方案中,我添加一个 WPF 应用程序和自定义控件 (WPF),然后在公共类中,我创建依赖属性 ....

现在我不知道如何为文本框编写规则以及哪个事件为真?

另一个问题:我对数字文本框的规则是什么,这个文本框必须给出 number.Separating .this自定义文本框用于会计系统。

public static readonly DependencyProperty NumberTextbox; 
static Numeric()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(Numeric), new FrameworkPropertyMetadata(typeof(Numeric)));
    FrameworkPropertyMetadata metadata = new FrameworkPropertyMetadata("Enter Your Text", OnKeyDown);
    NumberTextbox =DependencyProperty.Register("Text", typeof(TextBox), typeof(FrameworkElement), metadata);
}


public string NumberTXT
{
    get { return (string)GetValue(NumberTextbox); }
    set { SetValue(NumberTextbox, value); }
} 

【问题讨论】:

  • 我为我的规则写了这个事件,但在我的元数据中它不是真的???
  • protected override void OnKeyDown(DependencyObject o, KeyEventArgs e) { //System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]"); //if (reg.IsMatch(NumberTXT)) //{ // e.Handled = true; //} base.OnKeyDown(e); if (e.Key >= Key.D0 && e.Key
  • 如果您有其他信息,您可以编辑您的答案,而不是评论它:)

标签: c# wpf dependency-properties


【解决方案1】:

我建议您在下面的示例代码中添加另一个依赖属性,我将其命名为 Value 也可以用逗号或 NumberFormatInfo.CurrentInfo.NumberDecimalSeparator 格式化您的号码 并通过两个属性 SelectionLength 和 SelectionStart 控制插入符号位置的变化。 最后获取更详细和完整的代码WPF Maskable Number Entry TextBox

区域值属性

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(double), typeof(NumericTextBox), new PropertyMetadata(new Double(), OnValueChanged));

    private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        //var numericBoxControl = (NumericTextBox)sender;
    }
    public double Value
    {
        get { return (double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); Text = value.ToString("###,###,###"); }
    }

结束区域

    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        base.OnPreviewTextInput(e);
        var txt = e.Text.Replace(",", "");
        e.Handled = !IsTextAllowed(txt);
        if (IsTextAllowed(txt))
        {
            if (Text.Length == 3)
            {
                Text = Text.Insert(1,",");
                SelectionLength = 1;
                SelectionStart += Text.Length;
            }
        }
    }

    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        base.OnPreviewKeyDown(e);
        if (e.Key == Key.Back)
        {
            if (Text.Length == 5)
            {
                Text = Text.Replace(",", "");
                SelectionLength = 1;
                SelectionStart += Text.Length;
            }
        }
    }



    protected override void OnTextChanged(TextChangedEventArgs e)
    {            
        var txt = Text.Replace(",", "");
        SetValue(ValueProperty, txt.Length==0?0:double.Parse(txt));
        base.OnTextChanged(e);
    }

    private static bool IsTextAllowed(string text)
    {
        try
        {
            double.Parse(text);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }

【讨论】:

    【解决方案2】:

    我不完全理解您的问题以及为什么您需要依赖属性来制作数字文本框自定义控件。您可以做的是从文本框继承并处理 PreviewTextInput,就像它在 this question by Ray 中解决的那样:

    然后你得到:

      public class NumericTextBox : TextBox
      {
    
        public NumericTextBox()
        {
          PreviewTextInput += NumericTextBox_PreviewTextInput;
        }
    
        void NumericTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
          e.Handled = !isTextAllowed(e.Text);
        }
    
        private static bool isTextAllowed(string text)
        {
          var regex = new Regex("[^0-9]+");
          return !regex.IsMatch(text);
        }
      }
    

    你可以这样使用它:

     <myNameSpace:NumericTextBox />
    

    现在您可以添加您想要的任何其他验证。

    我还将针对粘贴问题实施解决方案,例如(另请参阅链接):

    private void textBoxPasting(object sender, DataObjectPastingEventArgs e)
        {
          if (e.DataObject.GetDataPresent(typeof(String)))
          {
            var text = (String)e.DataObject.GetData(typeof(String));
            if (!isTextAllowed(text))
            {
              e.CancelCommand();
            }
          }
          else
          {
            e.CancelCommand();
          }
        }
    

    【讨论】:

    • 有人不知道这件事吗?
    【解决方案3】:

    干得好,但让我用 C# 中的 UserControl 完成以下任务:

    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    namespace NumericBox
    {
        public partial class NumericBox : TextBox
        {
            public NumericBox
            {
                this.TextAlign = HorizontalAlignment.Right;
                this.Text = "0,00";
                this.KeyPress += NumericBox_KeyPress;
            }
    
            public double NumericResult
            {
                get{
                    double d = Convert.ToDouble(this.Text.Replace('.', ','));
                    return d;
                }
            }
            private void NumericBox_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
                    e.Handled = true;
    
                if ((e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1))
                    e.Handled = true;
    
                if (e.KeyChar == 13)
                {
                    e.Handled = true;
                    SendKeys.Send("{TAB}");
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多