Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF如何创建带有验证和绑定的自定义文本框_C#_Wpf_Xaml_Binding_Custom Controls - Fatal编程技术网

C# WPF如何创建带有验证和绑定的自定义文本框

C# WPF如何创建带有验证和绑定的自定义文本框,c#,wpf,xaml,binding,custom-controls,C#,Wpf,Xaml,Binding,Custom Controls,我正在开发一个用于货币编辑的自定义文本框。 我见过一些现成的,但它们很复杂和/或不是真正可用的,迫使您采用错误的做法(例如硬编码应该在控件上使用的名称)。 所以我决定自己做,但我在使用绑定选项时遇到了麻烦,因为分配给绑定属性的属性必须是十进制,但TextBox控件的Text属性接受字符串。 我认为答案可能是,重写基类(TextBox)中Text属性的访问方法(getter和setter),但这是不允许的。 “我的绑定”应设置为值,该值设置文本框的文本属性,将其格式化为文本(带有货币符号和所有内容

我正在开发一个用于货币编辑的自定义文本框。
我见过一些现成的,但它们很复杂和/或不是真正可用的,迫使您采用错误的做法(例如硬编码应该在控件上使用的名称)。
所以我决定自己做,但我在使用绑定选项时遇到了麻烦,因为分配给绑定属性的属性必须是十进制,但TextBox控件的Text属性接受字符串。
我认为答案可能是,重写基类(TextBox)中Text属性的访问方法(getter和setter),但这是不允许的。
“我的绑定”应设置为值,该值设置文本框的文本属性,将其格式化为文本(带有货币符号和所有内容),但在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();
        }
    }
公共类CurrencyTextBox:TextBox
{
专用布尔伊斯瓦利德基(密钥)
{
int k=(int)键;

return((k>=34&&k=74&&k看看这篇文章,我想它会对你有所帮助。

或者你可以把这个

private static bool IsTextAllowed(string text)
{
    Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
    return !regex.IsMatch(text);
}
previewtextireput
事件中

private static bool IsTextAllowed(string text)
{
    Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
    return !regex.IsMatch(text);
}
e、 Handled=!IsTextAllowed(e.Text)


像这样创建新的
依赖项属性

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 x = (CurrencyTextBox)d;
    x.Value = (decimal?)e.NewValue;
}

然后绑定到这个新属性

好吧,为了将来的目的,如果有人遇到同样的问题,这里是货币文本框的完整代码。您可以随意使用、修改、出售(千万不要认为它有价值),或者随心所欲地玩它

/*
 * 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());
    }
}
/*
*必要的使用:
*利用制度全球化;
*使用System.Windows;
*使用System.Windows.Controls;
*使用System.Windows.Input;
*使用系统线程;
*别忘了更改XAML上的货币设置
*或在默认情况下(在构造函数上)
*默认设置为巴西雷亚尔(R$)
*/
公共类CurrencyTextBox:TextBox
{
公共货币文本框()
{
CurrencySymbol=“R$”;
CurrencyDecimalPlaces=2;
小数分隔符=“,”;
千分位分隔符=“.”;
Culture=“pt BR”;
}
公共字符串CurrencySymbol{get;set;}
私有int CurrencyDecimalPlaces{get;set;}
公共字符串小数分隔符{get;set;}
公共字符串千位分隔符{get;set;}
公共字符串区域性{get;set;}
二等兵布尔·伊斯瓦利德基(内特k)
{

return(k>=34&&k=74&&k我认为这实际上是不可能的,除了一个只允许数字的框的简单情况。理想情况下,您希望框只能包含一个有效条目,但小数包含一些字符(如“-”和“.”)它们本身无效。用户无法在不将框置于无效状态的情况下键入“-”

类似地,他们可以输入“1”,然后删除1并使框处于不确定状态。当然,这会导致验证错误和红色边框,但您的视图模型仍然认为该值为1,并且不知道该问题

对于正整数,您只能允许数字,并在为空时自动插入零(尽管这有点不友好)


对于小数和负整数,我认为最好的方法是约束用户可以键入的键,但您仍然需要将number属性包装成字符串并进行验证—无论是在按下OK按钮时,还是在理想情况下实现INotifyDataError以显示错误并禁用OK按钮。

我想让用户输入任何文本即使是字符串,当失去焦点时,如果他没有添加十进制值,则调用。我想问题不清楚。问题在于绑定,而不是格式化逻辑。格式化文本已经可以了…如果是这种情况,请创建新的
依赖属性
调用它的值并将您的货币绑定到它。这解决了问题。在ValuePropertyChanged()中我已经用FormatBack和voilá设置了Value属性!竖起大拇指!你不能投票,因为我的“新手”名声!哇,这真的很有帮助!我这里还有另一个问题:当我把这个控件放到我的WPF UI上时,我绑定的初始值在我明确告诉控件更新之前不会显示。有没有办法在y中实现它我们的代码?编辑:我在值的Setter中添加了以下内容:如果(!this.IsFocused)this.Text=String.Format(“{0:0.00}”,Value)为什么要添加事件处理程序而不是只覆盖基处理程序?为什么不“private void keyreased(object sender,KeyEventArgs e)”,为什么不“protected override void OnKeyUp”(KeyEventArgs e)“?
<myNamespace:CurrencyTextBox
    Value="{Binding Path=DataContext.MyDecimalProperty, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
    CurrencySymbol="R$ "
    Culture="pt-BR"
    CurrencyDecimalPlaces="2"
    DecimalSeparator=","
    ThousandSeparator="." />