4

问题:我没有获得具有水平自动换行和垂直自动增长功能的文本框设置。我希望通过编写代码来做到这一点。我编写了以下代码,在鼠标 dblclick 处使用自动换行创建一个文本框:

        TextBox text2 = new TextBox();
        text2.Width = 500;
        text2.Visibility = Visibility.Visible;
        text2.Focus();
        text2.Height = 30;
        text2.HorizontalAlignment = HorizontalAlignment.Left;
        text2.VerticalAlignment = VerticalAlignment.Top;
        Point p = e.GetPosition(LayoutRoot);
        text2.Margin = new Thickness(p.X, p.Y, 0, 0);
        LayoutRoot.Children.Add(text2);

但是,文本框不会垂直增长。有人可以建议我用 C# 编写代码来完成我想要的吗?

4

3 回答 3

5

尝试使用这个

        Grid grid = new Grid();
        grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
        grid.RowDefinitions.Add(new RowDefinition());

        TextBox textBox = new TextBox() { Width = 100, TextWrapping = TextWrapping.Wrap };

        textBox.SetValue(Grid.RowProperty, 0);
        grid.Children.Add(textBox);
        window.Content = grid;

其中 window 是分配给 Window(root) 的名称。

于 2009-11-23T14:42:09.500 回答
0

One way to accomplish the growth you're looking for is to use a string measuring mechanism which you would run any time the text in your text box changes. Simply measure and resize your text box accordingly with any change to the contents.

于 2009-11-23T14:35:41.027 回答
0

你试过这个吗?

text2.Height = double.NaN; // or don't set the property, but some custom styles might give a default value ..
text2.TextWrapping = TextWrapping.Wrap;
text2.MinHeight = 30; // or not if you want the styles default

代替

text2.Height = 30;

不设置它或使用 double.NaN 与在 xaml 中使用“自动”相同。

于 2009-11-23T14:39:18.633 回答