使用保持样式的 MahApps 在 WPF 中扩展 TextBox

Extending TextBox in WPF using MahApps keeping Style

我制作了一个自定义文本框 class 来验证用户的输入,只允许十六进制值,并在 xaml 中使用了这个新的文本框 (HexTextBox)。它运行良好,但 HexTextBox 失去了 Mahapps 的所有样式,包括配色方案和 TextBoxHelper。你知道如何使用这个扩展的TexBox并保持风格吗?

十六进制文本框:

    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

<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 样式。

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