简体   繁体   中英

Convert code from Windows Form Application to WPF?

I'm trying to convert code from a WFA (Windows Form Application) over to a WPF. However, i'm running into many difficulties. There is no .MaxLength. There is also no .Text as there is when using a Windows Form Application. How would i re-write the following code for WPF?

xbox is refering to a box on a chat window where the user types in text....

PS. The code below DOES work for WFA....

private void BoxChatAreaKeyPress(object sender, KeyPressEventArgs e)
{
    var xBox = (RichTextBox) sender;

    //setting a limit so the user cannot type more than 4000 characters at once
    xBox.MaxLength = 4000;
    if ((xBox.Text.Length > 1) && (e.KeyChar == (char) Keys.Enter))
    {
        WriteMessage(xBox);
    }
}

private static void WriteMessage(RichTextBox xBox)
{
    var writer = new StreamWriter(_client.GetStream());
    String message = xBox.Text.TrimEnd('\n') + "|" + _font.Name;
    writer.WriteLine(message);
    writer.Flush();
    xBox.Text = null;
}

Depending on the complexity of your application, it may not be straightforward directly converting from WinForm to WPF. To answer your two specific problems.

1) As you know, there's no MaxLength property on a RichTextBox in WPF. One way around this is to record the number of characters after the user has entered a character and check if it's greater than your limit. For example ( from here ):

private void xBox_KeyDown(object sender, KeyEventArgs e)
{
     TextRange tr = new TextRange(xBox.Document.ContentStart ,
                                    xBox.Document.ContentEnd);
     if (tr.Text.Length >= 4000 || e.Key == Key.Space || e.Key == Key.Enter)
     {
           e.Handled = true;
           return;
     }
}

2) Likewise, you can use the TextRange property to get the text within an RTB:

TextRange xBoxTR = new TextRange(xBox.Document.ContentStart, 
                                  xBox.Document.ContentEnd);

string xBoxText = xBoxTR.Text;

This is what I came up with:

private void BoxChatAreaKeyPress(object sender, KeyEventArgs e)
{
    var xBox = (RichTextBox)sender;

    // Setting a limit so the user cannot type more than 4000 characters at once
    var textRange = new TextRange(xBox.Document.ContentStart, xBox.Document.ContentEnd);
    var textLen = textRange.Text.Trim();

    if (textLen.Length <= 4000)
    {
        if ((textLen.Length > 1) && (e.Key == Key.Enter))
        {
            WriteMessage(xBox);
        }
    }
    else
    {
        e.Handled = true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM