c# - WPF 如何创建具有验证和绑定(bind)的自定义文本框

标签 c# wpf xaml binding custom-controls

我正在开发一个用于货币编辑的自定义文本框。
我见过一些现成可用的,但它们很复杂和/或不是真正可用,迫使您采取不良做法(例如硬编码应该在控件上使用的名称)。
所以我决定自己做,但我在使用绑定(bind)选项时遇到了麻烦,因为分配给绑定(bind)属性的属性必须是小数,但 TextBox 控件的 Text 属性接受字符串。
我想的答案是,也许可以覆盖基类(TextBox)中Text属性的访问方法(getters和setters),但这是不允许的。
我的绑定(bind)应设置为值,该值设置 TextBox 的文本属性,将其格式化为文本(带有货币符号和所有内容),但在 Get 方法中将其转换回数字数据类型。
这是我到目前为止所取得的成就:

public class CurrencyTextBox : TextBox
    {
        private bool IsValidKey(Key key)
        {
            int k = (int)key;
            return ((k >= 34 && k <= 43) //digits 0 to 9
                || (k >= 74 && k <= 83) //numeric keypad 0 to 9
                || (k == 2) //back space
                || (k == 32) //delete
                );
        }
        private void Format()
        {
            //formatting decimal to currency text here
            //Done! no problems here
        }
        private void FormatBack()
        {
            //formatting currency text to decimal here
            //Done! no problems here
        }
        private void ValueChanged(object sender, TextChangedEventArgs e)
        {
            this.Format();
        }
        private void MouseClicked(object sender, MouseButtonEventArgs e)
        {
            this.Format();
            // Prevent changing the caret index
            this.CaretIndex = this.Text.Length;
            e.Handled = true;
        }
        private void MouseReleased(object sender, MouseButtonEventArgs e)
        {
            this.Format();
            // Prevent changing the caret index
            this.CaretIndex = this.Text.Length;
            e.Handled = true;
        }
        private void KeyPressed(object sender, KeyEventArgs e)
        {
            if (IsValidKey(e.Key))
                e.Handled = true;
            if (Keyboard.Modifiers != ModifierKeys.None)
                return;
            this.Format();
        }
        private void PastingEventHandler(object sender, DataObjectEventArgs e)
        {
            // Prevent copy/paste
            e.CancelCommand();
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            // Disable copy/paste
            DataObject.AddCopyingHandler(this, PastingEventHandler);
            DataObject.AddPastingHandler(this, PastingEventHandler);
            this.CaretIndex = this.Text.Length;
            this.PreviewKeyUp += KeyPressed;
            this.PreviewMouseDown += MouseClicked;
            this.PreviewMouseUp += MouseReleased;
            this.TextChanged += ValueChanged;
            this.Format();
        }
    }

这是 XAML:

<MyNamespace:CurrencyTextBox x:Name="TxbCurrency" Text="{Binding Path=DataContext.Element.Currency, ValidatesOnDataErrors=True}" />

到目前为止一切顺利!从 decimal 属性到 TextBox 文本的绑定(bind)是“正确的”。但是如何在编辑后从文本中取回小数点是现在的问题。
从 decimal 到 .Text 的绑定(bind)使用装箱来隐藏 ToString() 方法。
问题在这里: 在这种情况下,如何从 decimal 重载 Parse() 方法以使用我的 FormatBack() 方法从 TextBox 的文本中获取 decimal?

最佳答案

好吧,为了将来的目的,如果有人遇到同样的麻烦,这里是货币文本框的完整代码。随意使用它、修改它、出售它(不要认为它有值(value),你),或者随心所欲地使用它!

/*
 * the necessary usings:
 * using System.Globalization;
 * using System.Windows;
 * using System.Windows.Controls;
 * using System.Windows.Input;
 * using System.Threading;
 * And don't forget to change the currency settings on the XAML
 * or in the defaults (on the contructor)
 * It's set by default to Brazilian Real (R$)
 */
