使用MahApps保持样式在WPF中扩展TextBox [英] Extending TextBox in WPF using MahApps keeping Style

查看:349
本文介绍了使用MahApps保持样式在WPF中扩展TextBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个自定义文本框类,用于验证用户的输入以仅允许使用十六进制值,并在xaml中使用了此新文本框(HexTextBox).它运作良好,但HexTextBox放弃了Mahapps的所有样式,包括配色方案和TextBoxHelper.您知道如何使用扩展的TexBox并保持样式吗?

I made a custom textbox class for validating the input of the user to only allow Hexadecimal values, and used this new textbox (HexTextBox) in the xaml. It works well, but the HexTextBox looses all the style from the Mahapps, including color scheme and TextBoxHelper. Do you know how to use this extended TexBox and keep the style?

HexTextBox:

HexTextBox:

    public class HexTextBox : TextBox
    {
    public HexTextBox()
    {

    }
    /// <summary>
    /// Raise when a keyboard key is pressed.
    /// </summary>
    /// <param name="e">The event args.</param>
    protected override void OnPreviewKeyDown(KeyEventArgs e)
    {
        if (e.Key == Key.Space)
        {
            e.Handled = true;
        }

        base.OnPreviewKeyDown(e);
    }

    /// <summary>
    /// Raise when a text will be inputed in the text box object.
    /// </summary>
    /// <param name="e">The event args.</param>
    protected override void OnTextInput(TextCompositionEventArgs e)
    {
        int hexNumber;

        e.Handled = !int.TryParse(e.Text, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out hexNumber);

        base.OnTextInput(e);
    }
}

Window.xaml

Window.xaml

<UserControl
...
    xmlns:CoreWPF="clr-namespace:CoreWPF;assembly=CoreWPF" 
...>

<CoreWPF:HexTextBox 
        Text="{Binding DataXor1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
        Grid.Column="2" Grid.Row="0"
        controls:TextBoxHelper.ClearTextButton="True"
        Height="26"
        TextWrapping="Wrap" 
        CharacterCasing="Upper"
        VerticalAlignment="Center"/>

提前谢谢!

推荐答案

为自定义控件创建默认样式,该样式将基于TextBox样式.

Create default style for your custom control which will be based on TextBox style.

<Style TargetType="Controls:HexTextBox" BasedOn="{StaticResource {x:Type TextBox}}"/>

这篇关于使用MahApps保持样式在WPF中扩展TextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