ListBox日志效果 - (二十四)
执行效果如下:
BorderThickness:此属性设置 Border 边框的大小
x:Name:控件的名称
FontSize:字体大小
Background:背景色
HorizontalScrollBarVisibility:滚动条设置
1、Disabled,禁用滚动条。表现在无论内容是否超过父容器大小,都不会显示滚动条,并且滚动鼠标滑轮也不会滑动内容。
2、Auto,自动。内容不超出父容器时,不显示滚动条,超出父容器时,显示滚动条。
3、Hidden,隐藏滚动条。与Disabled的区别在于,这里只是隐藏,当滚动鼠标滑轮时,依然可以滚动内容。
4、Visible,始终显示。不论内容是否超过父容器大小,都会显示滚动条。
MainWindow.xaml 代码如下:
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="400" Width="600">
<Grid>
<ListBox Margin="10,10,10,10" BorderThickness="10" x:Name="ListBoxLog" FontSize="8"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="Black"></ListBox>
</Grid>
</Window>
MainWindow.xaml.cs代码如下:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace WpfApp
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
/// <summary>
/// 窗体日志信息
/// </summary>
public static ObservableCollection<TextBlock> ListBoxLogs { get; set; } = new ObservableCollection<TextBlock>();
public MainWindow()
{
InitializeComponent();
// 关联到数据
ListBoxLog.ItemsSource = ListBoxLogs;
// 启动线程
new Thread(ThreadLog) { IsBackground = true }.Start();
}
private void ThreadLog()
{
List<Brush> colors = new List<Brush>() { Brushes.White, Brushes.Yellow, Brushes.DarkOrange, Brushes.SpringGreen, Brushes.Blue };
while (true)
{
foreach (Brush color in colors)
{
Application.Current.Dispatcher.BeginInvoke((Action)delegate ()
{
TextBlock item = new TextBlock();
item.Text = $"当前时间:{DateTime.Now}";
item.FontSize = 14;
item.TextWrapping = TextWrapping.Wrap;
item.Foreground = color;
ListBoxLogs.Insert(0, item);
//控制只显示10条
if (ListBoxLogs.Count > 10)
{
for (int i = 10; i < ListBoxLogs.Count; i++)
{
ListBoxLogs.RemoveAt(i);
}
}
});
Thread.Sleep(1000);
}
}
}
}
}