Extending TextBox in WPF using MahApps keeping Style

妖精的绣舞 提交于 2019-12-01 07:50:14

问题


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:

    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"/>

Thanks in advance!


回答1:


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

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


来源:https://stackoverflow.com/questions/32230427/extending-textbox-in-wpf-using-mahapps-keeping-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!