繁体   English   中英

如何制作不会覆盖 WPF.XAML 中的样式的自定义文本框

[英]How to make Custom TextBox that wouldn't override the style in WPF .XAML

所以,我做了一个自定义文本框,它只允许数字:

public partial class IntegerTextBox : TextBox
{
    protected override void OnTextChanged(TextChangedEventArgs e)
    {
        base.OnTextChanged(e);

        Text = new String(Text.Where(c => Char.IsDigit(c)).ToArray());
        SelectionStart = Text.Length;
    }
}

我面临的问题是,当我以这种方式创建它时

IntegerTextBox textBox = new IntegerTextBox() {... };

或者

<u:IntegerTextBox/>

在我的.xaml

它还覆盖了我正在工作的环境(里程碑系统)使用的默认样式。 因此,我没有得到我应该得到的灰色文本框,而是得到 Windows 默认白色文本框。

在 Microsoft 文档中,我找到了一个类似的示例和解释,但我似乎真的找不到让它工作的方法: 覆盖示例

protected override void OnPaint(PaintEventArgs pe)
{
   base.OnPaint(pe);
   // Insert code to do custom painting.
   // If you want to completely change the appearance of your control,
   // do not call base.OnPaint(pe).
}

据我了解,它说:不要打电话给

base.OnTextChanged(e);

(在我的情况下)如果您不想更改控件的外观。 我尝试删除它并得到相同的结果。

如果您不想重新设置 TextBox 的样式,那么您甚至不需要创建自定义 TextBox,而您只需要“附加属性”即可。

在您的项目(如果是 MVVM 的 UI 项目)中,使用以下内容创建 class:

public class TextBoxExtensions
    {

        public static readonly DependencyProperty OnlyNumbersAllowedProperty =
            DependencyProperty.Register("OnlyNumbersAllowed", typeof(int), typeof(TextBoxExtensions), new PropertyMetadata(false,
                (o, args) =>
                {
                    // Assuring we are dealing with TextBox.
                    if (!(o is TextBox textField))
                        return;

                    // make sure TextBox contains characters.
                    if (textField.Text.Length == 0)
                        return;

                    // if TextBox only contains numbers then we are fine and don't go any further.
                    if (textField.Text.All(char.IsDigit)) return;

                    // A letter has been written in TextBox so that we remove it.
                    var result = textField.Text.Remove(textField.Text.Length - 1, 1);
                    textField.Text = result;


                }));

        public static bool GetOnlyNumberSupported(DependencyObject obj)
        {
            return (bool)obj.GetValue(OnlyNumbersAllowedProperty);
        }

        public static void SetOnlyNumberSupported(DependencyObject obj, bool value)
        {
            obj.SetValue(OnlyNumbersAllowedProperty, value);
        }

    }

现在您可以在视图中的任何位置(仅限文本框)使用它,如下所示:

local:TextBoxExtensions.OnlyNumbersAllowed="True"

提示:local 是您项目中 class 上面位置的路径,可以通过“xmlns”声明。

App.xaml IntegerTextBox一个隐式Style

<Style TargetType="{x:Type local:IntegerTextBox}" BasedOn="{StaticResource {x:Type TextBox}}">

然后它应该继承当前应用于<TextBox />元素的任何隐式Style

出现此问题的原因可能是新的 IntegerTextBox class 不使用基本 TextBox class 使用的样式。 请参考已经讨论过类似问题的以下线程: https://stackoverflow.com/a/6780802/12797700

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM