【wpf】TextBoxでログ出力スクロールバー表示で更新時、末尾を表示
ログ出力用のTextBoxを配置し、スクロールバーAutoで常に最新のログ行を表示させる方法
<NavigationWindow x:Class="tameshi01.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:tameshi01" mc:Ignorable="d" Title="TEST" Height="500" Width="700" Source="home.xaml"> </NavigationWindow>
<Page x:Class="tameshi01.home" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:tameshi01" mc:Ignorable="d" d:DesignHeight="500" d:DesignWidth="700" Title="home" Loaded="Page_Loaded"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="2*" /> <ColumnDefinition Width="1*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="1*" /> <RowDefinition Height="1*" /> </Grid.RowDefinitions> <TextBox x:Name="log_text" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" VerticalScrollBarVisibility="Auto" /> <Button x:Name="log_button" Grid.Column="1" Grid.Row="0" Click="logbuton" Content="ログボタン1"/ <Button x:Name="log_button2" Grid.Column="1" Grid.Row="1" Click="logbuton2" Content="ログボタン2" /> </Grid> </Page>
using System.Windows; using System.Windows.Controls; namespace tameshi01 { public partial class home : Page { public home() { InitializeComponent(); } private void Page_Loaded(object sender, RoutedEventArgs e) { writeLog("テスト文字列1"); writeLog("テスト文字列2"); } public void writeLog(string text) { log_text.AppendText("[" + System.DateTime.Now.ToString() + "]" + text + "\r\n"); log_text.ScrollToEnd(); } private void logbuton(object sender, RoutedEventArgs e) { writeLog("テスト文字列3"); writeLog("テスト文字列4"); } private void logbuton2(object sender, RoutedEventArgs e) { writeLog("テスト文字列5"); writeLog("テスト文字列6"); } } }