タイマイベントよりユーザ インターフェースにアクセスする
.NET では、Window 上のコントロール等、UI に別スレッドからアクセスすることはできなくなっている。System.Threading.Timer や System.Timers.Timer UI とは別スレッドで動作するため、UI にアクセスするには少々手順を踏まなければならない。System.Windows.Threading.DispatcherTimer は同じスレッドで動作するので、イベントハンドラ内から UI にアクセスが可能。
// Window1.xaml.cs using System.Windows; public partial class Window1 : Window { private void Window_IsVisibleChanged (object sender, DependencyPropertyChangedEventArgs e) { // ウインドウが表示された場合 if ((bool) e.NewValue == true) { ProgressUpdate.Value = 0; // タイマを作成 var timer = new System.Windows.Threading.DispatcherTimer (); // タイマ間隔を設定 timer.Interval = TimeSpan.FromMilliseconds (1000); // イベントハンドラを設定 timer.Tick += new EventHandler (delegate (object s, EventArgs a) { ProgressUpdate.Value += 10; if ((100 - ProgressUpdate.Value) < 0.1) { var t = s as System.Windows.Threading.DispatcherTimer; if (s != null) { t.Stop (); } this.Close (); } } ); // タイマ始動 timer.Start (); } } }
<!-- Window1.xaml -->
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
IsVisibleChanged="Window_IsVisibleChanged">
<Grid SnapsToDevicePixels="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Margin="5" TextAlignment="Center">処理中です…。</TextBlock>
<ProgressBar Grid.Row="1" Margin="5" Height="22" x:Name="ProgressUpdate" />
</Grid>
</Window>
トラックバック
- このエントリーにトラックバック:
- http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/2168
コメント