WPF How to create a Custom Textbox with validation and binding

前端 未结 4 1074
死守一世寂寞
死守一世寂寞 2021-01-15 05:47

I\'m developing a custom text box for currency editing.
I\'ve seen some ready to use ones, but they\'re complicated and/or not really usable, forcing you to bad practi

4条回答
  •  无人共我
    2021-01-15 06:16

    create new Dependency Property like this

    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;
    }
    

    and then bind to this new property

提交回复
热议问题