textBox经常用来显示程序的运行状态或者消息,如何让他自动滚动呢?
在显示消息代码下加一条自动滚动到底部的语句即可:
TextBox1.ScrollToEnd();
(如果要显示垂直滚动条设置VerticalScrollBarVisibility="Auto",如果不显示设置为Hidden)
我用的程序代码如下:
1
2
3
4
5
6
7
8
9
10
11
|
this
.Dispatcher.Invoke(
new
Action(() =>
{
//大于100行清除记录,可选
if
(txtReceived.LineCount > 100)
{
txtReceived.Clear();
}
txtReceived.AppendText(
string
.Format(
"当前时间{0:HH:MM:ss}\n"
, DateTime.Now));
//自动滚动到底部
txtReceived.ScrollToEnd();
}));
|
WPF窗口采用默认的Grid布局控件,其“Name”值为“grid1”,在“grid1”中添加三个Button按钮。动态添加控件并访问这些控件的代码如下:
1 private void button1_Click_1(object sender, RoutedEventArgs e) 2 { 3 //添加第一个文本框 4 TextBox tb1 = new TextBox(); 5 tb1.Name = "myTextBox1"; 6 7 tb1.Text = "第一个文本框"; 8 tb1.Width = 100; 9 tb1.Height = 30; 10 11 tb1.HorizontalAlignment = HorizontalAlignment.Left; 12 tb1.VerticalAlignment = VerticalAlignment.Top; 13 tb1.Margin = new Thickness(100, 100, 0, 0); 14 15 grid1.Children.Add(tb1); 16 17 //添加第二个文本框 18 TextBox tb2 = new TextBox(); 19 tb2.Name = "myTextBox2"; 20 21 tb2.Text = "第二个文本框"; 22 tb2.Width = 100; 23 tb2.Height = 30; 24 25 tb2.HorizontalAlignment = HorizontalAlignment.Left; 26 tb2.VerticalAlignment = VerticalAlignment.Top; 27 tb2.Margin = new Thickness(100, 150, 0, 0); 28 29 grid1.Children.Add(tb2); 30 31 } 32 33 private void button2_Click(object sender, RoutedEventArgs e) 34 { 35 //访问添加的全部文本框 36 foreach(var c in grid1.Children) 37 { 38 if (c is TextBox) 39 { 40 TextBox tb = (TextBox)c; 41 MessageBox.Show(tb.Text); 42 } 43 } 44 45 } 46 47 private void button3_Click(object sender, RoutedEventArgs e) 48 { 49 //访问添加的某个文本框 50 foreach (var c in grid1.Children) 51 { 52 if (c is TextBox) 53 { 54 TextBox tb = (TextBox)c; 55 if (tb.Name == "myTextBox2") 56 { 57 MessageBox.Show(tb.Text); 58 } 59 } 60 } 61 }