<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Prime Numbers" Width="260" Height="75">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" >
<Button Content="Start" Click="StartOrStop" Name="startStopButton" Margin="5,0,5,0"/>
<TextBlock Margin="10,5,0,0">Number:</TextBlock>
<TextBlock Name="numberTextBlock" Margin="4,5,0,0">3</TextBlock>
</StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Threading;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public delegate void NextPrimeDelegate();
private long num = 1;
private bool continueCalculating = false;
public Window1() : base()
{
InitializeComponent();
}
public void StartOrStop(object sender, EventArgs e)
{
if (continueCalculating)
{
continueCalculating = false;
startStopButton.Content = "Resume";
}
else
{
continueCalculating = true;
startStopButton.Content = "Stop";
startStopButton.Dispatcher.BeginInvoke(DispatcherPriority.Normal,new NextPrimeDelegate(CheckNextNumber));
}
}
public void CheckNextNumber()
{
numberTextBlock.Text = num.ToString();
num += 2;
if (continueCalculating)
{
startStopButton.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.SystemIdle,
new NextPrimeDelegate(this.CheckNextNumber));
}
}
}
}
|