C# WPF 从 TextBox 更改文本事件

问题描述 投票:0回答:1

我有一个问题。我创建了一个名为“LetterBox”的新类,该类继承自 TextBox,目前一切正常。但问题来了:我需要“填充”文本字段的事件或函数。

例如:我按“T”键,文本框文本字段中是字母 T。但是哪个事件或函数填充了该字段?

我想将文本字段从字符串更改为我自己的“WordElement”对象。

这是我的 LetterBox 课程:

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;
        }
    }
}

这是我的 WordElement 类:

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;
    }
}

希望您理解我的问题并可以帮助我:)

P.S.:我的英语不是最好的:P

c# wpf textbox .net-6.0
1个回答
0
投票

设置

e.Handled = true;
以抑制
LetterBox_KeyDown
中输入的标准处理。

但是,如果您从另一个控件派生,您将覆盖

OnKeyDown
而不是订阅事件,然后简单地不调用
base.OnKeyDown();
来抑制输入的标准处理。

protected override void OnKeyDown(KeyEventArgs e)
{
    // Your code
}
© www.soinside.com 2019 - 2024. All rights reserved.