views:

126

answers:

1

Hi,

is it possible to set number of characters per row for a multiline (AcceptsReturn="True") textbox in Silverlight? Like Cols attribute of Textarea in HTML.

+1  A: 

Not really. Normally you just set the height and width to whatever you want. Is there a particular reason why you want a certain number of characters on each line?

[EDIT]
I found some code here that splits a string into equal chunks:
http://stackoverflow.com/questions/1450774/c-split-a-string-into-equal-chunks-each-of-size-4
Using that, I came up with the following. It works ok but needs some tweaking.

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    var text = (sender as TextBox).Text.Replace(Environment.NewLine, "").Chunk(8).ToList();

    (sender as TextBox).Text = String.Join(Environment.NewLine, text.ToArray());
    (sender as TextBox).SelectionStart = (sender as TextBox).Text.Length;
}

And the extension method:

public static class Extensions
{
    public static IEnumerable<string> Chunk(this string str, int chunkSize)
    {
        for (int i = 0; i < str.Length; i += chunkSize)
            yield return str.Substring(i, Math.Min(chunkSize, str.Length - i));
    }
}
Henrik Söderlund
The reason is that the TextBox works as a formatter of a message that is about to be shown on an external display with fixed row length. So the user shall see it formatted as it will be shown.Using precise textbox width is the solution I am using right now but it would be much easier to set number of characters instead of calculating proper textbox width. Especially when the value changes.
gius