WPF Lecture Source Code
== ToUpper1.App.xaml =============================================
-- ToUpper1.App.xaml.cs ------------------------------------------
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace ToUpper1
{
///
/// ToUpper1 Example
/// A Simple XAML Example
///
/// Interaction logic for App.xaml
///
public partial class App : Application
{
}
}
-- ToUpper1.Window1.xaml -----------------------------------------
-- ToUpper1.Window1.xaml.cs --------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ToUpper1
{
///
/// ToUpper1 Example
/// A Simple XAML Example
///
/// Interaction logic for Window1.xaml
///
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void txtInput_TextChanged(
object sender, TextChangedEventArgs e)
{
txtUpperCase.Text = txtInput.Text.ToUpper();
}
}
}
== PizzaGuy1.Window1.xaml =========================================
-- PizzaGuy2.Window1.xaml.cs -------------------------------------
Pizza.jpg
== Local.Window1.xaml ============================================
-- Local.Person.cs -----------------------------------------------
using System;
namespace Local
{
///
/// Local Example
/// Use data binding to display the fields of a Person
/// object in textboxes.
///
public class Person
{
private string nameField;
private string genderField;
private int ageField;
public Person()
{
nameField = "Unknown";
genderField = "U";
ageField = -1;
}
public string Name
{
get { return nameField; }
set { nameField = value; }
}
public string Gender
{
get { return genderField; }
set { genderField = value; }
}
public int Age
{
get { return ageField; }
set { ageField = value; }
}
public override string ToString()
{
return "Name: " + Name + "\n" +
"Gender: " + Gender + "\n" +
"Age: " + Age;
}
}
}
== ListBox2.Window1.xaml.cs ======================================
RaccoonDeerBear
-- ListBox2.Window1.xaml.cs --------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
namespace ListBox
{
///
/// ListBox2 Example
/// Compare the items added at design time
/// with the items added at runtime.
///
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
listBox1.Items.Add("Oppossum");
listBox1.Items.Add("Mouse");
listBox1.Items.Add("Skunk");
}
private void listBox1_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
int index = listBox1.SelectedIndex;
if (index >= 0)
textBox1.Text = listBox1.Items[index].ToString();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
int index = listBox1.SelectedIndex;
if (index >= 0)
listBox1.Items.RemoveAt(index);
}
}
}
== RadioButtons.Window1.xaml.cs ==================================
== DependencyProperty.Window1.xaml ===============================
== RightToLeft.Window1.xaml ======================================
Hebrew: אבג
== Controls2.Window1.xaml ========================================
Radio Button 1
Radio Button 2
Check Box
-- Controls2.Window1.xaml.cs -------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
namespace Controls2
{
///
/// Controls1 Example
/// Display control settings when button is pressed.
///
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string output = "TextBox: " + txtString.Text + "\n" +
"Slider: " + sld1.Value + "\n" +
"Radio Button 1: " + rad1.IsChecked + "\n" +
"Radio Button 2: " + rad2.IsChecked + "\n" +
"Check Box: " + chk1.IsChecked;
MessageBox.Show(output);
}
}
}
== Controls3.Window1.xaml ========================================
Radio Button 1Radio Button 2Check Box
-- Controls3.Window1.xaml.cs -------------------------------------
// Code is same as Controls2 Example
== Numbers1.Window1.xaml =========================================
-- Numbers1.Window1.xaml.cs --------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
namespace Numbers1
{
///
/// Numbers1 Example
/// Show how to represent a phone keypad in a
/// UniformGrid layout. The size of the buttons
/// resize as the window is resized.
///
public partial class Window1 : Window
{
string digits;
public Window1()
{
InitializeComponent();
}
private void ClickHandler(object sender, RoutedEventArgs e)
{
string digit = ((Button) sender).Content.ToString();
digits += digit;
MessageBox.Show(digits);
}
private void Reset(object sender, RoutedEventArgs e)
{
digits = "";
MessageBox.Show("Digits reset.");
}
}
}
== Controls4.Window1.xaml ========================================
Radio Button 1Radio Button 2Check Box
== Controls5.Window1.xaml.cs =====================================
abcdefgRadio Button 1Radio Button 2Check Box
-- Controls5.Window1.xaml.cs -------------------------------------
// Code is same as Controls2 Example
== RoutedEvents.Window1.xaml =====================================
-- RoutedEvents.Window1.xaml.cs ----------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace RoutedEvents
{
///
/// RoutedEvents Example
/// Illustrate the difference between bubbling and tunneling
/// events using the MouseDown and PreviewMouseDown events.
/// Add the statement
/// e.Handled = true;
/// to an event handler to halt routing.
///
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void ellipse1_MouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("ellipse1_MouseDown");
}
private void ellipse1_PreviewMouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("ellipse1_PreviewMouseDown");
}
private void ellipse2_MouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("ellipse2_MouseDown");
}
private void ellipse2_PreviewMouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("ellipse2_PreviewMouseDown");
}
private void StackPanel_MouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("stackPanel1_MouseDown");
}
private void StackPanel_PreviewMouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("stackPanel1_PreviewMouseDown");
}
private void button1_MouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("buttonl_MouseDown");
}
private void button1_PreviewMouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("buttonl_PreviewMouseDown");
}
private void button1_Click(
object sender, RoutedEventArgs e)
{
Console.WriteLine("window1_Click");
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
Console.WriteLine("window1_MouseDown");
}
private void Window_PreviewMouseDown(
object sender, MouseButtonEventArgs e)
{
Console.WriteLine("window1_PreviewMouseDown");
}
}
}
== Slider2.Window1.xaml ==========================================
-- Slider2.DoubleToStringConverter.cs-----------------------------
using System;
using System.Windows.Data;
using System.Globalization;
namespace Slider2
{
///
/// Slider2 Example
/// Show how to use data binding to display the
/// value of a Slider control in a TextBox control.
/// Use a value converter to display the value
/// truncated to two places behind the decimal.
///
[ValueConversion(typeof(double), typeof(string))]
public class DoubleToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object obj, CultureInfo info)
{
if (targetType == typeof(string))
{
double x = double.Parse(value.ToString());
return string.Format("{0,5:#0.00}", x);
}
else
return null;
}
public object ConvertBack(object value, Type targetType,
object obj, CultureInfo info)
{
throw new NotImplementedException();
}
}
}
== HaveBirthday1.Window1.xaml ====================================
-- HaveBirthday1.Window1.xaml.cs ---------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
namespace HaveBirthday1
{
///
/// HaveBirthday1 Example
/// Show how to achieve two-way data transfer between a
/// Person class object and the Age textbox without using
/// data binding.
///
public partial class Window1 : Window
{
private Person person = new Person("Alice", "F", 11);
public Window1()
{
InitializeComponent();
// Fill in Name and Gender textboxes.
txtName.Text = person.Name;
txtGender.Text = person.Gender;
txtAge.Text = person.Age.ToString();
// Watch for changes in Age property of person.
person.PropertyChanged += person_PropertyChanged;
// Watch for changes in Age TextBox property.
}
private void btnShowPerson_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(person.ToString());
}
private void btnHaveBirthday_Click(object sender, RoutedEventArgs e)
{
person.HaveBirthday();
}
public void person_PropertyChanged(object sender,
PropertyChangedEventArgs e)
{
txtAge.Text = person.Age.ToString();
}
private void txtAge_TextChanged(object sender, TextChangedEventArgs e)
{
int age;
if (int.TryParse(txtAge.Text, out age))
person.Age = age;
else
person.Age = -1;
}
}
}
-- HaveBirthday1.Person.cs ---------------------------------------
using System;
using System.Text;
using System.ComponentModel;
namespace HaveBirthday1
{
///
/// HaveBirthday1 Example.
/// Show how to achieve two-way data transfer between a
/// Person class object and the Age textbox without using
/// data binding.
///
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string nameField;
private string genderField;
private int ageField;
public Person(string theName, string theGender, int theAge)
{
nameField = theName;
genderField = theGender;
ageField = theAge;
}
public string Name
{
get { return nameField; }
set { nameField = value; }
}
public string Gender
{
get { return genderField; }
set { genderField = value; }
}
public int Age
{
get { return ageField; }
set { ageField = value; Notify("Age"); }
}
public void HaveBirthday()
{
Age++;
Notify("Age");
}
public override string ToString()
{
return "Name: " + Name + "\n" +
"Gender: " + Gender + "\n" +
"Age: " + Age;
}
protected void Notify(string propName)
{
if (this.PropertyChanged != null)
PropertyChanged(this,
new PropertyChangedEventArgs(propName));
}
}
}
== HaveBirthday2.Window1.xaml ====================================
-- HaveBirthday2.Window1.xaml.cs ---------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
namespace HaveBirthday2
{
///
/// HaveBirthday2 Example
/// Show two-way data binding to a class object.
/// The Age textbox is updated when the Person
/// class raises the PropertyChanged event.
///
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void btnShowPerson_Click(object sender, RoutedEventArgs e)
{
Person p = (Person)this.FindResource("alice");
MessageBox.Show(p.ToString());
}
private void btnHaveBirthday_Click(object sender, RoutedEventArgs e)
{
Person p = (Person)this.FindResource("alice");
p.HaveBirthday();
}
}
}
-- HaveBirthday2.Person.cs ---------------------------------------
using System;
using System.ComponentModel;
namespace HaveBirthday2
{
///
/// HaveBirthday2 Example.
/// Show two-way data binding to a class object.
/// The Age textbox is updated when the Person
/// class raises the PropertyChanged event.
///
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string nameField;
private string genderField;
private int ageField;
public Person()
{
nameField = "Unknown";
genderField = "U";
ageField = -1;
}
public Person(string theName, string theGender, int theAge)
{
nameField = theName;
genderField = theGender;
ageField = theAge;
}
public string Name
{
get { return nameField; }
set { nameField = value; }
}
public string Gender
{
get { return genderField; }
set { genderField = value; }
}
public int Age
{
get { return ageField; }
set { ageField = value; Notify("Age"); }
}
public void HaveBirthday()
{
Age++;
Notify("Age");
}
public override string ToString()
{
return "Name: " + Name + "\n" +
"Gender: " + Gender + "\n" +
"Age: " + Age;
}
protected void Notify(string propName)
{
if (this.PropertyChanged != null)
PropertyChanged(this,
new PropertyChangedEventArgs(propName));
}
}
}
== TicTacToe1.Window1.xaml =======================================
-- TicTacToe1.Window1.xaml.cs ------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
namespace TicTacToe1
{
///
/// TicTacToe1 Example
/// Modified from Sells and Griffiths,
/// Programming WPF, O'Reilley, 2007.
/// Show the basics of WPF styles.
///
public partial class Window1 : System.Windows.Window
{
// Track the current player (X or O)
string currentPlayer;
// Track the list of cells for finding a winner etc.
Button[] cells;
public Window1()
{
InitializeComponent();
// Cache the list of buttons and handle their clicks
this.cells = new Button[] {
this.cell00, this.cell01, this.cell02,
this.cell10, this.cell11, this.cell12,
this.cell20, this.cell21, this.cell22 };
foreach (Button cell in this.cells)
{
cell.Click += cell_Click;
}
// Initialize a new game
NewGame();
}
string CurrentPlayer
{
get { return this.currentPlayer; }
set
{
this.currentPlayer = value;
this.statusTextBlock.Text =
"It's your turn, " + this.currentPlayer;
}
}
// Use the buttons to track game state
void NewGame()
{
foreach (Button cell in this.cells)
{
cell.Content = null;
}
CurrentPlayer = "X";
}
void cell_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
// Don't let multiple clicks change the player for a cell
if (button.Content != null) { return; }
// Set button content
button.Content = CurrentPlayer;
// Check for winner or a tie
if (HasWon(this.currentPlayer))
{
MessageBox.Show("Winner!", "Game Over");
NewGame();
return;
}
else if (TieGame())
{
MessageBox.Show("No Winner!", "Game Over");
NewGame();
return;
}
// Switch player
if (CurrentPlayer == "X")
{
CurrentPlayer = "O";
}
else
{
CurrentPlayer = "X";
}
}
// Use this.cells to find a winner or a tie
bool HasWon(string player)
{
Button[,] possibleWins = {
// row
{ this.cell00, this.cell01, this.cell02, },
{ this.cell10, this.cell11, this.cell12, },
{ this.cell20, this.cell21, this.cell22, },
// column
{ this.cell00, this.cell10, this.cell20, },
{ this.cell01, this.cell11, this.cell21, },
{ this.cell02, this.cell12, this.cell22, },
// diagonal
{ this.cell00, this.cell11, this.cell22, },
{ this.cell02, this.cell11, this.cell20, },
};
for (int i = 0; i != possibleWins.GetLength(0); ++i)
{
bool hasWon = true;
for (int j = 0; j != possibleWins.GetLength(1); ++j)
{
if (possibleWins[i, j].Content == null ||
(string)possibleWins[i, j].Content != player)
{
hasWon = false;
break;
}
}
if (hasWon) { return true; }
}
return false;
}
bool TieGame()
{
foreach (Button cell in this.cells)
{
if (cell.Content == null)
{
return false;
}
}
return true;
}
}
}
== TicTacToe2.Window1.xaml =======================================
-- TicTacToe2.Window1.xaml.cs ------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
namespace TicTacToe
{
///
/// TicTacToe2 Example
/// Modified from Sells and Griffiths,
/// Programming WPF, O'Reilley
/// Show how code can interact with styles.
///
public partial class Window1 : System.Windows.Window
{
// Track the current player (X or O)
string currentPlayer;
// Track the list of cells for finding a winner etc.
Button[] cells;
public Window1()
{
InitializeComponent();
// Cache the list of buttons and handle their clicks
this.cells = new Button[] {
this.cell00, this.cell01, this.cell02,
this.cell10, this.cell11, this.cell12,
this.cell20, this.cell21, this.cell22 };
foreach (Button cell in this.cells)
{
cell.Click += cell_Click;
}
// Initialize a new game
NewGame();
}
string CurrentPlayer
{
get { return this.currentPlayer; }
set
{
this.currentPlayer = value;
this.statusTextBlock.Text = "It's your turn, " + this.currentPlayer;
}
}
// Use the buttons to track game state
void NewGame()
{
foreach (Button cell in this.cells)
{
cell.Content = null;
}
CurrentPlayer = "X";
}
void cell_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
// Don't let multiple clicks change the player for a cell
if (button.Content != null) { return; }
// Set button content
button.Content = CurrentPlayer;
// Check for winner or a tie
if (HasWon(this.currentPlayer))
{
MessageBox.Show("Winner!", "Game Over");
NewGame();
return;
}
else if (TieGame())
{
MessageBox.Show("No Winner!", "Game Over");
NewGame();
return;
}
// Switch player
if (CurrentPlayer == "X")
{
button.Style = (Style)FindResource("XStyle");
CurrentPlayer = "O";
}
else
{
button.Style = (Style)FindResource("OStyle");
CurrentPlayer = "X";
}
}
// Use this.cells to find a winner or a tie
bool HasWon(string player)
{
Button[,] possibleWins = {
// row
{ this.cell00, this.cell01, this.cell02, },
{ this.cell10, this.cell11, this.cell12, },
{ this.cell20, this.cell21, this.cell22, },
// column
{ this.cell00, this.cell10, this.cell20, },
{ this.cell01, this.cell11, this.cell21, },
{ this.cell02, this.cell12, this.cell22, },
// diagonal
{ this.cell00, this.cell11, this.cell22, },
{ this.cell02, this.cell11, this.cell20, },
};
for (int i = 0; i != possibleWins.GetLength(0); ++i)
{
bool hasWon = true;
for (int j = 0; j != possibleWins.GetLength(1); ++j)
{
if (possibleWins[i, j].Content == null ||
(string)possibleWins[i, j].Content != player)
{
hasWon = false;
break;
}
}
if (hasWon) { return true; }
}
return false;
}
bool TieGame()
{
foreach (Button cell in this.cells)
{
if (cell.Content == null)
{
return false;
}
}
return true;
}
}
}
== TicTacToe4.Window1.xaml =======================================
-- TicTacToe4.Window1.xaml.cs ------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
namespace TicTacToe4
{
///
/// TicTacToe4 Example
/// Modified from Sells and Griffiths,
/// Programming WPF, O'Reilley
/// Show how to use data templates
/// with styles.
///
public partial class Window1 : System.Windows.Window
{
// Track the current player (X or O)
string currentPlayer;
// Track the move sequence per game
int moveNumber;
// Track the list of cells for finding a winner etc.
Button[] cells;
public Window1()
{
InitializeComponent();
// Cache the list of buttons and handle their clicks
this.cells = new Button[] {
this.cell00, this.cell01, this.cell02,
this.cell10, this.cell11, this.cell12,
this.cell20, this.cell21, this.cell22 };
foreach (Button cell in this.cells)
{
cell.Click += cell_Click;
}
// Initialize a new game
NewGame();
}
string CurrentPlayer
{
get { return this.currentPlayer; }
set
{
this.currentPlayer = value;
this.statusTextBlock.Text = "It's your turn, " +
this.currentPlayer;
}
}
// Use the buttons to track game state
void NewGame()
{
foreach (Button cell in this.cells)
{
cell.Content = null;
}
CurrentPlayer = "X";
this.moveNumber = 0;
}
void cell_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
// Don't let multiple clicks change the player for a cell
if (button.Content != null) { return; }
// Set button content
//button.Content = CurrentPlayer;
button.Content = new PlayerMove(this.CurrentPlayer,
++this.moveNumber);
// Check for winner or a tie
if (HasWon(this.currentPlayer))
{
MessageBox.Show("Winner!", "Game Over");
NewGame();
return;
}
else if (TieGame())
{
MessageBox.Show("No Winner!", "Game Over");
NewGame();
return;
}
// Switch player
if (CurrentPlayer == "X")
{
CurrentPlayer = "O";
}
else
{
CurrentPlayer = "X";
}
}
// Use this.cells to find a winner or a tie
bool HasWon(string player)
{
Button[,] possibleWins = {
// row
{ this.cell00, this.cell01, this.cell02, },
{ this.cell10, this.cell11, this.cell12, },
{ this.cell20, this.cell21, this.cell22, },
// column
{ this.cell00, this.cell10, this.cell20, },
{ this.cell01, this.cell11, this.cell21, },
{ this.cell02, this.cell12, this.cell22, },
// diagonal
{ this.cell00, this.cell11, this.cell22, },
{ this.cell02, this.cell11, this.cell20, },
};
for (int i = 0; i != possibleWins.GetLength(0); ++i)
{
bool hasWon = true;
for (int j = 0; j != possibleWins.GetLength(1); ++j)
{
if (possibleWins[i, j].Content == null ||
((PlayerMove) possibleWins[i, j].Content).
PlayerName != player)
{
hasWon = false;
break;
}
}
if (hasWon) { return true; }
}
return false;
}
bool TieGame()
{
foreach (Button cell in this.cells)
{
if (cell.Content == null)
{
return false;
}
}
return true;
}
}
}
-- TicTacToe4.PlayerMove.cs --------------------------------------
using System;
using System.ComponentModel;
namespace TicTacToe4
{
///
/// TicTacToe4 Example
/// Modified from Sells and Griffiths,
/// Programming WPF, O'Reilley
/// Show how to use data templates
/// with styles.
///
public class PlayerMove : INotifyPropertyChanged
{
string playerName;
int moveNumber;
bool isPartOfWin = false;
public event PropertyChangedEventHandler PropertyChanged;
public string PlayerName
{
get { return playerName; }
set
{
if (string.Compare(playerName, value) == 0)
return;
playerName = value;
Notify("PlayerName");
}
}
public int MoveNumber
{
get { return moveNumber; }
set
{
if (moveNumber == value)
return;
moveNumber = value;
Notify("MoveNumber");
}
}
public PlayerMove(string playerName, int moveNumber)
{
this.playerName = playerName;
this.moveNumber = moveNumber;
}
public bool IsPartOfWin
{
get { return isPartOfWin; }
set
{
if (isPartOfWin == value) { return; }
isPartOfWin = value;
Notify("IsPartOfWin");
}
}
void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propName));
}
}
}
}
== TicTacToe5.Window1.xaml =======================================
-- TicTacToe5.Window1.xaml.cs ------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
namespace TicTacToe5
{
///
/// TicTacToe3 Example
/// Modified from Sells and Griffiths,
/// Programming WPF, O'Reilley
/// Show how to use data templates
/// with styles.
///
public class PlayerMove : INotifyPropertyChanged
{
string playerName;
public string PlayerName
{
get { return playerName; }
set
{
if (string.Compare(playerName, value) == 0) { return; }
playerName = value;
Notify("PlayerName");
}
}
int moveNumber;
public int MoveNumber
{
get { return moveNumber; }
set
{
if (moveNumber == value) { return; }
moveNumber = value;
Notify("MoveNumber");
}
}
bool isPartOfWin = false;
public bool IsPartOfWin
{
get { return isPartOfWin; }
set
{
if (isPartOfWin == value) { return; }
isPartOfWin = value;
Notify("IsPartOfWin");
}
}
public PlayerMove(string playerName, int moveNumber)
{
this.playerName = playerName;
this.moveNumber = moveNumber;
}
// INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propName));
}
}
}
public partial class Window1 : System.Windows.Window
{
// Track the current player (X or O)
string currentPlayer;
// Track the move sequence per game
int moveNumber;
// Track the list of cells for finding a winner etc.
Button[] cells;
public Window1()
{
InitializeComponent();
// Cache the list of buttons and handle their clicks
this.cells = new Button[] {
this.cell00, this.cell01, this.cell02,
this.cell10, this.cell11, this.cell12,
this.cell20, this.cell21, this.cell22 };
foreach (Button cell in this.cells)
{
cell.Click += cell_Click;
}
// Initialize a new game
NewGame();
}
string CurrentPlayer
{
get { return this.currentPlayer; }
set
{
this.currentPlayer = value;
this.statusTextBlock.Text = "It's your turn, " +
this.currentPlayer;
}
}
// Use the buttons to track game state
void NewGame()
{
foreach (Button cell in this.cells)
{
cell.ClearValue(Button.ContentProperty);
}
CurrentPlayer = "X";
this.moveNumber = 0;
}
void cell_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
// Don't let multiple clicks change the player for a cell
if (button.Content != null) { return; }
// Set button content
button.Content = new PlayerMove(this.CurrentPlayer,
++this.moveNumber);
// Only allow each player to have three moves on at once
Button[] currentPlayerButtons = Array.FindAll(
this.cells,
delegate(Button it) { return it.Content != null &&
((PlayerMove)it.Content).PlayerName ==
this.currentPlayer; });
if (currentPlayerButtons.Length == 4)
{
Button earliestButton = currentPlayerButtons[0];
Array.ForEach(
currentPlayerButtons,
delegate(Button it)
{
if (((PlayerMove)it.Content).MoveNumber <
((PlayerMove)earliestButton.Content).MoveNumber)
{
earliestButton = it;
}
});
earliestButton.Content = null;
}
// Check for winner or a tie
if (HasWon(this.currentPlayer))
{
MessageBox.Show("Winner!", "Game Over");
NewGame();
return;
}
else if (TieGame())
{
MessageBox.Show("No Winner!", "Game Over");
NewGame();
return;
}
// Switch player
if (CurrentPlayer == "X")
{
CurrentPlayer = "O";
}
else
{
CurrentPlayer = "X";
}
}
// Use this.cells to find a winner or a tie
bool HasWon(string player)
{
Button[,] possibleWins = {
// row
{ this.cell00, this.cell01, this.cell02, },
{ this.cell10, this.cell11, this.cell12, },
{ this.cell20, this.cell21, this.cell22, },
// column
{ this.cell00, this.cell10, this.cell20, },
{ this.cell01, this.cell11, this.cell21, },
{ this.cell02, this.cell12, this.cell22, },
// diagonal
{ this.cell00, this.cell11, this.cell22, },
{ this.cell02, this.cell11, this.cell20, },
};
for (int i = 0; i != possibleWins.GetLength(0); ++i)
{
bool hasWon = true;
for (int j = 0; j != possibleWins.GetLength(1); ++j)
{
if (possibleWins[i, j].Content == null ||
((PlayerMove)possibleWins[i, j].Content).
PlayerName != player)
{
hasWon = false;
break;
}
}
if (hasWon)
{
for (int j = 0; j != possibleWins.GetLength(1); ++j)
{
((PlayerMove)possibleWins[i, j].Content).
IsPartOfWin = true;
}
return true;
}
}
return false;
}
bool TieGame()
{
foreach (Button cell in this.cells)
{
if (cell.Content == null)
{
return false;
}
}
return true;
}
}
}
== TicTacToe6.Window1.xaml =======================================
-- TicTacToe6.Window1.xaml.cs ------------------------------------
-- ToUpper1.Window1.xaml.cs --------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.ComponentModel;
using System.Windows.Media.Effects;
namespace TicTacToe6
{
///
/// TicTacToe6 Example.
/// Modified from Sells and Griffiths,
/// Programming WPF, O'Reilley
/// Show how to use control templates.
///
///
public class PlayerMove : INotifyPropertyChanged
{
string playerName;
public string PlayerName
{
get { return playerName; }
set
{
//if (string.Compare(playerName, value) == 0) { return; }
if (playerName == value)
return;
playerName = value;
Notify("PlayerName");
}
}
int moveNumber;
public int MoveNumber
{
get { return moveNumber; }
set
{
if (moveNumber == value)
return;
moveNumber = value;
Notify("MoveNumber");
}
}
bool isPartOfWin = false;
public bool IsPartOfWin
{
get { return isPartOfWin; }
set
{
if (isPartOfWin == value) { return; }
isPartOfWin = value;
Notify("IsPartOfWin");
}
}
public PlayerMove(string playerName, int moveNumber)
{
this.playerName = playerName;
this.moveNumber = moveNumber;
}
// INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}
public partial class Window1 : System.Windows.Window
{
// Track the current player (X or O)
string currentPlayer;
// Track the move sequence per game
int moveNumber;
// Track the list of cells for finding a winner etc.
Button[] cells;
public Window1()
{
InitializeComponent();
// Cache the list of buttons and handle their clicks
this.cells = new Button[]
{
this.cell00, this.cell01, this.cell02,
this.cell10, this.cell11, this.cell12,
this.cell20, this.cell21, this.cell22
};
foreach (Button cell in this.cells)
{
cell.Click += cell_Click;
}
// Initialize a new game
NewGame();
}
string CurrentPlayer
{
get { return this.currentPlayer; }
set
{
this.currentPlayer = value;
this.statusTextBlock.Text =
"It's your turn, " + this.currentPlayer;
}
}
// Use the buttons to track game state
void NewGame()
{
foreach (Button cell in this.cells)
{
cell.Content = null;
}
CurrentPlayer = "X";
this.moveNumber = 0;
}
void cell_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
// Don't let multiple clicks change the player for a cell
if (button.Content != null) { return; }
// Set button content
button.Content = new PlayerMove(this.CurrentPlayer,
++this.moveNumber);
// Only allow each player to have three moves on at once
Button[] currentPlayerButtons = Array.FindAll(
this.cells,
delegate(Button it) { return it.Content != null &&
((PlayerMove)it.Content).PlayerName ==
this.currentPlayer; });
if (currentPlayerButtons.Length == 4)
{
Button earliestButton = currentPlayerButtons[0];
Array.ForEach(
currentPlayerButtons,
delegate(Button it)
{
if (((PlayerMove)it.Content).MoveNumber <
((PlayerMove)earliestButton.Content).MoveNumber)
{
earliestButton = it;
}
});
earliestButton.Content = null;
}
// Check for winner or a tie
if (HasWon(this.currentPlayer))
{
MessageBox.Show("Winner!", "Game Over");
NewGame();
return;
}
else if (TieGame())
{
MessageBox.Show("No Winner!", "Game Over");
NewGame();
return;
}
// Switch player
if (CurrentPlayer == "X")
{
CurrentPlayer = "O";
}
else
{
CurrentPlayer = "X";
}
}
// Use this.cells to find a winner or a tie
bool HasWon(string player)
{
Button[,] possibleWins = {
// row
{ this.cell00, this.cell01, this.cell02, },
{ this.cell10, this.cell11, this.cell12, },
{ this.cell20, this.cell21, this.cell22, },
// column
{ this.cell00, this.cell10, this.cell20, },
{ this.cell01, this.cell11, this.cell21, },
{ this.cell02, this.cell12, this.cell22, },
// diagonal
{ this.cell00, this.cell11, this.cell22, },
{ this.cell02, this.cell11, this.cell20, },
};
for (int i = 0; i != possibleWins.GetLength(0); ++i)
{
bool hasWon = true;
for (int j = 0; j != possibleWins.GetLength(1); ++j)
{
if (possibleWins[i, j].Content == null ||
((PlayerMove)possibleWins[i, j].Content).PlayerName
!= player)
{
hasWon = false;
break;
}
}
if (hasWon)
{
for (int j = 0; j != possibleWins.GetLength(1); ++j)
{
((PlayerMove)possibleWins[i, j].Content).
IsPartOfWin = true;
}
return true;
}
}
return false;
}
bool TieGame()
{
foreach (Button cell in this.cells)
{
if (cell.Content == null)
{
return false;
}
}
return true;
}
}
public class MouseOverEffectProperties
{
public static DependencyProperty MouseOverEffectProperty;
static MouseOverEffectProperties()
{
OuterGlowBitmapEffect defaultEffect = new OuterGlowBitmapEffect();
defaultEffect.GlowColor = Colors.Yellow;
defaultEffect.GlowSize = 10;
MouseOverEffectProperty =
DependencyProperty.RegisterAttached(
"MouseOverEffect",
typeof(BitmapEffect),
typeof(MouseOverEffectProperties),
new PropertyMetadata(defaultEffect));
}
public static BitmapEffect GetMouseOverEffect(DependencyObject target)
{
return (BitmapEffect)target.GetValue(MouseOverEffectProperty);
}
public static void SetMouseOverEffect(DependencyObject target,
BitmapEffect value)
{
target.SetValue(MouseOverEffectProperty, value);
}
}
}
== Document1.Window1.xaml ========================================
Lorem ipsum dolor sit amet.
ABCD
OneTwoThree
== Document2.Window1.xaml ========================================
-- Document2.Window1.xaml.cs -------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.IO;
using System.Windows.Markup;
using System.Windows.Forms;
namespace Document2
{
///
/// Document2 Example
/// Load the FlowDocument xaml file into the
/// FlowDocumentScrollViewer at runtime.
///
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
FileStream fs = new FileStream("../../sample1.xaml",
FileMode.Open, FileAccess.Read);
FlowDocument content = XamlReader.Load(fs) as FlowDocument;
viewer.Document = content;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
FileDialog dialog = new OpenFileDialog();
dialog.ShowDialog();
FileStream fs = new FileStream(dialog.FileName,
FileMode.Open, FileAccess.Read);
FlowDocument content = XamlReader.Load(fs) as FlowDocument;
viewer.Document = content;
}
}
}
-- sample1.xaml --------------------------------------------------
This is a test.
-- sample2.xaml --------------------------------------------------
Lorem ipsum dolor sit amet.