public class CurrencyTextBox : TextBox
{
    public CurrencyTextBox()
    {
        CurrencySymbol = "R$ ";
        CurrencyDecimalPlaces = 2;
        DecimalSeparator = ",";
        ThousandSeparator = ".";
        Culture = "pt-BR";
    }
    public string CurrencySymbol { get; set; }
    private int CurrencyDecimalPlaces { get; set; }
    public string DecimalSeparator { get; set; }
    public string ThousandSeparator { get; set; }
    public string Culture { get; set; }
    private bool IsValidKey(int k)
    {
        return (k >= 34 && k <= 43) //digits 0 to 9
            || (k >= 74 && k <= 83) //numeric keypad 0 to 9
            || (k == 2) //back space
            || (k == 32) //delete
            ;
    }
    private string Format(string text)
    {
        string unformatedString = text == string.Empty ? "0,00" : text; //Initial state is always string.empty
        unformatedString = unformatedString.Replace(CurrencySymbol, ""); //Remove currency symbol from text
        unformatedString = unformatedString.Replace(DecimalSeparator, ""); //Remove separators (decimal)
        unformatedString = unformatedString.Replace(ThousandSeparator, ""); //Remove separators (thousands)
        decimal number = decimal.Parse(unformatedString) / (decimal)Math.Pow(10, CurrencyDecimalPlaces); //The value will have 'x' decimal places, so divide it by 10^x
        unformatedString = number.ToString("C", CultureInfo.CreateSpecificCulture(Culture));
        return unformatedString;
    }
    private decimal FormatBack(string text)
    {
        string unformatedString = text == string.Empty ? "0.00" : text;
        unformatedString = unformatedString.Replace(CurrencySymbol, ""); //Remove currency symbol from text
        unformatedString = unformatedString.Replace(ThousandSeparator, ""); //Remove separators (thousands);
        CultureInfo current = Thread.CurrentThread.CurrentUICulture; //Let's change the culture to avoid "Input string was in an incorrect format"
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Culture);
        decimal returnValue = decimal.Parse(unformatedString);
        Thread.CurrentThread.CurrentUICulture = current; //And now change it back, cuz we don't own the world, right?
        return returnValue;
    }
    private void ValueChanged(object sender, TextChangedEventArgs e)
    {
        // Keep the caret at the end
        this.CaretIndex = this.Text.Length;
    }
    private void MouseClicked(object sender, MouseButtonEventArgs e)
    {
        // Prevent changing the caret index
        e.Handled = true;
        this.Focus();
    }
    private void MouseReleased(object sender, MouseButtonEventArgs e)
    {
        // Prevent changing the caret index
        e.Handled = true;
        this.Focus();
    }
    private void KeyReleased(object sender, KeyEventArgs e)
    {
        this.Text = Format(this.Text);
        this.Value = FormatBack(this.Text);
    }
    private void KeyPressed(object sender, KeyEventArgs e)
    {
        if (IsValidKey((int)e.Key))
            return;
        e.Handled = true;
        this.CaretIndex = this.Text.Length;
    }
    private void PastingEventHandler(object sender, DataObjectEventArgs e)
    {
        // Prevent/disable paste
        e.CancelCommand();
    }
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        DataObject.AddCopyingHandler(this, PastingEventHandler);
        DataObject.AddPastingHandler(this, PastingEventHandler);
        this.CaretIndex = this.Text.Length;
        this.KeyDown += KeyPressed;
        this.KeyUp += KeyReleased;
        this.PreviewMouseDown += MouseClicked;
        this.PreviewMouseUp += MouseReleased;
        this.TextChanged += ValueChanged;
        this.Text = Format(string.Empty);
    }
    public decimal? Value
    {
        get { return (decimal?)this.GetValue(ValueProperty); }
        set { this.SetValue(ValueProperty, value); }
    }
    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
        "Value",
        typeof(decimal?),
        typeof(CurrencyTextBox),
        new FrameworkPropertyMetadata(new decimal?(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(ValuePropertyChanged)));
    private static void ValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((CurrencyTextBox)d).Value = ((CurrencyTextBox)d).FormatBack(e.NewValue.ToString());
    }
}

和 xaml:

<myNamespace:CurrencyTextBox
    Value="{Binding Path=DataContext.MyDecimalProperty, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
    CurrencySymbol="R$ "
    Culture="pt-BR"
    CurrencyDecimalPlaces="2"
    DecimalSeparator=","
    ThousandSeparator="." />

关于c# - WPF 如何创建具有验证和绑定(bind)的自定义文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973220/

相关文章:

c# - 哪些异常类已经存在,我们什么时候使用它们?

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException 未处理

c# - 在图片上添加点击事件

c# - 根据您放入另一个 WPF 的信息将值/打开文件放入 WPF

c# - 名称 <...> 在 namespace clr-namespace <...> 中不存在

c# - XAML 布局更改未在生成时更新

c# - 如何在 Win 10 UWP 项目上找到本地 IP 地址

c# - 使用来自 WCF WebService 的模型

c# - System.Diagnostics.StackTrace 紧凑框架

c# - WPF:无法获取自定义附加属性作为触发器属性