Search code examples
c#wpftextbox.net-6.0

C# WPF Change Text Event From TextBox


i have a problem. I made a new class called "LetterBox" this class inherits from TextBox everything is working for now. But here comes the problem: I need the Event or Function that "fills" the Text-Field.

For example: I press the 'T' Key and in the TextBox Text Field ist the letter T. But which event or function fills this field?

I wanna change the Text-Field from String to my own 'WordElement' object.

Here is my LetterBox class:

internal class LetterBox : TextBox
{
    public static List<WordElement> Letters { get; set; } = new();

    public LetterBox()
    {
        FontSize = 20;

        KeyDown += LetterBox_KeyDown;
    }
    
    // This event wont work as expected, because the Text gets added twice
    public void LetterBox_KeyDown(object sender, KeyEventArgs e)
    {
        // Retrieve the Key that was pressed
        Key key = e.Key;
        char ckey = (char)key;

        WordElement we = new();
        
        // Set the Letter in the WordElement to manipulate it later
        we.SetLetter(ckey);
        
        Letters.Add(we);

        // Delete the Text to "refresh" it
        Text = "";

        // Put every Letter from the list back in the Text
        foreach (WordElement wordElement in Letters)
        {
            Text += wordElement.Letter;
        }
    }
}

Here is my WordElement class:

internal class WordElement
{
    public char Letter { get; private set; }
    public Color Color { get; private set; } = Colors.Black;
    public float Size { get; private set; } = 12;
    public bool Bold { get; private set; } = false;
    public bool Italic { get; private set; } = false;
    public bool Underlined { get; private set; } = false;

    public void SetLetter(char letter)
    {
        Letter = letter;
    }

    public void SetColor(Color color)
    {
        Color = color;
    }

    public void SetSize(float size)
    {
        Size = size;
    }

    public void SetBold(bool bold)
    {
        Bold = bold;
    }

    public void SetItalic(bool italic)
    {
        Italic = italic;
    }

    public void SetUnderlined(bool underlined)
    {
        Underlined = underlined;
    }
}

Hopefully you understand my problem and can help me :)

P.S.: my english is not the best :P


Solution

  • Set e.Handled = true; to suppress the standard handling of the input in LetterBox_KeyDown.

    But if you derive from another control, you would override OnKeyDown instead of subscribing to the event and then simply not call base.OnKeyDown(); to suppress the standard handling of the input.

    protected override void OnKeyDown(KeyEventArgs e)
    {
        // Your code
    }