<|start_filename|>Animation/AnimationExamples/ElasticDoubleAnimation.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace AnimationExamples
{
    /// <summary>
    ///     ElasticDoubleAnimation - like something attached to a rubber band
    /// </summary>
    public class ElasticDoubleAnimation : DoubleAnimationBase
    {
        public enum EdgeBehaviorEnum
        {
            EaseIn,
            EaseOut,
            EaseInOut
        }

        public static readonly DependencyProperty EdgeBehaviorProperty =
            DependencyProperty.Register("EdgeBehavior", typeof (EdgeBehaviorEnum), typeof (ElasticDoubleAnimation),
                new PropertyMetadata(EdgeBehaviorEnum.EaseIn));

        public static readonly DependencyProperty SpringinessProperty =
            DependencyProperty.Register("Springiness", typeof (double), typeof (ElasticDoubleAnimation),
                new PropertyMetadata(3.0));

        public static readonly DependencyProperty OscillationsProperty =
            DependencyProperty.Register("Oscillations", typeof (double), typeof (ElasticDoubleAnimation),
                new PropertyMetadata(10.0));

        public static readonly DependencyProperty FromProperty =
            DependencyProperty.Register("From",
                typeof (double?),
                typeof (ElasticDoubleAnimation),
                new PropertyMetadata(null));

        public static readonly DependencyProperty ToProperty =
            DependencyProperty.Register("To",
                typeof (double?),
                typeof (ElasticDoubleAnimation),
                new PropertyMetadata(null));

        /// <summary>
        ///     which side gets the effect
        /// </summary>
        public EdgeBehaviorEnum EdgeBehavior
        {
            get { return (EdgeBehaviorEnum) GetValue(EdgeBehaviorProperty); }
            set { SetValue(EdgeBehaviorProperty, value); }
        }

        /// <summary>
        ///     how much springiness is there in the effect
        /// </summary>
        public double Springiness
        {
            get { return (double) GetValue(SpringinessProperty); }
            set { SetValue(SpringinessProperty, value); }
        }

        /// <summary>
        ///     number of oscillations in the effect
        /// </summary>
        public double Oscillations
        {
            get { return (double) GetValue(OscillationsProperty); }
            set { SetValue(OscillationsProperty, value); }
        }

        /// <summary>
        ///     Specifies the starting value of the animation.
        /// </summary>
        public double? From
        {
            get { return (double?) GetValue(FromProperty); }
            set { SetValue(FromProperty, value); }
        }

        /// <summary>
        ///     Specifies the ending value of the animation.
        /// </summary>
        public double? To
        {
            get { return (double?) GetValue(ToProperty); }
            set { SetValue(ToProperty, value); }
        }

        protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue,
            AnimationClock clock)
        {
            double returnValue;
            var start = From ?? defaultOriginValue;
            var delta = To - start ?? defaultOriginValue - start;
            switch (EdgeBehavior)
            {
                case EdgeBehaviorEnum.EaseIn:
                    returnValue = EaseIn(clock.CurrentProgress.Value, start, delta, Springiness, Oscillations);
                    break;
                case EdgeBehaviorEnum.EaseOut:
                    returnValue = EaseOut(clock.CurrentProgress.Value, start, delta, Springiness, Oscillations);
                    break;
                default:
                    returnValue = EaseInOut(clock.CurrentProgress.Value, start, delta, Springiness, Oscillations);
                    break;
            }
            return returnValue;
        }

        protected override Freezable CreateInstanceCore() => new ElasticDoubleAnimation();

        private static double EaseOut(double timeFraction, double start, double delta, double springiness,
            double oscillations)
        {
            // math magic: The cosine gives us the right wave, the timeFraction * the # of oscillations is the 
            // frequency of the wave, and the amplitude (the exponent) makes the wave get smaller at the end
            // by the "springiness" factor. This is extremely similar to the bounce equation.
            var returnValue = Math.Pow((1 - timeFraction), springiness)
                              *Math.Cos(2*Math.PI*timeFraction*oscillations);
            returnValue = delta - (returnValue*delta);
            returnValue += start;
            return returnValue;
        }

        private static double EaseIn(double timeFraction, double start, double delta, double springiness,
            double oscillations)
        {
            // math magic: The cosine gives us the right wave, the timeFraction * the # of oscillations is the 
            // frequency of the wave, and the amplitude (the exponent) makes the wave get smaller at the beginning
            // by the "springiness" factor. This is extremely similar to the bounce equation. 
            var returnValue = Math.Pow((timeFraction), springiness)
                              *Math.Cos(2*Math.PI*timeFraction*oscillations);
            returnValue = returnValue*delta;
            returnValue += start;
            return returnValue;
        }

        private static double EaseInOut(double timeFraction, double start, double delta, double springiness,
            double oscillations)
        {
            double returnValue;

            // we cut each effect in half by multiplying the time fraction by two and halving the distance.
            if (timeFraction <= 0.5)
            {
                return EaseIn(timeFraction*2, start, delta/2, springiness, oscillations);
            }
            returnValue = EaseOut((timeFraction - 0.5)*2, start, delta/2, springiness, oscillations);
            returnValue += (delta/2);
            return returnValue;
        }
    }
}

<|start_filename|>Data Binding/CollectionViewSource/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace CollectionViewSource
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/main.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: DLL Entrypoint for TestCodec
//----------------------------------------------------------------------------------------
#include "precomp.hpp"

HINSTANCE g_DllInstance;
TestCodecsRegistryManager rvm;

extern "C"
STDAPI DllRegisterServer()
{    
    rvm.Register();
    return S_OK;
}

extern "C"
STDAPI DllUnregisterServer()
{ 
    rvm.Unregister();
    return S_OK;
}

extern "C"
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppv)
{
    HRESULT result = E_INVALIDARG; 

    if (NULL != ppv)
    {
        IClassFactory *classFactory = NULL;
        if (CLSID_YCbCrPixelFormatConverter == rclsid)
        {
            result = S_OK;
            classFactory = new TestClassFactory<YCbCrPixelFormatConverter>();
        }
        else if (CLSID_CmykPixelFormatConverter == rclsid)
        {
            result = S_OK;
            classFactory = new TestClassFactory<CmykPixelFormatConverter>();
        }
        else if (CLSID_AitDecoder == rclsid)
        {
            result = S_OK;
            classFactory = new TestClassFactory<AitDecoder>();
        }
        else if (CLSID_AitEncoder == rclsid)
        {
            result = S_OK;
            classFactory = new TestClassFactory<AitEncoder>();
        }        
        else
        {
            result = E_NOINTERFACE;
        }

        if (SUCCEEDED(result))
        {
            if (NULL != classFactory)
            {
                result = classFactory->QueryInterface(riid, ppv);
            }
            else
            {
                result = E_OUTOFMEMORY;
            }
        }
    }
    return result;    
}

extern "C"
BOOL DllMain(HINSTANCE hinstDLL, ULONG fdwReason, LPVOID *lpvReserved)
{
    BOOL result = TRUE;

    switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
        g_DllInstance = hinstDLL;
        DisableThreadLibraryCalls(hinstDLL);
        break;

    case DLL_PROCESS_DETACH:
        break;
    }

    return result;
}

<|start_filename|>Application Management/SingleInstanceDetection/SingleInstanceApplication.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace SingleInstanceDetection
{
    public class SingleInstanceApplication : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Create and show the application's main window
            var window = new MainWindow();
            window.Show();
        }

        public void Activate()
        {
            // Reactivate application's main window
            MainWindow.Activate();
        }
    }
}

<|start_filename|>Graphics/Brushes/SampleViewer.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Xml;

namespace Brushes
{
    /// <summary>
    ///     Interaction logic for SampleViewer.xaml
    /// </summary>
    public partial class SampleViewer : Page
    {
        public static RoutedUICommand ExitCommand =
            new RoutedUICommand("Exit", "Exit", typeof (SampleViewer));

        public SampleViewer()
        {
            InitializeComponent();
        }

        private void TransitionAnimationStateChanged(object sender, EventArgs args)
        {
            var transitionAnimationClock = (AnimationClock) sender;
            if (transitionAnimationClock.CurrentState == ClockState.Filling)
            {
                FadeEnded();
            }
        }

        private void MyFrameNavigated(object sender, NavigationEventArgs args)
        {
            var myFadeInAnimation = (DoubleAnimation) Resources["MyFadeInAnimationResource"];
            myFrame.BeginAnimation(OpacityProperty, myFadeInAnimation, HandoffBehavior.SnapshotAndReplace);
        }

        private void FadeEnded()
        {
            var el = (XmlElement) myPageList.SelectedItem;
            var att = el.Attributes["Uri"];
            if (att != null)
            {
                myFrame.Navigate(new Uri(att.Value, UriKind.Relative));
            }
            else
            {
                myFrame.Content = null;
            }
        }

        private void ExecuteExitCommand(object sender, ExecutedRoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}

<|start_filename|>Data Binding/SortFilter/Orders.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;

namespace SortFilter
{
    // Create the collection of Order objects
    public class Orders : ObservableCollection<Order>
    {
        public Order O1 = new Order(1001, 5682, "Blue Sweater", 44, "Yes", new DateTime(2003, 1, 23),
            new DateTime(2003, 2, 4));

        public Order O2 = new Order(1002, 2211, "Gray Jacket Long", 181, "No", new DateTime(2003, 2, 14));

        public Order O3 = new Order(1003, 5682, "Brown Pant W", 02, "Yes", new DateTime(2002, 12, 20),
            new DateTime(2003, 1, 13));

        public Order O4 = new Order(1004, 3143, "Orange T-shirt", 205, "No", new DateTime(2003, 1, 28));

        public Orders()
        {
            Add(O1);
            Add(O2);
            Add(O3);
            Add(O4);
        }
    }
}

<|start_filename|>Migration and Interoperability/HWNDInWPF/hwndinwpf/resource.h<|end_filename|>
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by TypicalWin32Dialog.rc
//
#define IDC_MYICON                      2
#define IDD_TYPICALWIN32DIALOG_DIALOG   102
#define IDS_APP_TITLE                   103
#define IDD_ABOUTBOX                    103
#define IDM_ABOUT                       104
#define IDM_EXIT                        105
#define IDI_TYPICALWIN32DIALOG          107
#define IDI_SMALL                       108
#define IDC_TYPICALWIN32DIALOG          109
#define IDR_MAINFRAME                   128
#define IDD_DIALOG1                     129
#define IDC_STATIC                      -1

#define IDC_EDIT1                       1001
#define IDC_EDIT2                       1002
#define IDC_EDIT3                       1003
#define IDC_EDIT4                       1004
#define IDC_EDIT5                       1005
#define IDC_EDIT6                       1006
#define IDC_EDIT7                       1007
#define IDC_MONTHCALENDAR1              1008
#define IDC_SPIN1                       1009
#define ID_EDIT_CUT                     32771
#define ID_EDIT_COPY                    32772
#define ID_EDIT_PASTE                   32773
#define ID_EDIT_SAVE                    32774
#define ID_EDIT_CANCEL                  32775
#define ID_FILE_OPEN                    32776
#define ID_FILE_SAVE                    32777
#define ID_FILE_NEW                     32778
#define ID_FILE_SAVEAS                  32779
#define IDC_STATIC                      -1

// Next default values for new objects
// 
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC                     1
#define _APS_NEXT_RESOURCE_VALUE        130
#define _APS_NEXT_COMMAND_VALUE         32771
#define _APS_NEXT_CONTROL_VALUE         1000
#define _APS_NEXT_SYMED_VALUE           110
#endif
#endif


<|start_filename|>Migration and Interoperability/WpfHostingWindowsFormsControl/FormsControlLibrary/MyControl.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace MyControls
{
    /// <summary>
    ///     Summary description for UserControl1.
    /// </summary>
    public class MyControl : UserControl
    {
        public delegate void MyControlEventHandler(object sender, MyControlEventArgs args);

        /// <summary>
        ///     Required designer variable.
        /// </summary>
        private readonly IContainer components = null;

        private Label _label1;
        private Label _label2;
        private Button _btnCancel;
        private Button _btnOk;
        private Label _label3;
        private Label _label4;
        private Label _label5;
        private Label _label6;
        private TextBox _txtAddress;
        private TextBox _txtCity;
        private TextBox _txtName;
        private TextBox _txtState;
        private TextBox _txtZip;

        public MyControl()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();

            // TODO: Add any initialization after the InitComponent call
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                components?.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        ///     Required method for Designer support - do not modify
        ///     the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this._label1 = new System.Windows.Forms.Label();
            this._label2 = new System.Windows.Forms.Label();
            this._label3 = new System.Windows.Forms.Label();
            this._label4 = new System.Windows.Forms.Label();
            this._label5 = new System.Windows.Forms.Label();
            this._txtName = new System.Windows.Forms.TextBox();
            this._txtAddress = new System.Windows.Forms.TextBox();
            this._txtCity = new System.Windows.Forms.TextBox();
            this._txtState = new System.Windows.Forms.TextBox();
            this._txtZip = new System.Windows.Forms.TextBox();
            this._btnOk = new System.Windows.Forms.Button();
            this._btnCancel = new System.Windows.Forms.Button();
            this._label6 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // label1
            // 
            this._label1.Location = new System.Drawing.Point(20, 46);
            this._label1.Margin = new System.Windows.Forms.Padding(3, 3, 3, 1);
            this._label1.Name = "_label1";
            this._label1.Size = new System.Drawing.Size(65, 16);
            this._label1.TabIndex = 8;
            this._label1.Text = "Name";
            this._label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label2
            // 
            this._label2.Location = new System.Drawing.Point(20, 88);
            this._label2.Name = "_label2";
            this._label2.Size = new System.Drawing.Size(94, 13);
            this._label2.TabIndex = 9;
            this._label2.Text = "Street Address";
            this._label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label3
            // 
            this._label3.Location = new System.Drawing.Point(20, 127);
            this._label3.Margin = new System.Windows.Forms.Padding(3, 3, 3, 2);
            this._label3.Name = "_label3";
            this._label3.Size = new System.Drawing.Size(49, 13);
            this._label3.TabIndex = 10;
            this._label3.Text = "City";
            this._label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label4
            // 
            this._label4.Location = new System.Drawing.Point(246, 127);
            this._label4.Margin = new System.Windows.Forms.Padding(3, 0, 3, 3);
            this._label4.Name = "_label4";
            this._label4.Size = new System.Drawing.Size(47, 13);
            this._label4.TabIndex = 11;
            this._label4.Text = "State";
            this._label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label5
            // 
            this._label5.Location = new System.Drawing.Point(23, 167);
            this._label5.Margin = new System.Windows.Forms.Padding(3, 3, 2, 3);
            this._label5.Name = "_label5";
            this._label5.Size = new System.Drawing.Size(46, 13);
            this._label5.TabIndex = 12;
            this._label5.Text = "Zip";
            this._label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // txtName
            // 
            this._txtName.Location = new System.Drawing.Point(135, 44);
            this._txtName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 3);
            this._txtName.Name = "_txtName";
            this._txtName.Size = new System.Drawing.Size(199, 20);
            this._txtName.TabIndex = 0;
            // 
            // txtAddress
            // 
            this._txtAddress.Location = new System.Drawing.Point(136, 84);
            this._txtAddress.Margin = new System.Windows.Forms.Padding(3, 1, 3, 3);
            this._txtAddress.Name = "_txtAddress";
            this._txtAddress.Size = new System.Drawing.Size(198, 20);
            this._txtAddress.TabIndex = 1;
            // 
            // txtCity
            // 
            this._txtCity.Location = new System.Drawing.Point(136, 123);
            this._txtCity.Name = "_txtCity";
            this._txtCity.TabIndex = 2;
            // 
            // txtState
            // 
            this._txtState.Location = new System.Drawing.Point(300, 123);
            this._txtState.Name = "_txtState";
            this._txtState.Size = new System.Drawing.Size(33, 20);
            this._txtState.TabIndex = 3;
            // 
            // txtZip
            // 
            this._txtZip.Location = new System.Drawing.Point(135, 163);
            this._txtZip.Margin = new System.Windows.Forms.Padding(1, 3, 3, 3);
            this._txtZip.Name = "_txtZip";
            this._txtZip.TabIndex = 4;
            // 
            // btnOK
            // 
            this._btnOk.Location = new System.Drawing.Point(23, 207);
            this._btnOk.Margin = new System.Windows.Forms.Padding(3, 3, 3, 1);
            this._btnOk.Name = "_btnOk";
            this._btnOk.TabIndex = 5;
            this._btnOk.Text = "OK";
            this._btnOk.Click += new System.EventHandler(this.OKButton_Click);
            // 
            // btnCancel
            // 
            this._btnCancel.Location = new System.Drawing.Point(157, 207);
            this._btnCancel.Name = "_btnCancel";
            this._btnCancel.TabIndex = 6;
            this._btnCancel.Text = "Cancel";
            this._btnCancel.Click += new System.EventHandler(this.CancelButton_Click);
            // 
            // label6
            // 
            this._label6.Location = new System.Drawing.Point(66, 12);
            this._label6.Name = "_label6";
            this._label6.Size = new System.Drawing.Size(226, 23);
            this._label6.TabIndex = 13;
            this._label6.Text = "Simple Windows Forms Control";
            this._label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // MyControl1
            // 
            this.Controls.Add(this._label6);
            this.Controls.Add(this._btnCancel);
            this.Controls.Add(this._btnOk);
            this.Controls.Add(this._txtZip);
            this.Controls.Add(this._txtState);
            this.Controls.Add(this._txtCity);
            this.Controls.Add(this._txtAddress);
            this.Controls.Add(this._txtName);
            this.Controls.Add(this._label5);
            this.Controls.Add(this._label4);
            this.Controls.Add(this._label3);
            this.Controls.Add(this._label2);
            this.Controls.Add(this._label1);
            this.Name = "MyControl1";
            this.Size = new System.Drawing.Size(359, 244);
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        #endregion

        public event MyControlEventHandler OnButtonClick;

        private void OKButton_Click(object sender, EventArgs e)
        {
            var retvals = new MyControlEventArgs(true,
                _txtName.Text,
                _txtAddress.Text,
                _txtCity.Text,
                _txtState.Text,
                _txtZip.Text);
            OnButtonClick(this, retvals);
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            var retvals = new MyControlEventArgs(false,
                _txtName.Text,
                _txtAddress.Text,
                _txtCity.Text,
                _txtState.Text,
                _txtZip.Text);
            OnButtonClick(this, retvals);
        }
    }
}

// </snippet1>

<|start_filename|>Accessibility/SelectionPattern/SelectionTarget/Target.designer.cs<|end_filename|>
namespace SelectionPatternTarget
{
    /// <summary>
    /// The target application for the SelectionPattern Sample.
    /// </summary>
    partial class Target
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem("Item1");
            System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem("Item2");
            System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem("Item3");
            System.Windows.Forms.ListViewItem listViewItem4 = new System.Windows.Forms.ListViewItem("Item4");
            System.Windows.Forms.ListViewItem listViewItem5 = new System.Windows.Forms.ListViewItem("Item5");
            System.Windows.Forms.ListViewItem listViewItem6 = new System.Windows.Forms.ListViewItem("Item6");
            this.ListBox = new System.Windows.Forms.ListBox();
            this.ListView = new System.Windows.Forms.ListView();
            this.ComboBox = new System.Windows.Forms.ComboBox();
            this.CheckedListBox = new System.Windows.Forms.CheckedListBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.groupBox4 = new System.Windows.Forms.GroupBox();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.groupBox4.SuspendLayout();
            this.SuspendLayout();
            // 
            // ListBox
            // 
            this.ListBox.FormattingEnabled = true;
            this.ListBox.Items.AddRange(new object[] {
            "Item1",
            "Item2",
            "Item3",
            "Item4",
            "Item5",
            "Item6"});
            this.ListBox.Location = new System.Drawing.Point(36, 25);
            this.ListBox.Name = "ListBox";
            this.ListBox.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
            this.ListBox.Size = new System.Drawing.Size(121, 95);
            this.ListBox.TabIndex = 0;
            // 
            // ListView
            // 
            this.ListView.HideSelection = false;
            listViewItem1.Checked = true;
            listViewItem1.StateImageIndex = 1;
            listViewItem1.Tag = "";
            this.ListView.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
            listViewItem1,
            listViewItem2,
            listViewItem3,
            listViewItem4,
            listViewItem5,
            listViewItem6});
            this.ListView.Location = new System.Drawing.Point(27, 28);
            this.ListView.Name = "ListView";
            this.ListView.Size = new System.Drawing.Size(150, 86);
            this.ListView.TabIndex = 1;
            this.ListView.UseCompatibleStateImageBehavior = false;
            // 
            // ComboBox
            // 
            this.ComboBox.FormattingEnabled = true;
            this.ComboBox.Items.AddRange(new object[] {
            "Item1",
            "Item2",
            "Item3",
            "Item4",
            "Item5",
            "Item6"});
            this.ComboBox.Location = new System.Drawing.Point(36, 28);
            this.ComboBox.Name = "ComboBox";
            this.ComboBox.Size = new System.Drawing.Size(121, 21);
            this.ComboBox.TabIndex = 2;
            // 
            // CheckedListBox
            // 
            this.CheckedListBox.CheckOnClick = true;
            this.CheckedListBox.FormattingEnabled = true;
            this.CheckedListBox.Items.AddRange(new object[] {
            "CheckBoxItem1",
            "CheckBoxItem2",
            "CheckBoxItem3",
            "CheckBoxItem4",
            "CheckBoxItem5",
            "CheckBoxItem6"});
            this.CheckedListBox.Location = new System.Drawing.Point(27, 26);
            this.CheckedListBox.Name = "CheckedListBox";
            this.CheckedListBox.Size = new System.Drawing.Size(120, 94);
            this.CheckedListBox.TabIndex = 3;
            this.CheckedListBox.UseWaitCursor = true;
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.ListView);
            this.groupBox1.Location = new System.Drawing.Point(242, 29);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(200, 134);
            this.groupBox1.TabIndex = 4;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "ListView";
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.CheckedListBox);
            this.groupBox2.Location = new System.Drawing.Point(23, 29);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(200, 134);
            this.groupBox2.TabIndex = 5;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "CheckedListBox";
            // 
            // groupBox3
            // 
            this.groupBox3.Controls.Add(this.ComboBox);
            this.groupBox3.Location = new System.Drawing.Point(23, 181);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(200, 134);
            this.groupBox3.TabIndex = 6;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "ComboBox";
            // 
            // groupBox4
            // 
            this.groupBox4.Controls.Add(this.ListBox);
            this.groupBox4.Location = new System.Drawing.Point(242, 181);
            this.groupBox4.Name = "groupBox4";
            this.groupBox4.Size = new System.Drawing.Size(200, 134);
            this.groupBox4.TabIndex = 7;
            this.groupBox4.TabStop = false;
            this.groupBox4.Text = "ListBox";
            // 
            // Target
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(459, 338);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox4);
            this.Name = "Target";
            this.Text = "SelectionPatternTarget";
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.groupBox3.ResumeLayout(false);
            this.groupBox4.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ListBox ListBox;
        private System.Windows.Forms.ListView ListView;
        private System.Windows.Forms.ComboBox ComboBox;
        private System.Windows.Forms.CheckedListBox CheckedListBox;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.GroupBox groupBox4;
    }
}



<|start_filename|>Tools/BamlReflector/BamlTools/BamlRecords.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace BamlTools
{
    // Some of the records are "Not Implemented" this means there really is no
    // such record.  Some of the records are "Unused" because the BamlWriter doesn't
    // actually write them.
    public enum BamlRecordType : byte
    {
        Unknown = 0,
        DocumentStart,              // 1
        DocumentEnd,                // 2
        ElementStart,               // 3
        ElementEnd,                 // 4
        Property,                   // 5
        PropertyCustom,             // 6
        PropertyComplexStart,       // 7
        PropertyComplexEnd,         // 8
        PropertyArrayStart,         // 9
        PropertyArrayEnd,           // 10
        PropertyIListStart,         // 11
        PropertyIListEnd,           // 12
        PropertyIDictionaryStart,   // 13
        PropertyIDictionaryEnd,     // 14
        LiteralContent,             // 15
        Text,                       // 16
        TextWithConverter,          // 17
        RoutedEvent,                // 18       UNUSED
        ClrEvent,                   // 19       NOT IMPLEMENTED in Avalon
        XmlnsProperty,              // 20
        XmlAttribute,               // 21       NOT IMPLEMENTED in Avalon
        ProcessingInstruction,      // 22       NOT IMPLEMENTED in Avalon
        Comment,                    // 23       NOT IMPLEMENTED in Avalon
        DefTag,                     // 24       NOT IMPLEMENTED in Avalon
        DefAttribute,               // 25
        EndAttributes,              // 26       NOT IMPLEMENTED in Avalon
        PIMapping,                  // 27
        AssemblyInfo,               // 28
        TypeInfo,                   // 29
        TypeSerializerInfo,         // 30
        AttributeInfo,              // 31
        StringInfo,                 // 32
        PropertyStringReference,    // 33       UNUSED
        PropertyTypeReference,      // 34
        PropertyWithExtension,      // 35
        PropertyWithConverter,      // 36
        DeferableContentStart,      // 37
        DefAttributeKeyString,      // 38
        DefAttributeKeyType,        // 39
        KeyElementStart,            // 40
        KeyElementEnd,              // 41
        ConstructorParametersStart, // 42
        ConstructorParametersEnd,   // 43
        ConstructorParameterType,   // 44
        ConnectionId,               // 45
        ContentProperty,            // 46
        NamedElementStart,          // 47
        StaticResourceStart,        // 48
        StaticResourceEnd,          // 49
        StaticResourceId,           // 50
        TextWithId,                 // 51
        PresentationOptionsAttribute,// 52
        LineNumberAndPosition,      // 53
        LinePosition,               // 54
        OptimizedStaticResource,     // 55,
        PropertyWithStaticResourceId,// 56,
        LastRecordType
    }


    public class MockFormatVersion
    {
        // the real format version is Window Internal.
        // But we don't need the real type, we just need a unique type to standin for it.
    }

    public class DataFormatVersion
    {
        public string name;
        public int readerVersion;
        public int updateVersion;
        public int writerVersion;
    }

    [Flags]
    public enum BamlRecordFlags
    {
        None = 0x0,
        Start = 0x01,
        End = 0x02,
        Table = 0x04,
        Debug = 0x08
    }

    public class BamlRecord
    {
        private BamlRecordType _recordId;
        private bool _isVariableSize;
        private BamlRecordFlags _flags;
        private BamlField[] _fields;

        public BamlRecord(BamlRecordType recordId, bool isVariableSize, BamlRecordFlags flags, BamlField[] fields)
        {
            if (null == fields)
            {
                throw new ArgumentNullException("fields");
            }
            if (recordId <= BamlRecordType.Unknown || recordId >= BamlRecordType.LastRecordType)
            {
                throw new ArgumentOutOfRangeException("BamlRecordType recordId");
            }
            _recordId = recordId;
            _flags = flags;
            _isVariableSize = isVariableSize;
            _fields = fields;
        }

        public BamlRecord Clone()
        {
            return new BamlRecord(_recordId, _isVariableSize, _flags, (BamlField[])_fields.Clone());
        }

        public BamlRecordType Id
        {
            get { return _recordId; }
        }

        public bool IsVariableSize
        {
            get { return _isVariableSize; }
        }

        public BamlRecordFlags Flags
        {
            get { return _flags; }
        }

        public BamlField[] Fields
        {
            get { return _fields; }
        }
    }

    class StaticBamlRecords
    {
        private static BamlRecord[] _records;

        public static BamlRecord GetRecord(BamlRecordType recordId)
        {
            BamlRecord rec = _records[(int)recordId];
            return rec.Clone();
        }

        static StaticBamlRecords()
        {
            BamlRecordType recordId;
            BamlField[] fields;

            _records = new BamlRecord[(int)BamlRecordType.LastRecordType];

            // DocumentStart = 1
            recordId = BamlRecordType.DocumentStart;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.LoadAsync),
                new BamlField(BamlFieldType.MaxAsyncRecords),
                new BamlField(BamlFieldType.DebugBamlStream),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // DocumentEnd = 2
            recordId = BamlRecordType.DocumentEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // ElementStart = 3
            recordId = BamlRecordType.ElementStart;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.TypeId),
                new BamlField(BamlFieldType.FlagsByte),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // ElementEnd = 4
            recordId = BamlRecordType.ElementEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // Property = 5
            recordId = BamlRecordType.Property;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.Value),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // PropertyCustom = 6
            recordId = BamlRecordType.PropertyCustom;
            fields = new BamlField[]             // same interface as Property 
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.SerializerTypeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // PropertyComplexStart = 7
            recordId = BamlRecordType.PropertyComplexStart;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // PropertyComplexEnd = 8
            recordId = BamlRecordType.PropertyComplexEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // PropertyArrayStart = 9
            recordId = BamlRecordType.PropertyArrayStart;
            fields = new BamlField[]           // based on ComplexPropertyStart
            {
                new BamlField(BamlFieldType.AttributeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // PropertyArrayEnd = 10
            recordId = BamlRecordType.PropertyArrayEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // PropertyIListStart = 11
            recordId = BamlRecordType.PropertyIListStart;
            fields = new BamlField[]           // based on ComplexPropertyStart
            {
                new BamlField(BamlFieldType.AttributeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // PropertyIListEnd = 12
            recordId = BamlRecordType.PropertyIListEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // PropertyIDictionaryStart = 13
            recordId = BamlRecordType.PropertyIDictionaryStart;
            fields = new BamlField[]           // based on PropertyComplexStart
            {
                new BamlField(BamlFieldType.AttributeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // PropertyIDictionaryEnd = 14
            recordId = BamlRecordType.PropertyIDictionaryEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // LiteralContent = 15
            recordId = BamlRecordType.LiteralContent;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.Value),
                new BamlField(BamlFieldType.LineNumber),
                new BamlField(BamlFieldType.LinePosition),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // Text =16
            recordId = BamlRecordType.Text;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.Value),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // TextWithConverter = 17
            recordId = BamlRecordType.TextWithConverter;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.Value),
                new BamlField(BamlFieldType.ConverterTypeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // RoutedEvent = 18                     UNUSED
            recordId = BamlRecordType.RoutedEvent;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.Value),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // ClrEvent = 19                        NOT IMPLEMENTED in Avalon
            recordId = BamlRecordType.ClrEvent;
            fields = new BamlField[] {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // XmlnsProperty = 20
            recordId = BamlRecordType.XmlnsProperty;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.NamespacePrefix),
                new BamlField(BamlFieldType.Value),
                new BamlField(BamlFieldType.AssemblyIdList),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // XmlAttribute = 21                     NOT IMPLEMENTED in Avalon
            recordId = BamlRecordType.XmlAttribute;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // ProcessingInstruction = 22            NOT IMPLEMENTED in Avalon
            recordId = BamlRecordType.ProcessingInstruction;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // Comment = 23                          NOT IMPLEMENTED in Avalon
            recordId = BamlRecordType.Comment;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // DefTag = 24                           NOT IMPLEMENTED in Avalon
            recordId = BamlRecordType.DefTag;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // DefAttribute = 25
            recordId = BamlRecordType.DefAttribute;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.Value),
                new BamlField(BamlFieldType.NameId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // EndAttributes = 26                    NOT IMPLEMENTED in Avalon
            recordId = BamlRecordType.EndAttributes;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // PIMapping = 27
            recordId = BamlRecordType.PIMapping;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.XmlNamespace),
                new BamlField(BamlFieldType.ClrNamespace),
                new BamlField(BamlFieldType.AssemblyId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // AssemblyInfo = 28
            recordId = BamlRecordType.AssemblyInfo;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AssemblyId),
                new BamlField(BamlFieldType.AssemblyFullName),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // TypeInfo = 29
            recordId = BamlRecordType.TypeInfo;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.TypeId),
                new BamlField(BamlFieldType.AssemblyId),
                new BamlField(BamlFieldType.TypeFullName),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // TypeSerializerInfo = 30
            recordId = BamlRecordType.TypeSerializerInfo;
            fields = new BamlField[]  //                       based on TypeInfo
            {
                new BamlField(BamlFieldType.TypeId),
                new BamlField(BamlFieldType.AssemblyId),
                new BamlField(BamlFieldType.TypeFullName),
                new BamlField(BamlFieldType.SerializerTypeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // AttributeInfo = 31
            recordId = BamlRecordType.AttributeInfo;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId, "NewAttributeId"),
                new BamlField(BamlFieldType.TypeId, "OwnerTypeId"),
                new BamlField(BamlFieldType.AttributeUsage),
                new BamlField(BamlFieldType.Value, "NewAttributeValue"),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // StringInfo = 32
            recordId = BamlRecordType.StringInfo;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.StringId),
                new BamlField(BamlFieldType.Value),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Table, fields);

            // PropertyStringReference = 33                 UNUSED
            recordId = BamlRecordType.PropertyStringReference;
            fields = new BamlField[]           // based on PropertyComplexStart
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.StringId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // PropertyTypeReference = 34
            recordId = BamlRecordType.PropertyTypeReference;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.TypeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // PropertyWithExtension = 35
            recordId = BamlRecordType.PropertyWithExtension;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.ExtensionTypeId),
                new BamlField(BamlFieldType.ValueId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // PropertyWithConverter = 36
            recordId = BamlRecordType.PropertyWithConverter;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.Value),
                new BamlField(BamlFieldType.ConverterTypeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // DeferableContentStart = 37
            recordId = BamlRecordType.DeferableContentStart;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.ContentSize),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Table, fields);

            // DefAttributeKeyString = 38
            recordId = BamlRecordType.DefAttributeKeyString;
            fields = new BamlField[]
            {
                // the "value" is not serialized on this record.
                new BamlField(BamlFieldType.ValueId),
                new BamlField(BamlFieldType.ValuePosition),
                new BamlField(BamlFieldType.Shared),
                new BamlField(BamlFieldType.SharedSet),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // DefAttributeKeyType = 39
            recordId = BamlRecordType.DefAttributeKeyType;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.TypeId),
                new BamlField(BamlFieldType.FlagsByte),
                new BamlField(BamlFieldType.ValuePosition),
                new BamlField(BamlFieldType.Shared),
                new BamlField(BamlFieldType.SharedSet),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // KeyElementStart = 40
            recordId = BamlRecordType.KeyElementStart;
            fields = new BamlField[]        // same as DefAttributeKeyType
            {
                new BamlField(BamlFieldType.TypeId),
                new BamlField(BamlFieldType.ValuePosition),
                new BamlField(BamlFieldType.FlagsByte),
                new BamlField(BamlFieldType.Shared),
                new BamlField(BamlFieldType.SharedSet),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // KeyElementEnd = 41
            recordId = BamlRecordType.KeyElementEnd;
            fields = new BamlField[]         // same as ElementEnd
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // ConstructorParametersStart=  42
            recordId = BamlRecordType.ConstructorParametersStart;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // ConstructorParametersEnd = 43
            recordId = BamlRecordType.ConstructorParametersEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // ConstructorParameterType = 44
            recordId = BamlRecordType.ConstructorParameterType;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.TypeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // ConnectionId = 45
            recordId = BamlRecordType.ConnectionId;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.ConnectionId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // ContentProperty = 46
            recordId = BamlRecordType.ContentProperty;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // NamedElementStart = 47
            recordId = BamlRecordType.NamedElementStart;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.TypeId),
                new BamlField(BamlFieldType.RuntimeName),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.Start, fields);

            // StaticResourceStart = 48
            recordId = BamlRecordType.StaticResourceStart;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.TypeId),
                new BamlField(BamlFieldType.FlagsByte),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Start, fields);

            // StaticResourceEnd = 49
            recordId = BamlRecordType.StaticResourceEnd;
            fields = new BamlField[]
            {
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.End, fields);

            // StaticResourceId = 50
            recordId = BamlRecordType.StaticResourceId;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.StaticResourceId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // TextWithId = 51
            recordId = BamlRecordType.TextWithId;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.ValueId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // PresentationOptionsAttribute = 52
            recordId = BamlRecordType.PresentationOptionsAttribute;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.Value),
                new BamlField(BamlFieldType.NameId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, true, BamlRecordFlags.None, fields);

            // LineNumber = 53
            recordId = BamlRecordType.LineNumberAndPosition;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.LineNumber),
                new BamlField(BamlFieldType.LinePosition),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Debug, fields);

            // LinePosition = 54
            recordId = BamlRecordType.LinePosition;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.LinePosition),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.Debug, fields);

            // PropertyWithStaticResourceId = 55
            recordId = BamlRecordType.PropertyWithStaticResourceId;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.AttributeId),
                new BamlField(BamlFieldType.StaticResourceId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);

            // OptimizedStaticResource = 56
            recordId = BamlRecordType.OptimizedStaticResource;
            fields = new BamlField[]
            {
                new BamlField(BamlFieldType.FlagsByte),
                new BamlField(BamlFieldType.ValueId),
            };
            _records[(int)recordId] = new BamlRecord(recordId, false, BamlRecordFlags.None, fields);
        }
    }
}


<|start_filename|>Data Binding/PropertyChangeNotification/BidCollection.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;
using System.Timers;

namespace PropertyChangeNotification
{
    public class BidCollection : ObservableCollection<Bid>
    {
        private readonly Bid _item1 = new Bid("Perseus Vase", (decimal) 24.95);
        private readonly Bid _item2 = new Bid("Hercules Statue", (decimal) 16.05);
        private readonly Bid _item3 = new Bid("Odysseus Painting", (decimal) 100.0);

        public BidCollection()
        {
            Add(_item1);
            Add(_item2);
            Add(_item3);
            CreateTimer();
        }

        private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
        {
            _item1.BidItemPrice += (decimal) 1.25;
            _item2.BidItemPrice += (decimal) 2.45;
            _item3.BidItemPrice += (decimal) 10.55;
        }

        private void CreateTimer()
        {
            var timer1 = new Timer
            {
                Enabled = true,
                Interval = 2000
            };
            timer1.Elapsed += Timer1_Elapsed;
        }
    }
}

<|start_filename|>Drag and Drop/DragDropDataFormats/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace DragDropDataFormats
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ClickClear(object sender, RoutedEventArgs e)
        {
            tbDropTarget.Clear();
        }

        private void EhDragEnter(object sender, DragEventArgs args)
        {
            args.Effects = DragDropEffects.Copy;
        }

        private void EhPreviewDrop(object sender, DragEventArgs args)
        {
            // TextBox includes native drop handling.  This is to let the TextBox know that we're handling
            // the Drop event, and we don't want the native handler to execute.  
            args.Handled = true;

            ShowDataFormats(args);
        }

        private void ShowDataFormats(DragEventArgs args)
        {
            tbDropTarget.AppendText("The following data formats are present:\n");
            if (cbAutoConvert.IsChecked.Value)
            {
                foreach (var format in args.Data.GetFormats((bool) cbAutoConvert.IsChecked))
                {
                    if (args.Data.GetDataPresent(format, false))
                        tbDropTarget.AppendText("\t- " + format + " (native)\n");
                    else tbDropTarget.AppendText("\t- " + format + " (autoconvert)\n");
                }
            }
            else
            {
                foreach (var format in args.Data.GetFormats((bool) cbAutoConvert.IsChecked))
                {
                    tbDropTarget.AppendText("\t- " + format + " (native)\n");
                }
            }

            tbDropTarget.AppendText("\n");
            tbDropTarget.ScrollToEnd();
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/BamlFields.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics;

namespace BamlTools
{
    public enum BamlFieldType : byte
    {
        None = 0,
        BamlVersion,
        LoadAsync,
        MaxAsyncRecords,
        TypeId,
        AttributeId,
        Value,
        ExtensionTypeId,
        SerializerTypeId,
        LineNumber,
        LinePosition,
        ConverterTypeId,
        NamespacePrefix,
        NameId,
        XmlNamespace,
        ClrNamespace,
        AssemblyId,
        AssemblyFullName,
        TypeFullName,
        AttributeUsage,
        StringId,
        ValuePosition,
        ValueId,
        StaticResourceId,
        ContentSize,
        Shared,
        SharedSet,
        ConnectionId,
        RuntimeName,
        FlagsByte,
        DebugBamlStream,
        AssemblyIdList,
        LastFieldType
    }

    public struct BamlField
    {
        private static readonly Type[] _clrTypes;

        private readonly BamlFieldType _fieldType;
        private readonly string _name;
        private object _val;

        public BamlField(BamlFieldType ft, string n)
        {
            _fieldType = ft;
            _name = n;
            _val = null;
        }

        public BamlField(BamlFieldType ft)
        {
            _fieldType = ft;
            _name = null;
            _val = null;
        }

        static BamlField()
        {
            _clrTypes = new Type[(int)BamlFieldType.LastFieldType];

            _clrTypes[(int)BamlFieldType.BamlVersion] = typeof(MockFormatVersion);
            _clrTypes[(int)BamlFieldType.LoadAsync] = typeof(bool);
            _clrTypes[(int)BamlFieldType.MaxAsyncRecords] = typeof(Int32);
            _clrTypes[(int)BamlFieldType.TypeId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.AttributeId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.Value] = typeof(string);
            _clrTypes[(int)BamlFieldType.ExtensionTypeId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.SerializerTypeId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.LineNumber] = typeof(Int32);
            _clrTypes[(int)BamlFieldType.LinePosition] = typeof(Int32);
            _clrTypes[(int)BamlFieldType.ConverterTypeId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.NamespacePrefix] = typeof(string);
            _clrTypes[(int)BamlFieldType.NameId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.XmlNamespace] = typeof(string);
            _clrTypes[(int)BamlFieldType.ClrNamespace] = typeof(string);
            _clrTypes[(int)BamlFieldType.AssemblyId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.AssemblyFullName] = typeof(string);
            _clrTypes[(int)BamlFieldType.TypeFullName] = typeof(string);
            _clrTypes[(int)BamlFieldType.AttributeUsage] = typeof(byte);
            _clrTypes[(int)BamlFieldType.StringId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.ValuePosition] = typeof(Int32);
            _clrTypes[(int)BamlFieldType.ValueId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.StaticResourceId] = typeof(Int16);
            _clrTypes[(int)BamlFieldType.ContentSize] = typeof(Int32);
            _clrTypes[(int)BamlFieldType.Shared] = typeof(bool);
            _clrTypes[(int)BamlFieldType.SharedSet] = typeof(bool);
            _clrTypes[(int)BamlFieldType.ConnectionId] = typeof(Int32);
            _clrTypes[(int)BamlFieldType.RuntimeName] = typeof(string);
            _clrTypes[(int)BamlFieldType.FlagsByte] = typeof(byte);
            _clrTypes[(int)BamlFieldType.DebugBamlStream] = typeof(bool);
            _clrTypes[(int)BamlFieldType.AssemblyIdList] = typeof(Int16[]);

#if DEBUG
            for (int i = 1; i < (int)BamlFieldType.LastFieldType; i++)
            {
                Debug.Assert(_clrTypes[i] != null, "A CLR definition for BamlFieldType " + ((BamlFieldType)i).ToString() + " is missing.  ");
            }
#endif
        }

        public string Name
        {
            get { return _name ?? _fieldType.ToString(); }
        }

        public Type ClrType
        {
            get { return _clrTypes[(int)_fieldType]; }
        }

        public BamlFieldType BamlFieldType
        {
            get { return _fieldType; }
        }

        public object Value
        {
            set { _val = value; }
            get { return _val; }
        }
    }
}


<|start_filename|>Sample Applications/DataBindingDemo/SpecialFeaturesConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace DataBindingDemo
{
    internal class SpecialFeaturesConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values == null || values.Length < 2) return false;
            if (values[0] == DependencyProperty.UnsetValue) return false;
            if (values[1] == DependencyProperty.UnsetValue) return false;
            var rating = (int) values[0];
            var date = (DateTime) values[1];

            // if the user has a good rating (10+) and has been a member for more than a year, special features are available
            if ((rating >= 10) && (date.Date < (DateTime.Now.Date - new TimeSpan(365, 0, 0, 0))))
            {
                return true;
            }
            return false;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => new[] { Binding.DoNothing, Binding.DoNothing };
    }
}

<|start_filename|>Migration and Interoperability/LocalizingWpfInWf/SimpleControlA.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Controls;

namespace LocalizingWpfInWf
{
    /// <summary>
    ///     Interaction logic for SimpleControlA.xaml
    /// </summary>
    public partial class SimpleControlA : UserControl
    {
        public SimpleControlA()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Sample Applications/PhotoStoreDemo/PrintTypeList.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;

namespace PhotoStoreDemo
{
    public class PrintTypeList : ObservableCollection<PrintType>
    {
        public PrintTypeList()
        {
            Add(new PrintType("4x6 Print", 0.15));
            Add(new PrintType("Greeting Card", 1.49));
            Add(new PrintType("T-Shirt", 14.99));
        }
    }
}

<|start_filename|>Elements/ContextMenuOpening/Pane.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace ContextMenuOpening
{
    public partial class Pane
    {
        private bool _flagForCustomContextMenu;

        private ContextMenu BuildMenu()
        {
            var theMenu = new ContextMenu();
            var mia = new MenuItem {Header = "Item1"};
            var mib = new MenuItem {Header = "Item2"};
            var mic = new MenuItem {Header = "Item3"};
            theMenu.Items.Add(mia);
            theMenu.Items.Add(mib);
            theMenu.Items.Add(mic);
            return theMenu;
        }

        private void AddItemToCm(object sender, ContextMenuEventArgs e)
        {
            //check if Item4 is already there, this will probably run more than once
            var fe = e.Source as FrameworkElement;
            var cm = fe.ContextMenu;
            if (cm.Items.Cast<MenuItem>().Any(mi => (string) mi.Header == "Item4"))
            {
                return;
            }
            var mi4 = new MenuItem {Header = "Item4"};
            fe.ContextMenu.Items.Add(mi4);
        }

        private void HandlerForCMO(object sender, ContextMenuEventArgs e)
        {
            var fe = e.Source as FrameworkElement;
            fe.ContextMenu = BuildMenu();
        }

        private void HandlerForCMO2(object sender, ContextMenuEventArgs e)
        {
            if (!_flagForCustomContextMenu)
            {
                e.Handled = true; //need to suppress empty menu
                var fe = e.Source as FrameworkElement;
                fe.ContextMenu = BuildMenu();
                _flagForCustomContextMenu = true;
                fe.ContextMenu.IsOpen = true;
            }
        }
    }
}

<|start_filename|>Graphics/ShapeElements/SampleViewer.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace Microsoft.Samples.Graphics
{
    public partial class SampleViewer : Window
    {
        private readonly Page[] navigationArray;

        public SampleViewer()
        {
            navigationArray = new Page[11];
            navigationArray[0] = new ShapeTypes();
            navigationArray[1] = new LineExample();
            navigationArray[2] = new RectangleExample();
            navigationArray[3] = new EllipseExample();
            navigationArray[4] = new PolylineExample();
            navigationArray[5] = new PolygonExample();
            navigationArray[6] = new PathExample();
            navigationArray[7] = new FillRuleExample();
            navigationArray[8] = new LineCapsAndJoinsExample();
            navigationArray[9] = new MiterLimitExample();
            navigationArray[10] = new StretchExample();
            InitializeComponent();
        }
    }
}

<|start_filename|>PerMonitorDPI/WinFormsHost/LoginControl.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsHost
{
    public partial class LoginControl : UserControl
    {
        public LoginControl()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}


<|start_filename|>Windows/SaveWindowState/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using SaveWindowState.Properties;

namespace SaveWindowState
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            try
            {
                // Load window placement details for previous application session from application settings
                // Note - if window was closed on a monitor that is now disconnected from the computer,
                //        SetWindowPlacement will place the window onto a visible monitor.
                var wp = Settings.Default.WindowPlacement;
                wp.length = Marshal.SizeOf(typeof (WindowPlacement));
                wp.flags = 0;
                wp.showCmd = (wp.showCmd == SwShowminimized ? SwShownormal : wp.showCmd);
                var hwnd = new WindowInteropHelper(this).Handle;
                SetWindowPlacement(hwnd, ref wp);
            }
            catch
            {
                // ignored
            }
        }

        // WARNING - Not fired when Application.SessionEnding is fired
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            // Persist window placement details to application settings
            WindowPlacement wp;
            var hwnd = new WindowInteropHelper(this).Handle;
            GetWindowPlacement(hwnd, out wp);
            Settings.Default.WindowPlacement = wp;
            Settings.Default.Save();
        }

        #region Win32 API declarations to set and get window placement

        [DllImport("user32.dll")]
        private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WindowPlacement lpwndpl);

        [DllImport("user32.dll")]
        private static extern bool GetWindowPlacement(IntPtr hWnd, out WindowPlacement lpwndpl);

        private const int SwShownormal = 1;
        private const int SwShowminimized = 2;

        #endregion
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/PlaneXY.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    public sealed class PlaneXy : FunctionMesh
    {
        public PlaneXy(double lengthX, double lengthY)
        {
            Init(new VariableExpression("u"),
                new VariableExpression("v"),
                new ConstantExpression(0.0),
                -lengthX/2.0, lengthX/2.0,
                -lengthY/2.0, lengthY/2.0
                );
        }
    }
}

<|start_filename|>Accessibility/FetchTimer/FetchTimerForm.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Forms;

namespace FetchTimer
{
    public partial class FetchTimerForm : Form
    {
        public delegate void OutputDelegate(string results);

        private TreeScope _cacheScope;
        private AutomationElementMode _elementMode;
        private UiAutomationFetcher _fetcher;
        // Member variables.
        private Point _targetPoint;
        private Thread _workerThread;
        public OutputDelegate OutputMethodInstance;

        /// <summary>
        ///     Constructor.
        /// </summary>
        public FetchTimerForm()
        {
            InitializeComponent();
            OutputMethodInstance = OutputResults;
        }

        /// <summary>
        ///     Enables/disables Children check box when Descendants changed, since
        ///     Descendants includes Children.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbDescendants_CheckedChanged(object sender, EventArgs e)
        {
            var box = sender as CheckBox;
            cbChildren.Enabled = !box.Checked;
        }

        /// <summary>
        ///     Prints information to the text box.
        /// </summary>
        /// <param name="output">String to print.</param>
        public void OutputResults(string output)
        {
            tbOutput.AppendText(output);
        }

        /// <summary>
        ///     Clears the output box.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            tbOutput.Clear();
        }

        /// <summary>
        ///     Responds to button click; saves options and starts
        ///     the UI Automation worker thread.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void btnProps_Click(object sender, EventArgs e)
        {
            // Convert Drawing.Point to Windows.Point.
            var drawingPoint = Cursor.Position;
            _targetPoint = new Point(drawingPoint.X, drawingPoint.Y);

            // Save caching settings in member variables so UI isn't accessed 
            // directly by the other thread.

            _elementMode = rbFull.Checked ? AutomationElementMode.Full : AutomationElementMode.None;

            // For simplicity, always include Element in scope.
            _cacheScope = TreeScope.Element;
            if (cbDescendants.Checked)
            {
                _cacheScope |= TreeScope.Descendants;
            }
            // Note: if descendants are specified, children 
            // are automatically included.
            else if (cbChildren.Checked)
            {
                _cacheScope |= TreeScope.Children;
            }

            _fetcher = new UiAutomationFetcher(this, _targetPoint,
                _cacheScope, _elementMode);

            // Start another thread to do the UI Automation work.
            var threadDelegate = new ThreadStart(StartWorkerThread);
            _workerThread = new Thread(threadDelegate) {Priority = ThreadPriority.Highest};
            _workerThread.Start();
            OutputResults("Wait..." + Environment.NewLine);
        }

        /// <summary>
        ///     Delegated method for ThreadStart.
        /// </summary>
        /// <remarks>
        ///     UI Automation must be called on a separate thread if the client application
        ///     itself might be a target.
        /// </remarks>
        private void StartWorkerThread()
        {
            _fetcher.DoWork();
        }
    } // Form class
} // Namespace

<|start_filename|>Documents/Flow Content/FontProperties/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Media;

namespace FontProperties
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public void OnClick1(object sender, RoutedEventArgs e)
        {
            txt1.Text = "The FontFamily is set to Arial.";
            txt2.FontFamily = new FontFamily("Arial");
        }

        public void OnClick2(object sender, RoutedEventArgs e)
        {
            txt1.Text = "The FontFamily is set to Courier new.";
            txt2.FontFamily = new FontFamily("Courier new");
        }

        public void OnClick3(object sender, RoutedEventArgs e)
        {
            txt1.Text = "The FontFamily is set to Tahoma.";
            txt2.FontFamily = new FontFamily("Tahoma");
        }

        public void OnClick4(object sender, RoutedEventArgs e)
        {
            txt1.Text = "The FontFamily is set to Times new Roman.";
            txt2.FontFamily = new FontFamily("Times new Roman");
        }

        public void OnClick5(object sender, RoutedEventArgs e)
        {
            txt1.Text = "The FontFamily is set to Verdana.";
            txt2.FontFamily = new FontFamily("Verdana");
        }

        public void OnClick6(object sender, RoutedEventArgs e)
        {
            txt3.Text = "The FontSize is set to 8 point.";
            txt2.FontSize = 8;
        }

        public void OnClick7(object sender, RoutedEventArgs e)
        {
            txt3.Text = "The FontSize is set to 10 point.";
            txt2.FontSize = 10;
        }

        public void OnClick8(object sender, RoutedEventArgs e)
        {
            txt3.Text = "The FontSize is set to 12 point.";
            txt2.FontSize = 12;
        }

        public void OnClick9(object sender, RoutedEventArgs e)
        {
            txt3.Text = "The FontSize is set to 14 point.";
            txt2.FontSize = 14;
        }

        public void OnClick10(object sender, RoutedEventArgs e)
        {
            txt3.Text = "The FontSize is set to 16 point.";
            txt2.FontSize = 16;
        }

        public void OnClick11(object sender, RoutedEventArgs e)
        {
            txt4.Text = "The Foreground color is set to Black.";
            txt2.Foreground = Brushes.Black;
        }

        public void OnClick12(object sender, RoutedEventArgs e)
        {
            txt4.Text = "The Foreground color is set to Blue.";
            txt2.Foreground = Brushes.Blue;
        }

        public void OnClick13(object sender, RoutedEventArgs e)
        {
            txt4.Text = "The Foreground color is set to Green.";
            txt2.Foreground = Brushes.Green;
        }

        public void OnClick14(object sender, RoutedEventArgs e)
        {
            txt4.Text = "The Foreground color is set to Red.";
            txt2.Foreground = Brushes.Red;
        }

        public void OnClick15(object sender, RoutedEventArgs e)
        {
            txt4.Text = "The Foreground color is set to Yellow.";
            txt2.Foreground = Brushes.Yellow;
        }
    }
}

<|start_filename|>Accessibility/FetchTimer/FetchTimerForm.designer.cs<|end_filename|>
/*************************************************************************************************
 *
 * File: FetchTimerForm.Designer.cs
 *
 * Description: Design-time code for the interface.
 * 
 * See FetchTimerForm.cs for a full description of the sample.
 *
 *     
 *  This file is part of the Microsoft WinfFX SDK Code Samples.
 * 
 *  Copyright (C) Microsoft Corporation.  All rights reserved.
 * 
 * This source code is intended only as a supplement to Microsoft
 * Development Tools and/or on-line documentation.  See these other
 * materials for detailed information regarding Microsoft code samples.
 * 
 * THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
 * PARTICULAR PURPOSE.
 * 
 *************************************************************************************************/
namespace FetchTimer
{
    partial class FetchTimerForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.gbScope = new System.Windows.Forms.GroupBox();
            this.cbDescendants = new System.Windows.Forms.CheckBox();
            this.cbChildren = new System.Windows.Forms.CheckBox();
            this.comboElement = new System.Windows.Forms.CheckBox();
            this.tbOutput = new System.Windows.Forms.TextBox();
            this.lblOutput = new System.Windows.Forms.Label();
            this.btnProps = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.btnClear = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.rbFull = new System.Windows.Forms.RadioButton();
            this.rbNone = new System.Windows.Forms.RadioButton();
            this.gbScope.SuspendLayout();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // gbScope
            // 
            this.gbScope.Controls.Add(this.cbDescendants);
            this.gbScope.Controls.Add(this.cbChildren);
            this.gbScope.Controls.Add(this.comboElement);
            this.gbScope.Location = new System.Drawing.Point(239, 76);
            this.gbScope.Name = "gbScope";
            this.gbScope.Size = new System.Drawing.Size(97, 93);
            this.gbScope.TabIndex = 3;
            this.gbScope.TabStop = false;
            this.gbScope.Text = "TreeScope";
            // 
            // cbDescendants
            // 
            this.cbDescendants.AutoSize = true;
            this.cbDescendants.Location = new System.Drawing.Point(6, 68);
            this.cbDescendants.Name = "cbDescendants";
            this.cbDescendants.Size = new System.Drawing.Size(89, 17);
            this.cbDescendants.TabIndex = 2;
            this.cbDescendants.Text = "&Descendants";
            this.cbDescendants.UseVisualStyleBackColor = true;
            this.cbDescendants.CheckedChanged += new System.EventHandler(this.cbDescendants_CheckedChanged);
            // 
            // cbChildren
            // 
            this.cbChildren.AutoSize = true;
            this.cbChildren.Location = new System.Drawing.Point(6, 44);
            this.cbChildren.Name = "cbChildren";
            this.cbChildren.Size = new System.Drawing.Size(64, 17);
            this.cbChildren.TabIndex = 1;
            this.cbChildren.Text = "&Children";
            this.cbChildren.UseVisualStyleBackColor = true;
            // 
            // comboElement
            // 
            this.comboElement.AutoCheck = false;
            this.comboElement.AutoSize = true;
            this.comboElement.Checked = true;
            this.comboElement.CheckState = System.Windows.Forms.CheckState.Checked;
            this.comboElement.Location = new System.Drawing.Point(6, 20);
            this.comboElement.Name = "comboElement";
            this.comboElement.Size = new System.Drawing.Size(64, 17);
            this.comboElement.TabIndex = 0;
            this.comboElement.TabStop = false;
            this.comboElement.Text = "Element";
            this.comboElement.UseVisualStyleBackColor = true;
            // 
            // tbOutput
            // 
            this.tbOutput.BackColor = System.Drawing.SystemColors.Window;
            this.tbOutput.Location = new System.Drawing.Point(10, 180);
            this.tbOutput.Multiline = true;
            this.tbOutput.Name = "tbOutput";
            this.tbOutput.ReadOnly = true;
            this.tbOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.tbOutput.Size = new System.Drawing.Size(385, 165);
            this.tbOutput.TabIndex = 6;
            this.tbOutput.TabStop = false;
            // 
            // lblOutput
            // 
            this.lblOutput.AutoSize = true;
            this.lblOutput.Location = new System.Drawing.Point(20, 156);
            this.lblOutput.Name = "lblOutput";
            this.lblOutput.Size = new System.Drawing.Size(42, 13);
            this.lblOutput.TabIndex = 5;
            this.lblOutput.Text = "Results";
            this.lblOutput.Visible = false;
            // 
            // btnProps
            // 
            this.btnProps.Location = new System.Drawing.Point(156, 39);
            this.btnProps.Name = "btnProps";
            this.btnProps.Size = new System.Drawing.Size(100, 23);
            this.btnProps.TabIndex = 1;
            this.btnProps.Text = "&Get Properties";
            this.btnProps.UseVisualStyleBackColor = true;
            this.btnProps.Click += new System.EventHandler(this.btnProps_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(52, 7);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(319, 26);
            this.label1.TabIndex = 0;
            this.label1.Text = "Activate this window, put the cursor over an element\nanywhere on the screen, and " +
                "invoke the button by pressing Alt+G.";
            this.label1.TextAlign = System.Drawing.ContentAlignment.TopCenter;
            // 
            // btnClear
            // 
            this.btnClear.Location = new System.Drawing.Point(68, 151);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(60, 23);
            this.btnClear.TabIndex = 7;
            this.btnClear.Text = "Clea&r";
            this.btnClear.UseVisualStyleBackColor = true;
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.rbNone);
            this.groupBox1.Controls.Add(this.rbFull);
            this.groupBox1.Location = new System.Drawing.Point(36, 76);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(153, 69);
            this.groupBox1.TabIndex = 8;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "AutomationElementMode";
            // 
            // rbFull
            // 
            this.rbFull.AutoSize = true;
            this.rbFull.Checked = true;
            this.rbFull.Location = new System.Drawing.Point(51, 20);
            this.rbFull.Name = "rbFull";
            this.rbFull.Size = new System.Drawing.Size(41, 17);
            this.rbFull.TabIndex = 0;
            this.rbFull.TabStop = true;
            this.rbFull.Text = "&Full";
            this.rbFull.UseVisualStyleBackColor = true;
            // 
            // rbNone
            // 
            this.rbNone.AutoSize = true;
            this.rbNone.Location = new System.Drawing.Point(51, 44);
            this.rbNone.Name = "rbNone";
            this.rbNone.Size = new System.Drawing.Size(51, 17);
            this.rbNone.TabIndex = 1;
            this.rbNone.Text = "&None";
            this.rbNone.UseVisualStyleBackColor = true;
            // 
            // FetchForm
            // 
            this.ClientSize = new System.Drawing.Size(405, 357);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.btnClear);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnProps);
            this.Controls.Add(this.lblOutput);
            this.Controls.Add(this.tbOutput);
            this.Controls.Add(this.gbScope);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "FetchForm";
            this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
            this.Text = "UI Automation Caching Sample";
            this.TopMost = true;
            this.gbScope.ResumeLayout(false);
            this.gbScope.PerformLayout();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.GroupBox gbScope;
        private System.Windows.Forms.CheckBox comboElement;
        private System.Windows.Forms.CheckBox cbDescendants;
        private System.Windows.Forms.CheckBox cbChildren;
        private System.Windows.Forms.TextBox tbOutput;
        private System.Windows.Forms.Label lblOutput;
        private System.Windows.Forms.Button btnProps;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button btnClear;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.RadioButton rbNone;
        private System.Windows.Forms.RadioButton rbFull;
    }
}



<|start_filename|>Sample Applications/EditingExaminerDemo/CommandLine.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;
using System.Diagnostics;

namespace EditingExaminerDemo
{
    /// <summary>
    ///     This class parses the command line commands.
    /// </summary>
    public class CommandLine
    {
        private readonly Hashtable _table;

        /// <summary>
        ///     constructor
        /// </summary>
        /// <param name="commandLine"></param>
        /// <param name="table"></param>
        public CommandLine(string commandLine, Hashtable table)
        {
            _table = table;
            Result = new ObjectItem(null, null);
            DoParse(commandLine);
        }

        /// <summary>
        ///     Retrieve the parsed object.
        /// </summary>
        public ObjectItem Result { get; private set; }

        /// <summary>
        ///     Recursively parse the command line content
        /// </summary>
        /// <param name="commandLine"></param>
        private void DoParse(string commandLine)
        {
            string strLeft;
            string strRight;
            object left;
            var str = commandLine.Replace("  ", " ");
            str = str.Trim();
            //Asignment
            if (str.Contains("="))
            {
                var strs = str.Split('=');
                if (strs.Length != 2 || strs[0].Length == 0 || str[1] == 0)
                {
                    Result.Error = "syntax error: Don't know how to do Assignment!";
                    return;
                }
                strLeft = strRight = string.Empty;
                strLeft = strs[0];
                strRight = strs[1];
                strLeft = strLeft.Trim();
                strRight = strRight.Trim();
                Result = new CommandLine(strRight, _table).Result;

                //Set a value to a variable in the Table.
                if (_table.Contains(strLeft))
                {
                    _table.Remove(strLeft);
                    _table.Add(strLeft, Result.Value);
                }
                //Assign a value to a property.
                else if (strLeft.Contains("."))
                {
                    left =
                        new CommandLine(strLeft.Substring(0, strLeft.LastIndexOf(".", StringComparison.Ordinal)), _table)
                            .Result.Value;
                    if (left != null)
                    {
                        ReflectionUtils.SetProperty(left,
                            strLeft.Substring(strLeft.LastIndexOf(".", StringComparison.Ordinal) + 1),
                            Result.Value);
                    }
                    else
                    {
                        Result.Error = "Failed: can't set value to " + strLeft + "!";
                    }
                }
                //Make a declaration
                else
                {
                    _table.Add(strLeft, Result.Value);
                }
            }
            //Invoke a method, Creating a object.
            else if (str.EndsWith(")"))
            {
                if (str.StartsWith("new "))
                {
                    str = str.Substring(4).Trim();
                }
                left = null;
                strRight = strLeft = str.Substring(0, str.IndexOf("(", StringComparison.Ordinal));

                //If there is a dot, invoke a method from an object
                if (strLeft.LastIndexOf(".", StringComparison.Ordinal) >= 0)
                {
                    strLeft = strLeft.Substring(0, strLeft.LastIndexOf(".", StringComparison.Ordinal));
                    left = new CommandLine(strLeft, _table).Result.Value;
                }

                //When left is null, invoke a constructor, otherwise invoke a method.
                if (left != null)
                {
                    //Get the command line start from the method name
                    //this will get the argument list.
                    str = str.Substring(strRight.LastIndexOf(".", StringComparison.Ordinal) + 1);
                }

                Result.Value = InvokMethod(str, left);
            }

            //Retrive data
            else
            {
                if (_table.Contains(str))
                {
                    Result.Value = _table[str];
                    return;
                }
                left = null;
                strRight = str;

                if (str.Contains("."))
                {
                    strLeft = str.Substring(0, str.IndexOf(".", StringComparison.Ordinal));
                    left = _table[strLeft];

                    //If an object is found in a Table, the property name is needed in order to retrieve the value.
                    if (left != null && str.Length - (strLeft.Length + 1) > 0)
                    {
                        strRight = str.Substring(str.IndexOf(".", StringComparison.Ordinal) + 1,
                            str.Length - (strLeft.Length + 1));
                    }
                }

                Result = Get_Value(left, strRight);

                if (!string.IsNullOrEmpty(Result.Error))
                {
                    //If the expression is just for a static member of a class
                    Result = GetProperty(null, strRight);
                }
            }
        }

        /// <summary>
        ///     Create an object.
        ///     1. new a object: new abc(p1, p2, p3...)
        ///     2. Create a instance for a primative values. for example
        ///     3. Create instance for Enum.
        ///     4. create a instance for struct.
        /// </summary>
        /// <param name="commandLine"></param>
        /// <param name="objectInstance"></param>
        /// <returns></returns>
        private object InvokMethod(string commandLine, object objectInstance)
        {
            string name;
            string arg;
            string[] args;
            object[] objs;
            object returnValue;
            commandLine = commandLine.Trim();
            objs = null;
            returnValue = false;
            name = commandLine.Substring(0, commandLine.IndexOf("(", StringComparison.Ordinal));
            arg = commandLine.Substring(commandLine.IndexOf("(", StringComparison.Ordinal) + 1,
                commandLine.IndexOf(")", StringComparison.Ordinal) -
                (commandLine.IndexOf("(", StringComparison.Ordinal) + 1));
            arg = commandLine.Substring(commandLine.IndexOf("(", StringComparison.Ordinal) + 1);
            arg = arg.Substring(0, arg.Length - 1);
            if (arg.Length > 0)
            {
                args = arg.Trim().Split(',');
                objs = new object[args.Length];

                for (var i = 0; i < args.Length; i++)
                {
                    objs[i] = new CommandLine(args[i], _table).Result.Value;
                }
            }
            else
            {
                objs = new object[0];
            }
            //If there is an instance, we should invoke a instance methods. 
            if (objectInstance != null)
            {
                try
                {
                    //Try the instance methods first.
                    returnValue = ReflectionUtils.InvokeInstanceMethod(objectInstance, name, objs);
                }
                catch (Exception ex)
                {
                    //Try the static methods.
                    //If there the invoking failures here, the Exception message is sent to the Error box.
                    returnValue = ReflectionUtils.InvokeStaticMethod(objectInstance as Type, name, objs);
                    Debug.Write(ex.ToString());
                }
            }
            //Create the object. 
            else
            {
                returnValue = ReflectionUtils.CreateInstanceOfType(name, objs);
            }

            return returnValue;
        }

        /// <summary>
        ///     This method helps recursivly retrieve propeties.
        /// </summary>
        /// <param name="o"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private ObjectItem Get_Value(object o, string name)
        {
            var parseError = "Parser error: the command line can't be evaluated!";

            var result = new ObjectItem(null, null);
            if (string.IsNullOrEmpty(name))
            {
                return result;
            }

            var index = name.IndexOf('.');
            index = (index > 0) ? index : name.Length;
            var left = name.Substring(0, index);

            result = GetProperty(o, left);

            if (!string.IsNullOrEmpty(result.Error))
            {
                result.Error = parseError;
            }

            if (left != name)
            {
                if (result.Value == null)
                {
                    result.Error = parseError;
                }
                else
                {
                    result = Get_Value(result.Value, name.Substring(index + 1));
                }
            }

            return result;
        }

        private ObjectItem GetProperty(object objectInstance, string propertyName)
        {
            object returnValue = null;
            for (var i = 0; i <= 8; i++)
            {
                try
                {
                    switch (i)
                    {
                        case 0:
                            returnValue = ReflectionUtils.GetField(objectInstance, propertyName);
                            break;
                        case 1:

                            returnValue = ReflectionUtils.GetProperty(objectInstance, propertyName);
                            break;
                        case 2:
                            returnValue = ReflectionUtils.GetStaticField(objectInstance as Type, propertyName);
                            break;
                        case 3:
                            returnValue = ReflectionUtils.GetInterfaceProperty(objectInstance, propertyName,
                                propertyName);
                            break;
                        case 4:
                            returnValue = Convert.ToInt32(propertyName);
                            break;
                        case 5:
                            returnValue = Convert.ToDouble(propertyName);
                            break;
                        case 6:
                            if (propertyName.StartsWith("\"") && propertyName.EndsWith("\""))
                            {
                                returnValue = propertyName.Substring(1, propertyName.Length - 2);
                            }
                            else
                            {
                                throw new Exception("error");
                            }
                            break;
                        case 7:

                            returnValue = ReflectionUtils.GetStaticProperty(objectInstance as Type, propertyName);
                            break;
                        case 8:
                            if (objectInstance == null)
                            {
                                returnValue = ReflectionUtils.FindType(propertyName);
                            }
                            else
                            {
                                throw new Exception("");
                            }
                            break;
                    }
                    return new ObjectItem(returnValue, "");
                }
                catch (Exception ex)
                {
                    Debug.Write(ex.ToString());
                }
                if (returnValue != null)
                {
                    break;
                }
            }
            return new ObjectItem(null, "Parser error: the command line can't be evaluated!");
        }
    }
}

<|start_filename|>Migration and Interoperability/AxControl/wmpaxcontrol.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Forms;

namespace WmpAxLib
{
    public partial class WmpAxControl : UserControl
    {
        public WmpAxControl()
        {
            InitializeComponent();
        }

        public void Play(string url)
        {
            axWindowsMediaPlayer1.URL = url;
        }
    }
}

//</snippet100>

<|start_filename|>Sample Applications/StickyNotesDemo/Window2.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace StickyNotesDemo
{
    public class Window2 : Window
    {
        private Brush _backGround;
        private Dialog _dialog;
        private Brush _foreGround;
        private RichTextBox _rtb;
        private double _windowHeight;
        private double _windowWidth;

        public Window2()
        {
            Name = "Window2";

            var lgb = ChangeBackgroundColor(Colors.Yellow);
            Background = lgb;

            WindowStyle = WindowStyle.ToolWindow;
            Height = Width = 200;

            Content = InitializeStickyNote();

            Closing += Window2_Closing;
            SizeChanged += Window2_SizeChanged;
            PreviewMouseLeftButtonUp += Window2_PreviewMouseLeftButtonUp;
            ShowInTaskbar = false;
            Show();
            _rtb.Focus();
        }

        public int BackgroundColorIndex { get; set; } = -1;
        public int ForegroundColorIndex { get; set; } = -1;
        public DateTime Alarm { get; set; }
        public bool TopmostWindow { get; set; }
        public bool AlarmDismissed { get; set; }
        public string RepetitionNumber { get; set; } = "null";

        public static LinearGradientBrush ChangeBackgroundColor(Color c)
        {
            var gs1 = new GradientStop(Colors.White, 0);
            var gs2 = new GradientStop(c, 1);
            var gsc = new GradientStopCollection {gs1, gs2};
            var lgb = new LinearGradientBrush
            {
                StartPoint = new Point(0, 0),
                EndPoint = new Point(0, 1),
                GradientStops = gsc
            };
            return lgb;
        }

        private void Window2_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (WindowStyle.ToString() == WindowStyle.None.ToString())
            {
                WindowStyle = WindowStyle.ToolWindow;
                Height = _windowHeight;
                Width = _windowWidth;
                ResizeMode = ResizeMode.CanResize;
                Background = _backGround;
                Foreground = _foreGround;
                Cursor = Cursors.Arrow;
                BorderThickness = new Thickness(0);
                ShowInTaskbar = false;
            }
        }

        private void Window2_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            _rtb.Width = ((ActualWidth - 10) > 0) ? (ActualWidth - 10) : _rtb.Width;
            _rtb.Height = ((ActualHeight - 50) > 0) ? (ActualHeight - 50) : _rtb.Height;
        }

        private StackPanel InitializeStickyNote()
        {
            var sp = new StackPanel();
            var menu = new Menu
            {
                Background = Brushes.Transparent,
                Width = 20,
                Height = 15,
                HorizontalAlignment = HorizontalAlignment.Left
            };


            var m0 = new MenuItem
            {
                Padding = new Thickness(0),
                Margin = new Thickness(0)
            };
            var menuButton = new Button
            {
                Width = 18,
                Height = 13,
                Background = Brushes.Red
            };
            menuButton.Click += menuButton_Click;
            m0.Header = menuButton;
            m0.BorderThickness = new Thickness(1);


            var m1 = new MenuItem
            {
                Background = Brushes.BlanchedAlmond,
                Header = "Minimize"
            };
            m1.Click += m1_Click;

            var m2 = new MenuItem
            {
                Background = Brushes.BlanchedAlmond,
                Header = "Preferences"
            };
            m2.Click += m2_Click;


            var m3 = new MenuItem
            {
                Background = Brushes.BlanchedAlmond,
                Header = "Close"
            };
            m3.Click += m3_Click;

            var m4 = new MenuItem
            {
                Background = Brushes.BlanchedAlmond,
                Header = "AlwaysOnTop"
            };
            m4.Click += m4_Click;
            m4.Name = "AlwaysOnTop";

            var m5 = new MenuItem
            {
                Background = Brushes.BlanchedAlmond,
                Header = "Email Note To:"
            };
            m5.Click += m5_Click;
            m5.Name = "email";

            var m6 = new MenuItem
            {
                Background = Brushes.BlanchedAlmond,
                Header = "Remove Alarm"
            };
            m6.Click += m6_Click;
            m6.Name = "alarm";
            m6.IsEnabled = false;

            var m7 = new MenuItem
            {
                Background = Brushes.BlanchedAlmond,
                Header = "Dismiss Alarm"
            };
            m7.Click += m7_Click;
            m7.Name = "DismissAlarm";
            m7.IsEnabled = false;


            m0.Items.Add(m1);
            m0.Items.Add(m2);
            m0.Items.Add(m4);
            m0.Items.Add(m5);
            m0.Items.Add(m6);
            m0.Items.Add(m7);
            m0.Items.Add(m3);

            menu.Items.Add(m0);

            var wp = new WrapPanel();
            wp.Children.Add(menu);

            var simpleImage = new Image {Margin = new Thickness(0)};

            var bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("alarm3.PNG", UriKind.Relative);
            bi.EndInit();
            //Set image source
            simpleImage.Source = bi;
            simpleImage.HorizontalAlignment = HorizontalAlignment.Center;
            simpleImage.Visibility = Visibility.Hidden;
            simpleImage.Name = "AlarmIndicator";
            simpleImage.Width = 13;
            wp.Children.Add(simpleImage);

            sp.Children.Add(wp);

            _rtb = new RichTextBox
            {
                Name = "NoteBox",
                Background = Brushes.Transparent,
                BorderThickness = new Thickness(0, 1, 0, 0),
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                Height = Height - 50,
                Width = Width - 10
            };
            sp.Children.Add(_rtb);

            return sp;
        }

        private void m7_Click(object sender, RoutedEventArgs e)
        {
            var m = ((sender as MenuItem).Parent as MenuItem).Parent as Menu;
            (sender as MenuItem).IsEnabled = false;

            var w = ((Window2) (((StackPanel) (m.Parent as WrapPanel).Parent).Parent as Window));
            var m1 = sender as MenuItem;
            m1.IsEnabled = false;
            var m2 = LogicalTreeHelper.FindLogicalNode(w, "AlwaysOnTop") as MenuItem;
            w.Topmost = w.TopmostWindow;
            m2.IsChecked = w.Topmost;

            var menuItemRemoveAlarm = LogicalTreeHelper.FindLogicalNode(w, "alarm") as MenuItem;
            var im = LogicalTreeHelper.FindLogicalNode(w, "AlarmIndicator") as Image;
            if (w.RepetitionNumber.Contains("null"))
            {
                im.Visibility = Visibility.Hidden;
                menuItemRemoveAlarm.IsEnabled = false;
            }
            else
            {
                im.Visibility = Visibility.Visible;
                menuItemRemoveAlarm.IsEnabled = true;
            }

            w.BorderThickness = new Thickness(3);
            w.BorderBrush = Brushes.Red;
            AlarmDismissed = true;
        }

        private void m6_Click(object sender, RoutedEventArgs e)
        {
            var m = ((sender as MenuItem).Parent as MenuItem).Parent as Menu;
            var w = ((Window2) (((StackPanel) (m.Parent as WrapPanel).Parent).Parent as Window));
            w.Alarm = new DateTime();
            var m1 = sender as MenuItem;
            m1.IsEnabled = false;
            var m2 = LogicalTreeHelper.FindLogicalNode(w, "AlwaysOnTop") as MenuItem;
            w.Topmost = w.TopmostWindow;
            m2.IsChecked = w.Topmost;

            var menuItemDismissAlarm = LogicalTreeHelper.FindLogicalNode(w, "DismissAlarm") as MenuItem;
            menuItemDismissAlarm.IsEnabled = false;

            var im = LogicalTreeHelper.FindLogicalNode(w, "AlarmIndicator") as Image;
            im.Visibility = Visibility.Hidden;
            w.RepetitionNumber = "null";

            w.BorderThickness = new Thickness(0);
            w.BorderBrush = Brushes.Transparent;
        }

        private void m5_Click(object sender, RoutedEventArgs e)
        {
            var tr = new TextRange(_rtb.Document.ContentStart, _rtb.Document.ContentEnd);
            var emailDialog = new EmailDialog(tr.Text);
        }

        private void m2_Click(object sender, RoutedEventArgs e)
        {
            _dialog = new Dialog(Alarm, RepetitionNumber);
            _dialog.Closed += dialog_Closed;
        }

        private void dialog_Closed(object sender, EventArgs e)
        {
            var dia = sender as Dialog;
            if (dia.Tag != null)
            {
                dia.Tag = null;
                var arr = dia.PropertyArray;
                if (arr[0] != null)
                {
                    BackgroundColorIndex = (int) (arr[0]);
                    if (WindowStyle.ToString() == WindowStyle.None.ToString())
                    {
                        _backGround = ChangeBackgroundColor(Dialog.ColorArray[BackgroundColorIndex]);
                    }
                    else
                    {
                        Background = ChangeBackgroundColor(Dialog.ColorArray[BackgroundColorIndex]);
                        _backGround = Background;
                    }
                }
                else
                {
                    BackgroundColorIndex = (BackgroundColorIndex != -1) ? BackgroundColorIndex : -1;
                }
                if (arr[1] != null)
                {
                    ForegroundColorIndex = (int) (arr[1]);
                    var rtb = LogicalTreeHelper.FindLogicalNode(this, "NoteBox") as RichTextBox;
                    rtb.SelectAll();
                    rtb.Selection.ApplyPropertyValue(ForegroundProperty,
                        Dialog.ColorArrayForeground[ForegroundColorIndex]);
                    rtb.Selection.Select(rtb.Document.ContentStart, rtb.Document.ContentStart);
                    _foreGround = Foreground;
                }
                else
                {
                    ForegroundColorIndex = (ForegroundColorIndex != -1) ? ForegroundColorIndex : -1;
                }
                if (arr[2] != null)
                {
                    Alarm = dia.Alarm;


                    var w = this;
                    var m = LogicalTreeHelper.FindLogicalNode(w, "AlwaysOnTop") as MenuItem;
                    var m1 = LogicalTreeHelper.FindLogicalNode(w, "alarm") as MenuItem;
                    var m3 = LogicalTreeHelper.FindLogicalNode(w, "DismissAlarm") as MenuItem;
                    var m2 = LogicalTreeHelper.FindLogicalNode(w, "AlarmIndicator") as Image;
                    var alarm = w.Alarm;
                    var current = DateTime.Now;
                    m2.Visibility = (alarm.CompareTo(DateTime.Now) >= 0) ? (Visibility.Visible) : (Visibility.Hidden);

                    if (alarm.Date == current.Date)
                    {
                        var temp1 = alarm;
                        var temp2 = current;
                        temp1 = temp1.AddMinutes(30);
                        temp2 = temp2.AddMinutes(30);

                        if ((temp2.CompareTo(alarm) >= 0) && (temp1.CompareTo(current) >= 0))
                        {
                            w.Topmost = true;
                            m.IsChecked = true;
                            m1.IsEnabled = true;
                            w.BorderBrush = Brushes.Black;
                            w.BorderThickness = new Thickness(5);
                            m3.IsEnabled = true;
                        }
                    }
                    else
                    {
                        w.Topmost = w.TopmostWindow;
                        m.IsChecked = w.Topmost;
                        m1.IsEnabled = (alarm.CompareTo(DateTime.Now) >= 0) ? true : false;
                        m3.IsEnabled = false;

                        w.BorderBrush = Brushes.Transparent;
                        w.BorderThickness = new Thickness(0);
                    }
                }
                RepetitionNumber = dia.AlarmRepetition;
            }
        }

        private void m4_Click(object sender, RoutedEventArgs e)
        {
            var m = ((sender as MenuItem).Parent as MenuItem).Parent as Menu;
            var w = ((Window2) (((StackPanel) (m.Parent as WrapPanel).Parent).Parent as Window));
            if (w.Topmost == false)
            {
                w.Topmost = true;
                TopmostWindow = true;
                ((MenuItem) (sender)).IsChecked = true;
                w.UpdateLayout();
                w.BringIntoView();
            }
            else
            {
                TopmostWindow = w.Topmost = false;
                ((MenuItem) (sender)).IsChecked = false;
            }
        }

        private void m1_Click(object sender, RoutedEventArgs e)
        {
            var m = ((sender as MenuItem).Parent as MenuItem).Parent as Menu;
            var w = ((Window2) (((StackPanel) (m.Parent as WrapPanel).Parent).Parent as Window));
            _windowHeight = w.ActualHeight;
            _windowWidth = w.ActualWidth;
            w.Height = 20;
            w.Width = 20;

            _foreGround = w.Foreground;
            _backGround = w.Background;

            w.Cursor = Cursors.Hand;
            w.BorderThickness = new Thickness(2);
            w.WindowStyle = WindowStyle.None;
            w.ResizeMode = ResizeMode.NoResize;
            w.Background = Brushes.GreenYellow;
        }

        private void m3_Click(object sender, RoutedEventArgs e)
        {
            var m = ((sender as MenuItem).Parent as MenuItem).Parent as Menu;
            ((Window2) (((StackPanel) (m.Parent as WrapPanel).Parent).Parent as Window)).Close();
        }

        private void menuButton_Click(object sender, RoutedEventArgs e)
        {
            var b = sender as Button;
            var menuItem = b.Parent as MenuItem;
            menuItem.Focus();
            menuItem.IsSubmenuOpen = true;
        }

        private void Window2_Closing(object sender, CancelEventArgs e)
        {
            var w2 = sender as Window2;
            var w1 = Application.Current.MainWindow as MainWindow;
            var arr = w1.WindowArray;
            var index = ((int) (w2.Tag));
            arr[index] = null;
            _dialog?.Close();
        }
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/ExifMetadata.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Media.Imaging;

namespace PhotoViewerDemo
{
    public class ExifMetadata
    {
        private readonly BitmapMetadata _metadata;

        public ExifMetadata(Uri imageUri)
        {
            var frame = BitmapFrame.Create(imageUri, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
            _metadata = (BitmapMetadata) frame.Metadata;
        }

        public uint? Width
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif/subifd:{uint=40962}");
                if (val == null)
                {
                    return null;
                }
                if (val.GetType() == typeof (uint))
                {
                    return (uint?) val;
                }
                return Convert.ToUInt32(val);
            }
        }

        public uint? Height
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif/subifd:{uint=40963}");
                if (val == null)
                {
                    return null;
                }
                if (val.GetType() == typeof (uint))
                {
                    return (uint?) val;
                }
                return Convert.ToUInt32(val);
            }
        }

        public decimal? HorizontalResolution
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif:{uint=282}");
                if (val != null)
                {
                    return ParseUnsignedRational((ulong) val);
                }
                return null;
            }
        }

        public decimal? VerticalResolution
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif:{uint=283}");
                if (val != null)
                {
                    return ParseUnsignedRational((ulong) val);
                }
                return null;
            }
        }

        public string EquipmentManufacturer
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif:{uint=271}");
                return (val != null ? (string) val : string.Empty);
            }
        }

        public string CameraModel
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif:{uint=272}");
                return (val != null ? (string) val : string.Empty);
            }
        }

        public string CreationSoftware
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif:{uint=305}");
                return (val != null ? (string) val : string.Empty);
            }
        }

        public ColorRepresentation ColorRepresentation
        {
            get
            {
                if ((ushort) QueryMetadata("/app1/ifd/exif/subifd:{uint=40961}") == 1)
                    return ColorRepresentation.SRgb;
                return ColorRepresentation.Uncalibrated;
            }
        }

        public decimal? ExposureTime
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif/subifd:{uint=33434}");
                if (val != null)
                {
                    return ParseUnsignedRational((ulong) val);
                }
                return null;
            }
        }

        public decimal? ExposureCompensation
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif/subifd:{uint=37380}");
                if (val != null)
                {
                    return ParseSignedRational((long) val);
                }
                return null;
            }
        }

        public decimal? LensAperture
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif/subifd:{uint=33437}");
                if (val != null)
                {
                    return ParseUnsignedRational((ulong) val);
                }
                return null;
            }
        }

        public decimal? FocalLength
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif/subifd:{uint=37386}");
                if (val != null)
                {
                    return ParseUnsignedRational((ulong) val);
                }
                return null;
            }
        }

        public ushort? IsoSpeed => (ushort?) QueryMetadata("/app1/ifd/exif/subifd:{uint=34855}");

        public FlashMode FlashMode
        {
            get
            {
                if ((ushort) QueryMetadata("/app1/ifd/exif/subifd:{uint=37385}")%2 == 1)
                    return FlashMode.FlashFired;
                return FlashMode.FlashDidNotFire;
            }
        }

        public ExposureMode ExposureMode
        {
            get
            {
                var mode = (ushort?) QueryMetadata("/app1/ifd/exif/subifd:{uint=34850}");

                if (mode == null)
                {
                    return ExposureMode.Unknown;
                }
                switch ((int) mode)
                {
                    case 1:
                        return ExposureMode.Manual;
                    case 2:
                        return ExposureMode.NormalProgram;
                    case 3:
                        return ExposureMode.AperturePriority;
                    case 4:
                        return ExposureMode.ShutterPriority;
                    case 5:
                        return ExposureMode.LowSpeedMode;
                    case 6:
                        return ExposureMode.HighSpeedMode;
                    case 7:
                        return ExposureMode.PortraitMode;
                    case 8:
                        return ExposureMode.LandscapeMode;
                    default:
                        return ExposureMode.Unknown;
                }
            }
        }

        public WhiteBalanceMode WhiteBalanceMode
        {
            get
            {
                var mode = (ushort?) QueryMetadata("/app1/ifd/exif/subifd:{uint=37384}");

                if (mode == null)
                {
                    return WhiteBalanceMode.Unknown;
                }
                switch ((int) mode)
                {
                    case 1:
                        return WhiteBalanceMode.Daylight;
                    case 2:
                        return WhiteBalanceMode.Fluorescent;
                    case 3:
                        return WhiteBalanceMode.Tungsten;
                    case 10:
                        return WhiteBalanceMode.Flash;
                    case 17:
                        return WhiteBalanceMode.StandardLightA;
                    case 18:
                        return WhiteBalanceMode.StandardLightB;
                    case 19:
                        return WhiteBalanceMode.StandardLightC;
                    case 20:
                        return WhiteBalanceMode.D55;
                    case 21:
                        return WhiteBalanceMode.D65;
                    case 22:
                        return WhiteBalanceMode.D75;
                    case 255:
                        return WhiteBalanceMode.Other;
                    default:
                        return WhiteBalanceMode.Unknown;
                }
            }
        }

        public DateTime? DateImageTaken
        {
            get
            {
                var val = QueryMetadata("/app1/ifd/exif/subifd:{uint=36867}");
                if (val == null)
                {
                    return null;
                }
                var date = (string) val;
                try
                {
                    return new DateTime(
                        int.Parse(date.Substring(0, 4)), // year
                        int.Parse(date.Substring(5, 2)), // month
                        int.Parse(date.Substring(8, 2)), // day
                        int.Parse(date.Substring(11, 2)), // hour
                        int.Parse(date.Substring(14, 2)), // minute
                        int.Parse(date.Substring(17, 2)) // second
                        );
                }
                catch (FormatException)
                {
                    return null;
                }
                catch (OverflowException)
                {
                    return null;
                }
                catch (ArgumentNullException)
                {
                    return null;
                }
                catch (NullReferenceException)
                {
                    return null;
                }
            }
        }

        private decimal ParseUnsignedRational(ulong exifValue) => (exifValue & 0xFFFFFFFFL) / (decimal)((exifValue & 0xFFFFFFFF00000000L) >> 32);

        private decimal ParseSignedRational(long exifValue) => (exifValue & 0xFFFFFFFFL) / (decimal)((exifValue & 0x7FFFFFFF00000000L) >> 32);

        private object QueryMetadata(string query)
        {
            if (_metadata.ContainsQuery(query))
                return _metadata.GetQuery(query);
            return null;
        }
    }
}

<|start_filename|>Accessibility/InvokePattern/InvokePatternApp/invokepatternapp.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace InvokePatternApp
{
    /// ------------------------------------------------------------------------
    /// <summary>
    ///     Interaction logic for WCP client and Win32 target
    /// </summary>
    /// ------------------------------------------------------------------------
    public class InvokePatternApp : Application
    {
        #region Member variables

        private Window _clientWindow;
        private AutomationElement _rootElement;
        private StackPanel[] _clientTreeViews;
        private TextBlock _statusText;
        private StackPanel _treeviewPanel;
        private StringBuilder _elementInfoCompile;
        private ScrollViewer _clientScrollViewer;
        private string _targetApp;
        // Delegates for updating the client UI based on target application events.
        private delegate void OutputDelegate(string message);

        #endregion Member variables

        #region Target listeners

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Listens for a structure changed event in the target.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Since the events are happening on a different thread than the
        ///     client we need to use a Dispatcher delegate to handle them.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void ChildElementsAdded(object sender, StructureChangedEventArgs e)
        {
            _clientWindow.Dispatcher.BeginInvoke(
                DispatcherPriority.Background,
                new DispatcherOperationCallback(NotifyChildElementsAdded), null);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The delegate for the structure changed event in the target.
        /// </summary>
        /// <param name="arg">null argument</param>
        /// <returns>A null object.</returns>
        /// --------------------------------------------------------------------
        private object NotifyChildElementsAdded(object arg)
        {
            FindTreeViewsInTarget();
            return null;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the window closed event in the target.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void OnTargetClose(object sender, AutomationEventArgs e)
        {
            _clientWindow.Dispatcher.BeginInvoke(
                DispatcherPriority.Background,
                new DispatcherOperationCallback(CloseApp), null);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The delegate for the window closed event in the target.
        /// </summary>
        /// <param name="arg">null argument</param>
        /// <returns>A null object.</returns>
        /// --------------------------------------------------------------------
        private object CloseApp(object arg)
        {
            _clientWindow.Close();
            return (null);
        }

        #endregion Target listeners

        #region Client setup

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Initialize both client and target applications.
        /// </summary>
        /// <param name="args">Startup arguments</param>
        /// --------------------------------------------------------------------
        protected override void OnStartup(StartupEventArgs args)
        {
            // Create our informational window
            CreateWindow();

            // Get the root element from our target application.
            // In general, you should try to obtain only direct children of 
            // the RootElement. A search for descendants may iterate through 
            // hundreds or even thousands of elements, possibly resulting in 
            // a stack overflow. If you are attempting to obtain a specific 
            // element at a lower level, you should start your search from the 
            // application window or from a container at a lower level.
            _targetApp =
                System.Windows.Forms.Application.StartupPath + "\\Target.exe";
            _rootElement = StartApp(_targetApp);
            if (_rootElement == null)
            {
                return;
            }

            // Add a structure change listener for the root element.
            var structureChange =
                new StructureChangedEventHandler(ChildElementsAdded);
            Automation.AddStructureChangedEventHandler(
                _rootElement, TreeScope.Descendants, structureChange);

            // Iterate through the controls in the target application.
            FindTreeViewsInTarget();
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Start the target application.
        /// </summary>
        /// <param name="app">The target appliation.</param>
        /// <remarks>
        ///     Starts the application that we are going to use for as our
        ///     root element for this sample.
        /// </remarks>
        /// --------------------------------------------------------------------
        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        private AutomationElement StartApp(string app)
        {
            if (File.Exists(app))
            {
                AutomationElement targetElement;

                // Start application.
                var p = Process.Start(app);

                //// Give application a second to startup.
                Thread.Sleep(2000);

                targetElement = AutomationElement.FromHandle(p.MainWindowHandle);
                if (targetElement == null)
                {
                    return null;
                }
                var targetClosedHandler =
                    new AutomationEventHandler(OnTargetClose);
                Automation.AddAutomationEventHandler(
                    WindowPattern.WindowClosedEvent,
                    targetElement, TreeScope.Element, targetClosedHandler);

                // Set size and position of target.
                var targetTransformPattern =
                    targetElement.GetCurrentPattern(TransformPattern.Pattern)
                        as TransformPattern;
                if (targetTransformPattern == null)
                    return null;
                targetTransformPattern.Resize(550, 400);
                targetTransformPattern.Move(
                    _clientWindow.Left + _clientWindow.Width + 25, _clientWindow.Top);

                Output("Target started.");

                // Return the AutomationElement
                return (targetElement);
            }
            Output(app + " not found.");
            return (null);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Creates a client window to which output may be written.
        /// </summary>
        /// --------------------------------------------------------------------
        private void CreateWindow()
        {
            // Define a window.
            _clientWindow = new Window
            {
                Width = 400,
                Height = 600,
                Left = 50,
                Top = 50
            };

            // Define a ScrollViewer.
            _clientScrollViewer = new ScrollViewer
            {
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                HorizontalContentAlignment = HorizontalAlignment.Stretch
            };

            // Add Layout control.
            var clientStackPanel = new StackPanel();
            var statusPanel = new StackPanel {HorizontalAlignment = HorizontalAlignment.Center};
            _treeviewPanel = new StackPanel();

            _statusText = new TextBlock
            {
                FontWeight = FontWeights.Bold,
                TextWrapping = TextWrapping.Wrap
            };

            // Add child elements to the parent StackPanel
            statusPanel.Children.Add(_statusText);
            clientStackPanel.Children.Add(statusPanel);
            clientStackPanel.Children.Add(_treeviewPanel);

            // Add the StackPanel as the lone Child of the Border
            _clientScrollViewer.Content = clientStackPanel;

            // Add the Border as the Content of the Parent Window Object
            _clientWindow.Content = _clientScrollViewer;
            _clientWindow.Show();
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Finds all TreeView controls in the target.
        /// </summary>
        /// --------------------------------------------------------------------
        private void FindTreeViewsInTarget()
        {
            // Initialize the client area used to report target controls.
            _treeviewPanel.Children.Clear();
            // Set up our search condition
            var rootTreeViewCondition =
                new PropertyCondition(
                    AutomationElement.ControlTypeProperty, ControlType.Tree);
            // Find all controls that support the condition.
            var targetTreeViewElements =
                _rootElement.FindAll(TreeScope.Children, rootTreeViewCondition);
            if (targetTreeViewElements.Count <= 0)
            {
                Output("TreeView control(s) not found.");
                return;
            }
            // Create an area in the client to report each TreeView in the target.
            _clientTreeViews = new StackPanel[targetTreeViewElements.Count];
            for (var elementIndex = 0;
                elementIndex < targetTreeViewElements.Count;
                elementIndex++)
            {
                _clientTreeViews[elementIndex] = new StackPanel();
                var clientTreeViewBorder = new Border
                {
                    BorderThickness = new Thickness(1),
                    BorderBrush = Brushes.Black,
                    Margin = new Thickness(5),
                    Background = Brushes.LightGray,
                    Child = _clientTreeViews[elementIndex]
                };
                _treeviewPanel.Children.Add(clientTreeViewBorder);
                // Iterate through the descendant controls of each TreeView.
                FindTreeViewDescendants(
                    targetTreeViewElements[elementIndex], elementIndex);
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Walks the UI Automation tree of the target and reports the control
        ///     type of each element it finds in the control view to the client.
        /// </summary>
        /// <param name="targetTreeViewElement">
        ///     The root of the search on this iteration.
        /// </param>
        /// <param name="elementIndex">
        ///     The TreeView index for this iteration.
        /// </param>
        /// <remarks>
        ///     This is a recursive function that maps out the structure of the
        ///     subtree of the target beginning at the AutomationElement passed in
        ///     as the rootElement on the first call. This could be, for example,
        ///     an application window.
        ///     CAUTION: Do not pass in AutomationElement.RootElement. Attempting
        ///     to map out the entire subtree of the desktop could take a very
        ///     long time and even lead to a stack overflow.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void FindTreeViewDescendants(
            AutomationElement targetTreeViewElement, int treeviewIndex)
        {
            if (targetTreeViewElement == null)
                return;

            var elementNode =
                TreeWalker.ControlViewWalker.GetFirstChild(targetTreeViewElement);

            while (elementNode != null)
            {
                var elementInfo = new Label {Margin = new Thickness(0)};
                _clientTreeViews[treeviewIndex].Children.Add(elementInfo);

                // Compile information about the control.
                _elementInfoCompile = new StringBuilder();
                var controlName =
                    (elementNode.Current.Name == "")
                        ? "Unnamed control"
                        : elementNode.Current.Name;
                var autoIdName =
                    (elementNode.Current.AutomationId == "")
                        ? "No AutomationID"
                        : elementNode.Current.AutomationId;

                _elementInfoCompile.Append(controlName)
                    .Append(" (")
                    .Append(elementNode.Current.ControlType.LocalizedControlType)
                    .Append(" - ")
                    .Append(autoIdName)
                    .Append(")");

                // Test for the control patterns of interest for this sample.
                object objPattern;
                if (elementNode.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out objPattern))
                {
                    var expcolPattern = objPattern as ExpandCollapsePattern;
                    if (expcolPattern.Current.ExpandCollapseState != ExpandCollapseState.LeafNode)
                    {
                        var expcolButton = new Button
                        {
                            Margin = new Thickness(0, 0, 0, 5),
                            Height = 20,
                            Width = 100,
                            Content = "ExpandCollapse",
                            Tag = expcolPattern
                        };
                        expcolButton.Click +=
                            ExpandCollapse_Click;
                        _clientTreeViews[treeviewIndex].Children.Add(expcolButton);
                    }
                }
                if (elementNode.TryGetCurrentPattern(TogglePattern.Pattern, out objPattern))
                {
                    var togPattern = objPattern as TogglePattern;
                    var togButton = new Button
                    {
                        Margin = new Thickness(0, 0, 0, 5),
                        Height = 20,
                        Width = 100,
                        Content = "Toggle",
                        Tag = togPattern
                    };
                    togButton.Click += Toggle_Click;
                    _clientTreeViews[treeviewIndex].Children.Add(togButton);
                }
                if (elementNode.TryGetCurrentPattern(InvokePattern.Pattern, out objPattern))
                {
                    var invPattern = objPattern as InvokePattern;
                    var invButton = new Button
                    {
                        Margin = new Thickness(0),
                        Height = 20,
                        Width = 100,
                        Content = "Invoke",
                        Tag = invPattern
                    };
                    invButton.Click += Invoke_Click;
                    _clientTreeViews[treeviewIndex].Children.Add(invButton);
                }
                // Display compiled information about the control.
                elementInfo.Content = _elementInfoCompile;
                var sep = new Separator();
                _clientTreeViews[treeviewIndex].Children.Add(sep);

                // Iterate to next element.
                // elementNode - Current element.
                // treeviewIndex - Index of parent TreeView.
                FindTreeViewDescendants(elementNode, treeviewIndex);
                elementNode =
                    TreeWalker.ControlViewWalker.GetNextSibling(elementNode);
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the Toggle click event.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void Toggle_Click(object sender, RoutedEventArgs e)
        {
            var clientButton = sender as Button;
            var t = clientButton.Tag as TogglePattern;
            if (t == null)
                return;
            t.Toggle();
            _statusText.Text = "Element toggled " + t.Current.ToggleState;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the Invoke click event on the client control.
        ///     The client click handler calls Invoke() on the equivalent target control.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     The Tag property of the FrameworkElement, the client button in this
        ///     case, is used to store the InvokePattern object previously obtained
        ///     from the associated target control.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void Invoke_Click(object sender, RoutedEventArgs e)
        {
            var clientButton = sender as Button;
            var targetInvokePattern = clientButton.Tag as InvokePattern;
            if (targetInvokePattern == null)
                return;
            targetInvokePattern.Invoke();
            _statusText.Text = "Button invoked.";
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the ExpandCollapse click event.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void ExpandCollapse_Click(object sender, RoutedEventArgs e)
        {
            var clientButton = sender as Button;
            var ec = clientButton.Tag as ExpandCollapsePattern;
            if (ec == null)
                return;
            var currentState = ec.Current.ExpandCollapseState;
            try
            {
                if ((currentState == ExpandCollapseState.Collapsed) ||
                    (currentState == ExpandCollapseState.PartiallyExpanded))
                {
                    ec.Expand();
                    _statusText.Text = "TreeItem expanded.";
                }
                else if (currentState == ExpandCollapseState.Expanded)
                {
                    ec.Collapse();
                    _statusText.Text = "TreeItem collapsed.";
                }
            }
            catch (InvalidOperationException)
            {
                // The current state of the element is LeafNode.
                Output("Unable to expand or collapse the element.");
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Output target information to the client.
        /// </summary>
        /// <param name="message">The feedback string to display.</param>
        /// <remarks>
        ///     Since the events are happening on a different thread than the
        ///     client we need to use a Dispatcher delegate to handle them.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void Output(string message)
        {
            _clientWindow.Dispatcher.BeginInvoke(
                DispatcherPriority.Background,
                new OutputDelegate(NotifyTargetEvent), message);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The delegate for the text changed event in the target.
        /// </summary>
        /// <param name="arg">string argument</param>
        /// --------------------------------------------------------------------
        private void NotifyTargetEvent(object arg)
        {
            var message = arg as string;
            _statusText.Text = message;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The main entry point for the application.
        /// </summary>
        /// --------------------------------------------------------------------
        internal sealed class TestMain
        {
            [STAThread]
            private static void Main()
            {
                // Create an instance of the sample class 
                // and call its Run() method to start it.
                var app = new InvokePatternApp();

                app.Run();
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles our application shutdown.
        /// </summary>
        /// <param name="args">Event arguments.</param>
        /// --------------------------------------------------------------------
        protected override void OnExit(ExitEventArgs args)
        {
            if (_rootElement != null)
            {
                Automation.RemoveAllEventHandlers();
            }
            base.OnExit(args);
        }

        #endregion Client setup
    }
}

<|start_filename|>Sample Applications/EditingExaminerDemo/ObjectItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace EditingExaminerDemo
{
    /// <summary>
    ///     Class used to hold a parsed object
    /// </summary>
    public class ObjectItem
    {
        /// <summary>
        ///     Constructor used to create an object
        /// </summary>
        /// <param name="value"></param>
        /// <param name="error"></param>
        public ObjectItem(object value, string error)
        {
            Value = value;
            Error = error;
        }

        /// <summary>
        ///     Get the parsed object
        /// </summary>
        public object Value { get; set; }

        /// <summary>
        ///     Get the error message.
        /// </summary>
        public string Error { get; set; }

        /// <summary>
        ///     Override the ToSring method
        /// </summary>
        /// <returns></returns>
        public override string ToString() => string.IsNullOrEmpty(Error) ? Value?.ToString() ?? "null" : Error;
    }
}

<|start_filename|>Data Binding/DataTemplatingIntro/Task.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace DataTemplatingIntro
{
    public class Task : INotifyPropertyChanged
    {
        private string _description;
        private string _name;
        private int _priority;
        private TaskType _type;

        public Task()
        {
        }

        public Task(string name, string description, int priority, TaskType type)
        {
            _name = name;
            _description = description;
            _priority = priority;
            _type = type;
        }

        public string TaskName
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("TaskName");
            }
        }

        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                OnPropertyChanged("Description");
            }
        }

        public int Priority
        {
            get { return _priority; }
            set
            {
                _priority = value;
                OnPropertyChanged("Priority");
            }
        }

        public TaskType TaskType
        {
            get { return _type; }
            set
            {
                _type = value;
                OnPropertyChanged("TaskType");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public override string ToString() => _name;

        protected void OnPropertyChanged(string info)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}

<|start_filename|>Migration and Interoperability/HostingWfInWPF/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.Integration;

namespace HostingWfInWPF
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            // Create the interop host control.
            var host =
                new WindowsFormsHost();

            // Create the MaskedTextBox control.
            var mtbDate = new MaskedTextBox("00/00/0000");

            // Assign the MaskedTextBox control as the host control's child.
            host.Child = mtbDate;

            // Add the interop host control to the Grid
            // control's collection of child controls.
            grid1.Children.Add(host);
        }
    }
}

<|start_filename|>Data Binding/MultiBinding/NameList.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;

namespace MultiBinding
{
    public class NameList : ObservableCollection<PersonName>
    {
        public NameList()
        {
            Add(new PersonName("Willa", "Cather"));
            Add(new PersonName("Isak", "Dinesen"));
            Add(new PersonName("Victor", "Hugo"));
            Add(new PersonName("Jules", "Verne"));
        }
    }
}

<|start_filename|>Accessibility/InsertText/InsertTextClient/UnmanagedClass.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;
using System.Text;

namespace InsertTextClient
{
// This class *MUST* be internal for security purposes
    internal class UnmanagedClass
    {
        //
        // Control style information
        //
        public const int GclStyle = -16;
        // Editbox styles
        internal const int EsReadonly = 0x0800;
        // Editbox messages
        internal const int WmSettext = 0x000C;
        internal const int EmGetlimittext = 0x00D5;

        [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr SendMessageTimeout(
            Hwnd hwnd, int msg, IntPtr wParam, IntPtr lParam, int flags, int uTimeout, out IntPtr pResult);

        [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern IntPtr SendMessageTimeout(
            IntPtr hwnd, int uMsg, IntPtr wParam, StringBuilder lParam, int flags, int uTimeout, out IntPtr result);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr SendMessage(
            Hwnd hWnd, int nMsg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr SendMessage(
            Hwnd hWnd, int nMsg, IntPtr wParam, StringBuilder lParam);

        [DllImport("user32", ExactSpelling = true)]
        internal static extern bool IsWindowEnabled(IntPtr hWnd);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int GetWindowLong(Hwnd hWnd, int nIndex);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool IsWindowEnabled(Hwnd hwnd);

        [StructLayout(LayoutKind.Sequential)]
        public struct Hwnd
        {
            public IntPtr h;

            public static Hwnd Cast(IntPtr h)
            {
                var hTemp = new Hwnd {h = h};
                return hTemp;
            }

            public static implicit operator IntPtr(Hwnd h) => h.h;

            public static Hwnd Null
            {
                get
                {
                    var hTemp = new Hwnd {h = IntPtr.Zero};
                    return hTemp;
                }
            }

            public static bool operator ==(Hwnd hl, Hwnd hr) => hl.h == hr.h;

            public static bool operator !=(Hwnd hl, Hwnd hr) => hl.h != hr.h;

            public override bool Equals(object oCompare)
            {
                var hr = Cast((Hwnd) oCompare);
                return h == hr.h;
            }

            public override int GetHashCode() => (int)h;
        }
    }
}

<|start_filename|>Elements/LoadedEvent/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace LoadedEvent
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnLoad(object sender, RoutedEventArgs e)
        {
            var b1 = new Button {Content = "New Button"};
            root.Children.Add(b1);
            b1.Height = 25;
            b1.Width = 200;
            b1.HorizontalAlignment = HorizontalAlignment.Left;
        }
    }
}

<|start_filename|>Application Management/UnhandledExceptionHandling/App.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Threading;

namespace UnhandledExceptionHandling
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // Process unhandled exception
            var shutdown = false;

            // Process exception
            if (e.Exception is DivideByZeroException)
            {
                // Recoverable - continue processing
                shutdown = false;
            }
            else if (e.Exception is ArgumentNullException)
            {
                // Unrecoverable - end processing
                shutdown = true;
            }

            if (shutdown)
            {
                // If unrecoverable, attempt to save data
                var result =
                    MessageBox.Show("Application must exit:\n\n" + e.Exception.Message + "\n\nSave before exit?", "app",
                        MessageBoxButton.YesNo, MessageBoxImage.Error);
                if (result == MessageBoxResult.Yes)
                {
                    // Save data
                }

                // Add entry to event log
                EventLog.WriteEntry("app", "Unrecoverable Exception: " + e.Exception.Message, EventLogEntryType.Error);

                // Return exit code
                Shutdown(-1);
            }

            // Prevent default unhandled exception processing
            e.Handled = true;
        }
    }
}

<|start_filename|>Drag and Drop/DragDropEvents/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace DragDropEvents
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // To store the height of the other elements in the grid column containing
        // the event log.
        private readonly double _heightAdjustment;
        private uint _eventCount;

        public MainWindow()
        {
            InitializeComponent();
            _heightAdjustment = lblEventLogWindowTitle.Height + lblEventSelectionTitle.Height + eventChecksGrid.Height;
        }

        private void ClickClearEventHistory(object sender, RoutedEventArgs args)
        {
            tbEventEvents.Clear();
            _eventCount = 0;
        }

        // This event handler fires whenever the main window changes size.  
        private void EhEventWindowSizeChanged(object sender, EventArgs args)
        {
            // Adjust the size of the TextBox so scrolling works properly.
            tbEventEvents.MaxHeight = tbEventEvents.Height = mainGrid.RowDefinitions[1].ActualHeight - _heightAdjustment;
        }

        // Handlers for the drag/drop events.  
        private void EhDragEnter(object sender, DragEventArgs args)
        {
            if (cbDragEnter.IsChecked.Value) LogEvent(EventFireStrings.DragEnter, args);
        }

        private void EhDragLeave(object sender, DragEventArgs args)
        {
            if (cbDragLeave.IsChecked.Value) LogEvent(EventFireStrings.DragLeave, args);
        }

        private void EhDragOver(object sender, DragEventArgs args)
        {
            if (cbDragOver.IsChecked.Value) LogEvent(EventFireStrings.DragOver, args);
        }

        private void EhDrop(object sender, DragEventArgs args)
        {
            if (cbDrop.IsChecked.Value) LogEvent(EventFireStrings.Drop, args);
        }

        private void EhPreviewDragEnter(object sender, DragEventArgs args)
        {
            if (cbPreviewDragEnter.IsChecked.Value) LogEvent(EventFireStrings.PreviewDragEnter, args);
        }

        private void EhPreviewDragLeave(object sender, DragEventArgs args)
        {
            if (cbPreviewDragLeave.IsChecked.Value) LogEvent(EventFireStrings.PreviewDragLeave, args);
        }

        private void EhPreviewDragOver(object sender, DragEventArgs args)
        {
            if (cbPreviewDragOver.IsChecked.Value) LogEvent(EventFireStrings.PreviewDragOver, args);
        }

        private void EhPreviewDrop(object sender, DragEventArgs args)
        {
            if (cbPreviewDrop.IsChecked.Value) LogEvent(EventFireStrings.PreviewDrop, args);
        }

        private void LogEvent(string eventMessage, DragEventArgs args)
        {
            tbEventEvents.AppendText("[" + (++_eventCount) + eventMessage);

            if (cbVerbose.IsChecked.Value)
            {
                tbEventEvents.AppendText("     Source Object: " + args.Source + "\n");
                tbEventEvents.AppendText("     Drag Effects: " + args.Effects + "\n");
                tbEventEvents.AppendText("     Key States: " + args.KeyStates + "\n");
                tbEventEvents.AppendText("     Available Data Formats:\n");
                foreach (var format in args.Data.GetFormats())
                {
                    tbEventEvents.AppendText("          " + format + "\n");
                }
            }
            tbEventEvents.ScrollToEnd();
        }

        private struct EventFireStrings
        {
            public static readonly string DragEnter = "]: The DragEnter event just fired.\n";
            public static readonly string DragLeave = "]: The DragLeave event just fired.\n";
            public static readonly string DragOver = "]: The DragOver event just fired.\n";
            public static readonly string Drop = "]: The Drop event just fired.\n";
            public static readonly string PreviewDragEnter = "]: The PreviewDragEnter event just fired.\n";
            public static readonly string PreviewDragLeave = "]: The PreviewDragLeave event just fired.\n";
            public static readonly string PreviewDragOver = "]: The PreviewDragOver event just fired.\n";
            public static readonly string PreviewDrop = "]: The PreviewDrop event just fired.\n";
        }
    }
}

<|start_filename|>Data Binding/Colors/SourceToBoolConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace Colors
{
    // One-way conversion between ColorItem.Source and bool -
    // used to disable editing for builtin colors

    public class SourceToBoolConverter : IValueConverter
    {
        object IValueConverter.Convert(object o, Type type, object parameter, CultureInfo culture)
        {
            var source = (ColorItem.Sources) o;
            return (source != ColorItem.Sources.BuiltIn);
        }

        object IValueConverter.ConvertBack(object o, Type type, object parameter, CultureInfo culture) => null;
    }
}

<|start_filename|>Graphics/AITCodec/cpp/basedecoder.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Declaration of BaseDecoder
//----------------------------------------------------------------------------------------
#pragma once

#include "UnknownImpl.h"


class BaseFrameDecode : public IWICBitmapFrameDecode
{
public:
    BaseFrameDecode(IWICImagingFactory *pIFactory, UINT num);
    ~BaseFrameDecode();


    // IUnknown Interface
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv);
    STDMETHOD_(ULONG, AddRef)();
    STDMETHOD_(ULONG, Release)();


    // IWICBitmapFrameDecode Interface
    STDMETHOD(GetMetadataQueryReader)( 
        /* [out] */ IWICMetadataQueryReader **ppIMetadataQueryReader);

    STDMETHOD(GetColorContexts)(
        /* [in] */ UINT cCount,
        /* [in] [out] */ IWICColorContext **ppIColorContexts,
        /* [out] */ UINT *pcActualCount);

    STDMETHOD(GetThumbnail)( 
        /* [out] */ IWICBitmapSource **ppIThumbnail);

    // IWICBitmapSource Interface
    STDMETHOD(GetSize)( 
        /* [out] */ UINT *puiWidth,
        /* [out] */ UINT *puiHeight);

    STDMETHOD(GetPixelFormat)( 
        /* [out] */ WICPixelFormatGUID *pPixelFormat);

    STDMETHOD(GetResolution)( 
        /* [out] */ double *pDpiX,
        /* [out] */ double *pDpiY);

    STDMETHOD(CopyPalette)( 
        /* [in] */ IWICPalette *pIPalette);

    STDMETHOD(CopyPixels)( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels
        );
public:
    IWICImagingFactory             *factory;
    UINT                            frameNumber;
    IWICBitmapSource               *bitmapSource;
    IWICPalette                    *palette;
    std::vector<IWICColorContext*>  colorContexts;
    IWICBitmapSource               *thumbnail;
    IWICBitmapSource               *preview; 

private:
     void ReleaseMembers();
    UnknownImpl         unknownImpl;
};

class BaseDecoder : public IWICBitmapDecoder
{
public:
    BaseDecoder(GUID Me, GUID Container);
    ~BaseDecoder();


    // IUnknown Interface
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv);
    STDMETHOD_(ULONG, AddRef)();
    STDMETHOD_(ULONG, Release)();


    // IWICBitmapDecoder Interface
    STDMETHOD(QueryCapability)( 
        /* [in] */ IStream *pIStream,
        /* [out] */ DWORD *pCapability)=0;

    STDMETHOD(Initialize)( 
        /* [in] */ IStream *pIStream,
        /* [in] */ WICDecodeOptions cacheOptions)=0;

    STDMETHOD(GetContainerFormat)( 
        /* [out] */ GUID *pguidContainerFormat);

    STDMETHOD(GetDecoderInfo)( 
        /* [out] */ IWICBitmapDecoderInfo **ppIDecoderInfo);

    STDMETHOD(CopyPalette)( 
        /* [in] */ IWICPalette *pIPalette);

    STDMETHOD(GetMetadataQueryReader)( 
        /* [out] */ IWICMetadataQueryReader **ppIMetadataQueryReader);

    STDMETHOD(GetPreview)( 
        /* [out] */ IWICBitmapSource **ppIPreview);

    STDMETHOD(GetColorContexts)(
        /* [in] */ UINT cCount,
        /* [in] [out] */ IWICColorContext **ppIColorContexts,
        /* [out] */ UINT *pcActualCount);

    STDMETHOD(GetThumbnail)( 
        /* [out] */ IWICBitmapSource **ppIThumbnail);

    STDMETHOD(GetFrameCount)( 
        /* [out] */ UINT *pCount);

    STDMETHOD(GetFrame)( 
        /* [in] */ UINT index,
        /* [out] */ IWICBitmapFrameDecode **ppIBitmapFrame);

protected :
    //Additional functions
    virtual BaseFrameDecode* CreateNewDecoderFrame(IWICImagingFactory* factory , UINT i)=0; 
    virtual void AddDecoderFrame(BaseFrameDecode* frame); 
    HRESULT VerifyFactory();
    void ReleaseMembers(bool releaseFactory);   

    IWICImagingFactory             *factory;
    std::vector<BaseFrameDecode*>   frames;
    IWICPalette                    *palette;
    std::vector<IWICColorContext*>  colorContexts;
    IWICBitmapSource               *thumbnail;
    IWICBitmapSource               *preview;

    GUID CLSID_Container;
    GUID CLSID_This;

private:
    UnknownImpl                     unknownImpl;    
};


<|start_filename|>Migration and Interoperability/HostingAxInXaml/window1.xaml.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace HostingAxInWpfWithXaml
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            // Get the AxHost wrapper from the WindowsFormsHost control.
            AxWMPLib.AxWindowsMediaPlayer axWmp =
                wfh.Child as AxWMPLib.AxWindowsMediaPlayer;

            // Play a .wav file with the ActiveX control.
            axWmp.URL = @"C:\WINDOWS\Media\Windows XP Startup.wav";
        }
    }
}

//</snippet10>

<|start_filename|>Accessibility/FindText/FindText/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using Microsoft.Win32;

namespace FindText
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void LoadFile(object sender, RoutedEventArgs args)
        {
            var openFile = new OpenFileDialog
            {
                Filter = "FlowDocument Files (*.xaml)|*.xaml|All Files (*.*)|*.*",
                InitialDirectory = "Content"
            };

            if (openFile.ShowDialog().HasValue)
            {
                var xamlFile = openFile.OpenFile() as FileStream;
                if (xamlFile == null) return;
                FlowDocument content = null;
                try
                {
                    content = XamlReader.Load(xamlFile) as FlowDocument;
                    if (content == null)
                        throw (new XamlParseException("The specified file could not be loaded as a FlowDocument."));
                }
                catch (XamlParseException e)
                {
                    var error = "There was a problem parsing the specified file:\n\n";
                    error += openFile.FileName;
                    error += "\n\nException details:\n\n";
                    error += e.Message;
                    MessageBox.Show(error);
                    return;
                }
                catch (Exception e)
                {
                    var error = "There was a problem loading the specified file:\n\n";
                    error += openFile.FileName;
                    error += "\n\nException details:\n\n";
                    error += e.Message;
                    MessageBox.Show(error);
                    return;
                }

                // At this point, there is a non-null FlowDocument loaded into content.  
                FlowDocRdr.Document = content;
            }
        }

        private void SaveFile(object sender, RoutedEventArgs args)
        {
            var saveFile = new SaveFileDialog();
            FileStream xamlFile = null;
            saveFile.Filter = "FlowDocument Files (*.xaml)|*.xaml|All Files (*.*)|*.*";
            if (saveFile.ShowDialog().HasValue)
            {
                try
                {
                    xamlFile = saveFile.OpenFile() as FileStream;
                }
                catch (Exception e)
                {
                    var error = "There was a opening the file:\n\n";
                    error += saveFile.FileName;
                    error += "\n\nException details:\n\n";
                    error += e.Message;
                    MessageBox.Show(error);
                    return;
                }
                if (xamlFile == null) return;
                XamlWriter.Save(FlowDocRdr.Document, xamlFile);
                xamlFile.Close();
            }
        }

        private void Clear(object sender, RoutedEventArgs args)
        {
            FlowDocRdr.Document = null;
        }

        private void Exit(object sender, RoutedEventArgs args)
        {
            Close();
        }
    }
}

<|start_filename|>Styles & Templates/ContentControlStyle/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace ContentControlStyle
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            if (contCtrl.HasContent)
            {
                MessageBox.Show("contCtrl has content");
            }
        }
    }
}

<|start_filename|>Documents/Fixed Documents/DocumentMerge/DocumentItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.IO;
using System.Windows.Documents;
using System.Windows.Media;

namespace DocumentMerge
{
    public class DocumentItem
    {
        public DocumentItem(string documentPath, DocumentReference documentReference)
        {
            TooltipString = documentPath;
            DocumentReference = documentReference;
            FixedDocument = documentReference.GetDocument(true);
            var enumerator = FixedDocument.Pages.GetEnumerator();
            enumerator.MoveNext();
            _firstPage = enumerator.Current.GetPageRoot(true);
        }

        public DocumentItem(DocumentItem documentItem)
        {
            _firstPage = documentItem._firstPage;
            TooltipString = documentItem.DocumentPath;
            DocumentReference = documentItem.DocumentReference;
            FixedDocument = documentItem.FixedDocument;
        }

        public DocumentItem(FixedPage fixedPage)
        {
            _firstPage = fixedPage;
        }

        #region Public properties

        public string Info => Path.GetFileName(TooltipString);

        public string TooltipString { get; }

        public Brush PageBrush
        {
            get { return _pageBrush ?? (_pageBrush = new VisualBrush(_firstPage)); }
            set { _pageBrush = value; }
        }

        public DocumentReference DocumentReference { get; }

        public FixedDocument FixedDocument { get; }

        public string DocumentPath => TooltipString;

        #endregion

        #region priavate data

        private readonly FixedPage _firstPage;
        private Brush _pageBrush;

        #endregion private data
    }
}

<|start_filename|>Migration and Interoperability/WindowsFormsHostingWpfControl/WPFControls/MyControl.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFControls
{
    /// <summary>
    ///     Interaction logic for MyControl.xaml
    /// </summary>
    public partial class MyControl : UserControl
    {
        public delegate void MyControlEventHandler(object sender, MyControlEventArgs args);

        private SolidColorBrush _background;
        private FontFamily _fontFamily;
        private double _fontSize;
        private FontStyle _fontStyle;
        private FontWeight _fontWeight;
        private SolidColorBrush _foreground;

        public MyControl()
        {
            InitializeComponent();
        }

        public FontWeight MyControlFontWeight
        {
            get { return _fontWeight; }
            set
            {
                _fontWeight = value;
                nameLabel.FontWeight = value;
                addressLabel.FontWeight = value;
                cityLabel.FontWeight = value;
                stateLabel.FontWeight = value;
                zipLabel.FontWeight = value;
            }
        }

        public double MyControlFontSize
        {
            get { return _fontSize; }
            set
            {
                _fontSize = value;
                nameLabel.FontSize = value;
                addressLabel.FontSize = value;
                cityLabel.FontSize = value;
                stateLabel.FontSize = value;
                zipLabel.FontSize = value;
            }
        }

        public FontStyle MyControlFontStyle
        {
            get { return _fontStyle; }
            set
            {
                _fontStyle = value;
                nameLabel.FontStyle = value;
                addressLabel.FontStyle = value;
                cityLabel.FontStyle = value;
                stateLabel.FontStyle = value;
                zipLabel.FontStyle = value;
            }
        }

        public FontFamily MyControlFontFamily
        {
            get { return _fontFamily; }
            set
            {
                _fontFamily = value;
                nameLabel.FontFamily = value;
                addressLabel.FontFamily = value;
                cityLabel.FontFamily = value;
                stateLabel.FontFamily = value;
                zipLabel.FontFamily = value;
            }
        }

        public SolidColorBrush MyControlBackground
        {
            get { return _background; }
            set
            {
                _background = value;
                rootElement.Background = value;
            }
        }

        public SolidColorBrush MyControlForeground
        {
            get { return _foreground; }
            set
            {
                _foreground = value;
                nameLabel.Foreground = value;
                addressLabel.Foreground = value;
                cityLabel.Foreground = value;
                stateLabel.Foreground = value;
                zipLabel.Foreground = value;
            }
        }

        public event MyControlEventHandler OnButtonClick;

        private void Init(object sender, EventArgs e)
        {
            //They all have the same style, so use nameLabel to set initial values.
            _fontWeight = nameLabel.FontWeight;
            _fontSize = nameLabel.FontSize;
            _fontFamily = nameLabel.FontFamily;
            _fontStyle = nameLabel.FontStyle;
            _foreground = (SolidColorBrush) nameLabel.Foreground;
            _background = (SolidColorBrush) rootElement.Background;
        }

        private void ButtonClicked(object sender, RoutedEventArgs e)
        {
            var retvals = new MyControlEventArgs(true,
                txtName.Text,
                txtAddress.Text,
                txtCity.Text,
                txtState.Text,
                txtZip.Text);
            if (sender == btnCancel)
            {
                retvals.IsOk = false;
            }
            OnButtonClick?.Invoke(this, retvals);
        }
    }
}

<|start_filename|>Application Management/CustomApplication/CustomApplicationClient/CustomApplication.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace CustomApplicationClient
{
    public class CustomApplication : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MessageBox.Show(@"Hello, reusable custom application!");
        }
    }
}

<|start_filename|>Windows/Wizard/WizardPage3.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Navigation;

namespace Wizard
{
    public partial class WizardPage3 : PageFunction<WizardResult>
    {
        public WizardPage3(WizardData wizardData)
        {
            InitializeComponent();

            // Bind wizard state to UI
            DataContext = wizardData;
        }

        private void backButton_Click(object sender, RoutedEventArgs e)
        {
            // Go to previous wizard page
            NavigationService?.GoBack();
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            // Cancel the wizard and don't return any data
            OnReturn(new ReturnEventArgs<WizardResult>(WizardResult.Canceled));
        }

        private void finishButton_Click(object sender, RoutedEventArgs e)
        {
            // Finish the wizard and return bound data to calling page
            OnReturn(new ReturnEventArgs<WizardResult>(WizardResult.Finished));
        }
    }
}

<|start_filename|>Sample Applications/HtmlToXamlDemo/HtmlTokenType.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace HtmlToXamlDemo
{
    /// <summary>
    ///     types of lexical tokens for html-to-xaml converter
    /// </summary>
    internal enum HtmlTokenType
    {
        OpeningTagStart,
        ClosingTagStart,
        TagEnd,
        EmptyTagEnd,
        EqualSign,
        Name,
        Atom, // any attribute value not in quotes
        Text, //text content when accepting text
        Comment,
        Eof
    }
}

<|start_filename|>Input and Commands/TouchKeyboard/TouchKeyboardNotifier/InputPaneRcw.cs<|end_filename|>
﻿// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Windows.Input.TouchKeyboard.Rcw
{
    /// <summary>
    /// Contains internal RCWs for invoking the InputPane (tiptsf touch keyboard)
    /// </summary>
    internal static class InputPaneRcw
    {
        internal enum TrustLevel
        {
            BaseTrust,
            PartialTrust,
            FullTrust
        }

        [Guid("75CF2C57-9195-4931-8332-F0B409E916AF"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        [ComImport]
        internal interface IInputPaneInterop
        {
            [MethodImpl(MethodImplOptions.InternalCall)]
            void GetIids(out uint iidCount, [MarshalAs(UnmanagedType.LPStruct)] out Guid iids);

            [MethodImpl(MethodImplOptions.InternalCall)]
            void GetRuntimeClassName([MarshalAs(UnmanagedType.BStr)] out string className);

            [MethodImpl(MethodImplOptions.InternalCall)]
            void GetTrustLevel(out TrustLevel TrustLevel);

            [MethodImpl(MethodImplOptions.InternalCall)]
            IInputPane2 GetForWindow([In] IntPtr appWindow, [In] ref Guid riid);
        }

        [Guid("8A6B3F26-7090-4793-944C-C3F2CDE26276"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        [ComImport]
        internal interface IInputPane2
        {
            [MethodImpl(MethodImplOptions.InternalCall)]
            void GetIids(out uint iidCount, [MarshalAs(UnmanagedType.LPStruct)] out Guid iids);

            [MethodImpl(MethodImplOptions.InternalCall)]
            void GetRuntimeClassName([MarshalAs(UnmanagedType.BStr)] out string className);

            [MethodImpl(MethodImplOptions.InternalCall)]
            void GetTrustLevel(out TrustLevel TrustLevel);

            [MethodImpl(MethodImplOptions.InternalCall)]
            bool TryShow();

            [MethodImpl(MethodImplOptions.InternalCall)]
            bool TryHide();
        }
    }
}


<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/Horn.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    public sealed class Horn : FunctionMesh
    {
        public Horn(double scale)
        {
            Init(new MultExpression(new ConstantExpression(scale), FunctionParser.Parse("-(1+.15u cos(v))cos(u)")),
                new MultExpression(new ConstantExpression(scale), FunctionParser.Parse("(1+.15u cos(v))sin(u)")),
                new MultExpression(new ConstantExpression(scale), FunctionParser.Parse("-.15u sin(v)")),
                -Math.PI/2.0, 0.0, 0.0, 2*Math.PI);
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/basepixelformatconverter.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of BasePixelFormatConverter
//----------------------------------------------------------------------------------------
#include "precomp.hpp"

//IUnkown Interface
STDMETHODIMP_(ULONG) BasePixelFormatConverter::AddRef()
{
    return unknownImpl.AddRef();
}

STDMETHODIMP_(ULONG) BasePixelFormatConverter::Release()
{
    ULONG result = unknownImpl.Release();
    if (0 == result)
    {
        delete this;
    }
    return result;
}

STDMETHODIMP BasePixelFormatConverter::QueryInterface(REFIID iid, void **ppvObject)
{
    HRESULT result = E_INVALIDARG;

    if (ppvObject)
    {
        if (iid == IID_IUnknown)
        {
            *ppvObject = static_cast<IUnknown*>(this);
            AddRef();

            result = S_OK;
        }
        else if (iid == IID_IWICFormatConverter)
        {
            *ppvObject = static_cast<IWICFormatConverter*>(this);
            AddRef();

            result = S_OK;
        }
        else
        {
            result = E_NOINTERFACE;
        }
    }

    return result;
}


BasePixelFormatConverter::BasePixelFormatConverter()
: bitmapSource(NULL)
{
    memset(&destPixelFormat, 0, sizeof(GUID));
}

STDMETHODIMP BasePixelFormatConverter::Initialize( 
        /* [in] */ IWICBitmapSource *pISource,
        /* [in] */ REFWICPixelFormatGUID dstFormat,
        /* [in] */ WICBitmapDitherType dither,
        /* [in] */ IWICPalette *pIPalette,
        /* [in] */ double alphaThresholdPercent,
        /* [in] */ WICBitmapPaletteType paletteTranslate)
{
    if (NULL != bitmapSource)
    {
        bitmapSource->Release();
    }

    bitmapSource = pISource;
    destPixelFormat = dstFormat;

    if (NULL != bitmapSource)
    {
        bitmapSource->AddRef();
    }

    return S_OK;
}


STDMETHODIMP BasePixelFormatConverter::GetSize(
        /* [out] */ UINT *puiWidth,
        /* [out] */ UINT *puiHeight)
{
    HRESULT result = E_UNEXPECTED;

    if (NULL != bitmapSource)
    {
        result = bitmapSource->GetSize(puiWidth, puiHeight);
    }

    return result;
}

STDMETHODIMP BasePixelFormatConverter::GetPixelFormat( 
        /* [out] */ WICPixelFormatGUID *pPixelFormat)
{
    HRESULT result = E_UNEXPECTED;

    if (NULL != bitmapSource)
    {
        if (NULL != pPixelFormat)
        {
            result = S_OK;
            *pPixelFormat = destPixelFormat;
        }
        else
        {
            result = E_INVALIDARG;
        }
    }

    return result;
}

STDMETHODIMP BasePixelFormatConverter::GetResolution(
        /* [out] */ double *pDpiX,
        /* [out] */ double *pDpiY)
{
    HRESULT result = E_UNEXPECTED;

    if (NULL != bitmapSource)
    {
        result = bitmapSource->GetResolution(pDpiX, pDpiY);
    }

    return result;
}

STDMETHODIMP BasePixelFormatConverter::CopyPalette( 
        /* [in] */ IWICPalette *pIPalette)
{
    HRESULT result = E_UNEXPECTED;

    if (NULL != bitmapSource)
    {
        result = bitmapSource->CopyPalette(pIPalette);
    }

    return result;
}


<|start_filename|>Windows/NonRectangularWindow/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Input;

namespace NonRectangularWindow
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void NonRectangularWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void CloseButtonRectangle_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}

<|start_filename|>Elements/ContextMenuOpening/MyButton.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace ContextMenuOpening
{
    public class MyButton : Button
    {
        protected override void OnContextMenuOpening(ContextMenuEventArgs e)
        {
            base.OnContextMenuOpening(e);
            var buttonMenu = new ContextMenu();
            var mia = new MenuItem {Header = "Item1"};
            var mib = new MenuItem {Header = "Item2"};
            var mic = new MenuItem {Header = "Item3"};
            buttonMenu.Items.Add(mia);
            buttonMenu.Items.Add(mib);
            buttonMenu.Items.Add(mic);
            var fe = e.Source as FrameworkElement;
            fe.ContextMenu = buttonMenu;
        }
    }
}

<|start_filename|>Windows/Wizard/WizardReturnEventHandler.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Wizard
{
    public delegate void WizardReturnEventHandler(object sender, WizardReturnEventArgs e);
}

<|start_filename|>Migration and Interoperability/WPFWithWFAndDatabinding/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Forms;
using WPFWithWFAndDatabinding.NorthwindDataSetTableAdapters;

namespace WPFWithWFAndDatabinding
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly CustomersTableAdapter _customersTableAdapter =
            new CustomersTableAdapter();

        private readonly BindingSource _nwBindingSource;
        private readonly NorthwindDataSet _nwDataSet;

        private readonly OrdersTableAdapter _ordersTableAdapter =
            new OrdersTableAdapter();

        public MainWindow()
        {
            InitializeComponent();

            // Create a DataSet for the Customers data.
            _nwDataSet = new NorthwindDataSet {DataSetName = "nwDataSet"};

            // Create a BindingSource for the Customers data.
            _nwBindingSource = new BindingSource
            {
                DataMember = "Customers",
                DataSource = _nwDataSet
            };
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            // Fill the Customers table adapter with data.
            _customersTableAdapter.ClearBeforeFill = true;
            _customersTableAdapter.Fill(_nwDataSet.Customers);

            // Fill the Orders table adapter with data.
            _ordersTableAdapter.Fill(_nwDataSet.Orders);

            // Assign the BindingSource to 
            // the data context of the main grid.
            mainGrid.DataContext = _nwBindingSource;

            // Assign the BindingSource to 
            // the data source of the list box.
            listBox1.ItemsSource = _nwBindingSource;

            // Because this is a master/details form, the DataGridView
            // requires the foreign key relating the tables.
            dataGridView1.DataSource = _nwBindingSource;
            dataGridView1.DataMember = "FK_Orders_Customers";

            // Handle the currency management aspect of the data models.
            // Attach an event handler to detect when the current item 
            // changes via the WPF ListBox. This event handler synchronizes
            // the list collection with the BindingSource.
            //

            var cv = CollectionViewSource.GetDefaultView(
                _nwBindingSource) as BindingListCollectionView;

            cv.CurrentChanged += WPF_CurrentChanged;
        }

        // This event handler updates the current item 
        // of the data binding.
        private void WPF_CurrentChanged(object sender, EventArgs e)
        {
            var cv = sender as BindingListCollectionView;
            _nwBindingSource.Position = cv.CurrentPosition;
        }
    }
}

<|start_filename|>Graphics/DrawingBrush/SampleViewer.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace DrawingBrush
{
    public partial class SampleViewer : Window
    {
        public SampleViewer()
        {
            InitializeComponent();
        }

        private void SampleSelected(object sender, RoutedEventArgs args)
        {
            var rButton = sender as RadioButton;

            var buttonContent = (string) rButton?.Content;

            if (buttonContent != null)
            {
                if (buttonContent == "Using DrawingBrush Example")
                    mainFrame.Navigate(new DrawingBrushExample());
                else if (buttonContent == "Transform Example")
                    mainFrame.Navigate(new TransformExample());
                else if (buttonContent == "ImageDrawing Example")
                    mainFrame.Navigate(new ImageBrushExample());
                else
                    mainFrame.Navigate(new AnimateGeometryDrawingExample());
            }
        }

        private void ExitApplication(object sender, RoutedEventArgs args)
        {
            Application.Current.Shutdown();
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/TokenType.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    public enum TokenType
    {
        None = 0x0,
        Constant = 0x1,
        Variable = 0x2,
        Plus = 0x4,
        Minus = 0x8,
        Multiply = 0x10,
        Divide = 0x20,
        Exponent = 0x40,
        Sine = 0x80,
        Cosine = 0x100,
        Tangent = 0x200,
        OpenParen = 0x400,
        CloseParen = 0x800,
        Eof = 0x1000
    }
}

<|start_filename|>Data Binding/ValidateItemSample/FutureDateRule.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Controls;

namespace ValidateItemSample
{
    internal class FutureDateRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            DateTime date;
            try
            {
                date = DateTime.Parse(value?.ToString());
            }
            catch (FormatException)
            {
                return new ValidationResult(false, "Value is not a valid date.");
            }
            return DateTime.Now.Date > date
                ? new ValidationResult(false, "Please enter a date in the future.")
                : ValidationResult.ValidResult;
        }
    }
}

<|start_filename|>Migration and Interoperability/Win32HostingWPFPage/cpp/win32hostingwpfpage.cpp<|end_filename|>
// Win32HostingWPFPage.cpp : Defines the entry point for the application.
//
using namespace System;
using namespace System::Windows;
using namespace System::Windows::Controls;
using namespace System::Windows::Media;
using namespace System::Runtime;

#include "stdafx.h"
#include "Win32HostingWPFPage.h"
#include <gcroot.h>

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE hInst;                                // current instance
TCHAR szTitle[MAX_LOADSTRING];                    // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name
HWND wpfHwnd; //The hwnd associated with the hosted WPF page

// Forward declarations of functions included in this code module:
ATOM                MyRegisterClass(HINSTANCE hInstance);
BOOL                InitInstance(HINSTANCE, int);
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);
[System::STAThreadAttribute] //Needs to be an STA thread to play nicely with WPF
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    // TODO: Place code here.

    MSG msg;
    HACCEL hAccelTable;

    // Initialize global strings
    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadString(hInstance, IDC_WIN32HOSTINGWPFPAGE, szWindowClass, MAX_LOADSTRING);
    MyRegisterClass(hInstance);

    // Perform application initialization:
    if (!InitInstance (hInstance, nCmdShow))
    {
        return FALSE;
    }

    hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32HOSTINGWPFPAGE));

    // Main message loop:
    while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style         = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc   = WndProc;
    wcex.cbClsExtra    = 0;
    wcex.cbWndExtra    = 0;
    wcex.hInstance     = hInstance;
    wcex.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32HOSTINGWPFPAGE));
    wcex.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)(COLOR_BTNSHADOW);
    wcex.lpszMenuName  = MAKEINTRESOURCE(IDC_WIN32HOSTINGWPFPAGE);
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm       = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
    HWND hWnd;

    hInst = hInstance; // Store instance handle in our global variable

    hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

    if (!hWnd)
    {
        return FALSE;
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND    - process the application menu
//  WM_PAINT    - Paint the main window
//  WM_DESTROY    - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
      case WM_CREATE :
        GetClientRect(hWnd, &rect);
        wpfHwnd = GetHwnd(hWnd, rect.right-375, 0, 375, 250);
        CreateDataDisplay(hWnd, 275, rect.right-375, 375);
        CreateRadioButtons(hWnd);
      break;
      case WM_COMMAND:
        wmId    = LOWORD(wParam);
        wmEvent = HIWORD(wParam);

        switch (wmId)
        {
        //Menu selections
          case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
          break;
          case IDM_EXIT:
            DestroyWindow(hWnd);
          break;
          //RadioButtons
          case IDC_ORIGINALBACKGROUND :
            WPFPageHost::hostedPage->Background = WPFPageHost::initBackBrush;
          break;
          case IDC_LIGHTGREENBACKGROUND :
            WPFPageHost::hostedPage->Background = gcnew SolidColorBrush(Colors::LightGreen);
          break;
          case IDC_LIGHTSALMONBACKGROUND :
            WPFPageHost::hostedPage->Background = gcnew SolidColorBrush(Colors::LightSalmon);
          break;

          case IDC_ORIGINALFONTFAMILY :
            WPFPageHost::hostedPage->DefaultFontFamily = WPFPageHost::initFontFamily;
          break;
          case IDC_TIMESNEWROMAN :
            WPFPageHost::hostedPage->DefaultFontFamily = gcnew FontFamily("Times New Roman");
          break;
          case IDC_WINGDINGS:
            WPFPageHost::hostedPage->DefaultFontFamily = gcnew FontFamily("WingDings");
          break;
          case IDC_ORIGINALFONTSTYLE :
            WPFPageHost::hostedPage->DefaultFontStyle = WPFPageHost::initFontStyle;
          break;
          case IDC_ITALIC :
            WPFPageHost::hostedPage->DefaultFontStyle = System::Windows::FontStyles::Italic;
          break;
          case IDC_ORIGINALFONTSIZE :
            WPFPageHost::hostedPage->DefaultFontSize = WPFPageHost::initFontSize;
          break;
          case IDC_TENPOINT :
            WPFPageHost::hostedPage->DefaultFontSize = 10;
          break;
          case IDC_TWELVEPOINT :
            WPFPageHost::hostedPage->DefaultFontSize = 12;
          break;
          case IDC_ORIGINALFONTWEIGHT :
            WPFPageHost::hostedPage->DefaultFontWeight = WPFPageHost::initFontWeight;
          break;
          case IDC_BOLD :
            WPFPageHost::hostedPage->DefaultFontWeight = FontWeights::Bold;
          break;
          case IDC_ORIGINALFOREGROUND :
            WPFPageHost::hostedPage->DefaultForeBrush = WPFPageHost::initForeBrush;
          break;
          case IDC_REDFOREGROUND :
            WPFPageHost::hostedPage->DefaultForeBrush = gcnew SolidColorBrush(Colors::Red);
          break;
          case IDC_YELLOWFOREGROUND :
            WPFPageHost::hostedPage->DefaultForeBrush = gcnew SolidColorBrush(Colors::Yellow);
          break;
          default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
      break;
      case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        // TODO: Add any drawing code here...
        EndPaint(hWnd, &ps);
      break;
      case WM_DESTROY:
        PostQuitMessage(0);
      break;
      default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
      case WM_INITDIALOG:
        return (INT_PTR)TRUE;

      case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
      break;
    }
    return (INT_PTR)FALSE;
}

WPFPageHost::WPFPageHost(){} 
HWND GetHwnd(HWND parent, int x, int y, int width, int height)
{
    System::Windows::Interop::HwndSourceParameters^ sourceParams = gcnew System::Windows::Interop::HwndSourceParameters(
    "hi" // NAME
    );
    sourceParams->PositionX = x;
    sourceParams->PositionY = y;
    sourceParams->Height = height;
    sourceParams->Width = width;
    sourceParams->ParentWindow = IntPtr(parent);
    sourceParams->WindowStyle = WS_VISIBLE | WS_CHILD; // style
    System::Windows::Interop::HwndSource^ source = gcnew System::Windows::Interop::HwndSource(*sourceParams);
    WPFPage ^myPage = gcnew WPFPage(width, height);
    //Assign a reference to the WPF page and a set of UI properties to a set of static properties in a class
    //that is designed for that purpose.
    WPFPageHost::hostedPage = myPage;
    WPFPageHost::initBackBrush = myPage->Background;
    WPFPageHost::initFontFamily = myPage->DefaultFontFamily;
    WPFPageHost::initFontSize = myPage->DefaultFontSize;
    WPFPageHost::initFontStyle = myPage->DefaultFontStyle;
    WPFPageHost::initFontWeight = myPage->DefaultFontWeight;
    WPFPageHost::initForeBrush = myPage->DefaultForeBrush;
    myPage->OnButtonClicked += gcnew WPFPage::ButtonClickHandler(WPFButtonClicked);
    source->RootVisual = myPage;
    return (HWND) source->Handle.ToPointer();
}
void WPFButtonClicked(Object ^sender, MyPageEventArgs ^args)
{
    if(args->IsOK) //display data if OK button was clicked
    {
        WPFPage ^myPage = WPFPageHost::hostedPage;
        LPCWSTR userName = (LPCWSTR) InteropServices::Marshal::StringToHGlobalAuto("Name: " + myPage->EnteredName).ToPointer();
        SetWindowText(nameLabel, userName);
        LPCWSTR userAddress = (LPCWSTR) InteropServices::Marshal::StringToHGlobalAuto("Address: " + myPage->EnteredAddress).ToPointer();
        SetWindowText(addressLabel, userAddress);
        LPCWSTR userCity = (LPCWSTR) InteropServices::Marshal::StringToHGlobalAuto("City: " + myPage->EnteredCity).ToPointer();
        SetWindowText(cityLabel, userCity);
        LPCWSTR userState = (LPCWSTR) InteropServices::Marshal::StringToHGlobalAuto("State: " + myPage->EnteredState).ToPointer();
        SetWindowText(stateLabel, userState);
        LPCWSTR userZip = (LPCWSTR) InteropServices::Marshal::StringToHGlobalAuto("Zip: " + myPage->EnteredZip).ToPointer();
        SetWindowText(zipLabel, userZip);
    }
    else
    {
        SetWindowText(nameLabel, L"Name: ");
        SetWindowText(addressLabel, L"Address: ");
        SetWindowText(cityLabel, L"City: ");
        SetWindowText(stateLabel, L"State: ");
        SetWindowText(zipLabel, L"Zip: ");
    }
}

void CreateDataDisplay(HWND hWnd, int top, int left, int width)
{
    dataDisplayLabel = CreateWindowEx(0, L"static", L"Data From WPF Control",
                                      WS_CHILD | WS_VISIBLE | SS_LEFT,
                                      left, top+25,
                                      width, 25,
                                      hWnd,
                                      (HMENU) 1,
                                      hInst,
                                      NULL);

    nameLabel =        CreateWindowEx(0, L"static", L"Name: ",
                                      WS_CHILD | WS_VISIBLE | SS_LEFT,
                                      left, top+60,
                                      width, 25,
                                      hWnd,
                                     (HMENU) 1,
                                      hInst,
                                      NULL);

    addressLabel =     CreateWindowEx(0, L"static", L"Address: ",
                                      WS_CHILD | WS_VISIBLE | SS_LEFT,
                                      left, top+85,
                                      width, 25,
                                      hWnd,
                                      (HMENU) 1,
                                      hInst,
                                      NULL);
    cityLabel =        CreateWindowEx(0, L"static", L"City: ",
                                      WS_CHILD | WS_VISIBLE | SS_LEFT,
                                      left, top+110,
                                      width, 25,
                                      hWnd,
                                      (HMENU) 1,
                                      hInst,
                                      NULL);
  
    stateLabel =       CreateWindowEx(0, L"static", L"State: ",
                                      WS_CHILD | WS_VISIBLE | SS_LEFT,
                                      left, top+135,
                                      width, 25,
                                      hWnd,
                                      (HMENU) 1,
                                      hInst,
                                      NULL);
  
    zipLabel =         CreateWindowEx(0, L"static", L"Zip: ",
                                      WS_CHILD | WS_VISIBLE | SS_LEFT,
                                      left, top+160,
                                      width, 25,
                                      hWnd,
                                      (HMENU) 1,
                                      hInst,
                                      NULL);
  
}

void CreateRadioButtons(HWND hWnd)
{
    //Background color
    int top = 25;
    controlDisplayLabel = CreateWindowEx(0, L"static", L"ControlProperties",
                                      WS_CHILD | WS_VISIBLE | SS_LEFT,
                                      10, top,
                                      125, 25,
                                      hWnd,
                                      NULL,
                                      hInst,
                                      NULL);

    //Background radio buttons
    top += 35;
    backgroundGroup =  CreateWindowEx(0, L"button", L"Background Color",
                                      WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
                                      10, top,
                                      175, 100,
                                      hWnd,
                                      (HMENU) IDC_ORIGINALBACKGROUND,
                                      hInst,
                                      NULL);
    top += 20;
    originalBackgroundButton = CreateWindowEx(0, L"button", L"Original",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      125, 25,
                                      hWnd,
                                      (HMENU) IDC_ORIGINALBACKGROUND,
                                      hInst,
                                      NULL);
    top += 20;
    lightGreenBackgroundButton = CreateWindowEx(0, L"button", L"Light Green",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      125, 25,
                                      hWnd,
                                      (HMENU) IDC_LIGHTGREENBACKGROUND,
                                      hInst,
                                      NULL);

    top += 20;
    lightSalmonBackgroundButton = CreateWindowEx(0, L"button", L"Light Salmon",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      125, 25,
                                      hWnd,
                                      (HMENU) IDC_LIGHTSALMONBACKGROUND,
                                      hInst,
                                      NULL);
    //Foreground color
    top += 45;
    foregroundGroup =  CreateWindowEx(0, L"button", L"Foreground Color",
                                      WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
                                      10, top,
                                      175, 100,
                                      hWnd,
                                      NULL,
                                      hInst,
                                      NULL);
    top += 20;
    originalForegroundButton = CreateWindowEx(0, L"button", L"Original",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      125, 25,
                                      hWnd,
                                      (HMENU) IDC_ORIGINALFOREGROUND,
                                      hInst,
                                      NULL);
    top += 20;
    redForegroundButton = CreateWindowEx(0, L"button", L"Red",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      125, 25,
                                      hWnd,
                                      (HMENU) IDC_REDFOREGROUND,
                                      hInst,
                                      NULL);

    top += 20;
    yellowForegroundButton = CreateWindowEx(0, L"button", L"Yellow",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      125, 25,
                                      hWnd,
                                      (HMENU) IDC_YELLOWFOREGROUND,
                                      hInst,
                                      NULL);

    //Font family
    top += 45;
    fontFamilyGroup =  CreateWindowEx(0, L"button", L"Font Family",
                                      WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
                                      10, top,
                                      175, 100,
                                      hWnd,
                                      NULL,
                                      hInst,
                                      NULL);
    top += 20;
    originalFontFamily = CreateWindowEx(0, L"button", L"Original",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      125, 25,
                                      hWnd,
                                      (HMENU) IDC_ORIGINALFONTFAMILY,
                                      hInst,
                                      NULL);
    top += 20;
    timesFontFamily = CreateWindowEx(0, L"button", L"Times New Roman",
                                      WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                      15, top,
                                      140, 25,
                                      hWnd,
                                      (HMENU) IDC_TIMESNEWROMAN,
                                      hInst,
                                      NULL);

    top += 20;
    wingdingsFontFamily = CreateWindowEx(0, L"button", L"WingDings",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_WINGDINGS,
                                     hInst,
                                     NULL);

    //Font size
    top += 45;
    fontSizeGroup =   CreateWindowEx(0, L"button", L"Font Size",
                                     WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
                                     10, top,
                                     175, 100,
                                     hWnd,
                                     NULL,
                                     hInst,
                                     NULL);
    top += 20;
    originalFontSize = CreateWindowEx(0, L"button", L"Original",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_ORIGINALFONTSIZE,
                                     hInst,
                                     NULL);
    top += 20;
    tenpointFontSize = CreateWindowEx(0, L"button", L"10",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_TENPOINT,
                                     hInst,
                                     NULL);

    top += 20;
    twelvepointFontSize = CreateWindowEx(0, L"button", L"12",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_TWELVEPOINT,
                                     hInst,
                                     NULL);

    //Font style
    top += 45;
    fontStyleGroup = CreateWindowEx(0, L"button", L"Font Style",
                                     WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
                                     10, top,
                                     175, 70,
                                     hWnd,
                                     NULL,
                                     hInst,
                                     NULL);
    top += 20;
    originalFontStyle = CreateWindowEx(0, L"button", L"Original",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_ORIGINALFONTSTYLE,
                                     hInst,
                                     NULL);
    top += 20;
    italicFontStyle = CreateWindowEx(0, L"button", L"Italic",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_ITALIC,
                                     hInst,
                                     NULL);

    //Font weight
    top += 45;
    fontWeightGroup = CreateWindowEx(0, L"button", L"Font Weight",
                                     WS_CHILD | WS_VISIBLE | BS_GROUPBOX,
                                     10, top,
                                     175, 70,
                                     hWnd,
                                     NULL,
                                     hInst,
                                     NULL);
    top += 20;
    originalFontWeight = CreateWindowEx(0, L"button", L"Original",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_ORIGINALFONTWEIGHT,
                                     hInst,
                                     NULL);
    top += 20;
    boldFontWeight =  CreateWindowEx(0, L"button", L"Bold",
                                     WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON,
                                     15, top,
                                     125, 25,
                                     hWnd,
                                     (HMENU) IDC_BOLD,
                                     hInst,
                                     NULL);
}

<|start_filename|>PerMonitorDPI/WinFormsHost/MainWindow.xaml.cs<|end_filename|>
﻿using System;
using System.Windows;
using System.Windows.Forms.Integration;

namespace WinFormsHost
{
    /// <summary>
    /// This sample works with the Per Monitor DPI 11/2015 Preview of WPF.
    /// It shows how a developer can use WPF's Per Monitor DPI Aware APIs to
    /// perform scaling of WinForms content in a WPF app.
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            winFormsHost.DpiChanged += WinFormsHost_DpiChanged;
        }

        private void WinFormsHost_DpiChanged(object sender, DpiChangedEventArgs e)
        {
            System.Windows.Forms.Control control = ((WindowsFormsHost)sender).Child;

            float scaleFactor = (float) (e.NewDpi.PixelsPerDip / e.OldDpi.PixelsPerDip);
            
            // This method recursively scales all child Controls.
            control.Scale(new System.Drawing.SizeF(scaleFactor, scaleFactor));;
            
            // Scale the root control's font
            ScaleFont(control, scaleFactor);

            // Recursively scale the font of controls with different fonts
            ScaleFontRecursively(control, scaleFactor);
        }

        private void ScaleFont(System.Windows.Forms.Control control, float scaleFactor)
        {
            control.Font = new System.Drawing.Font(control.Font.FontFamily,
                                                   control.Font.Size * scaleFactor,
                                                   control.Font.Style
                                                   );
        }

        private void ScaleFontRecursively(System.Windows.Forms.Control parentControl, float scaleFactor)
        {
            System.Drawing.Font parentFont = parentControl.Font;
            foreach (System.Windows.Forms.Control control in parentControl.Controls)
            {
                // Scale the font only if it is different from the parent control's font.
                if (!Object.ReferenceEquals(control.Font, parentFont))
                {
                    ScaleFont(control, scaleFactor);
                }

                ScaleFontRecursively(control, scaleFactor);
            }
        }
    }
}


<|start_filename|>Sample Applications/PhotoStoreDemo/GreetingCard.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Media.Imaging;

namespace PhotoStoreDemo
{
    public class GreetingCard : PrintBase
    {
        public GreetingCard(BitmapSource photo) : base(photo, "Greeting Card", 1.49)
        {
        }
    }
}

<|start_filename|>Animation/AnimationExamples/BounceDoubleAnimation.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace AnimationExamples
{
    /// <summary>
    ///     BounceDoubleAnimation
    /// </summary>
    public class BounceDoubleAnimation : DoubleAnimationBase
    {
        public enum EdgeBehaviorEnum
        {
            EaseIn,
            EaseOut,
            EaseInOut
        }

        public static readonly DependencyProperty EdgeBehaviorProperty =
            DependencyProperty.Register("EdgeBehavior",
                typeof (EdgeBehaviorEnum),
                typeof (BounceDoubleAnimation),
                new PropertyMetadata(EdgeBehaviorEnum.EaseInOut));

        public static readonly DependencyProperty BouncesProperty =
            DependencyProperty.Register("Bounces",
                typeof (int),
                typeof (BounceDoubleAnimation),
                new PropertyMetadata(5));

        public static readonly DependencyProperty BouncinessProperty =
            DependencyProperty.Register("Bounciness",
                typeof (double),
                typeof (BounceDoubleAnimation),
                new PropertyMetadata(3.0));

        public static readonly DependencyProperty FromProperty =
            DependencyProperty.Register("From",
                typeof (double?),
                typeof (BounceDoubleAnimation),
                new PropertyMetadata(null));

        public static readonly DependencyProperty ToProperty =
            DependencyProperty.Register("To",
                typeof (double?),
                typeof (BounceDoubleAnimation),
                new PropertyMetadata(null));

        /// <summary>
        ///     Specifies which side of the transition gets the "bounce" effect.
        /// </summary>
        public EdgeBehaviorEnum EdgeBehavior
        {
            get { return (EdgeBehaviorEnum) GetValue(EdgeBehaviorProperty); }
            set { SetValue(EdgeBehaviorProperty, value); }
        }

        /// <summary>
        ///     Number of bounces in the effect
        /// </summary>
        public int Bounces
        {
            get { return (int) GetValue(BouncesProperty); }
            set
            {
                if (value > 0)
                {
                    SetValue(BouncesProperty, value);
                }
                else
                {
                    throw new ArgumentException("can't set the bounces to " + value);
                }
            }
        }

        /// <summary>
        ///     Specifies the amount by which the element springs back.
        /// </summary>
        public double Bounciness
        {
            get { return (double) GetValue(BouncinessProperty); }
            set
            {
                if (value > 0)
                {
                    SetValue(BouncinessProperty, value);
                }
                else
                {
                    throw new ArgumentException("can't set the bounciness to " + value);
                }
            }
        }

        /// <summary>
        ///     Specifies the starting value of the animation.
        /// </summary>
        public double? From
        {
            get { return (double?) GetValue(FromProperty); }
            set { SetValue(FromProperty, value); }
        }

        /// <summary>
        ///     Specifies the ending value of the animation.
        /// </summary>
        public double? To
        {
            get { return (double?) GetValue(ToProperty); }
            set { SetValue(ToProperty, value); }
        }

        protected override double GetCurrentValueCore(
            double defaultOriginValue,
            double defaultDestinationValue,
            AnimationClock clock)
        {
            double returnValue;
            var start = From ?? defaultOriginValue;
            var delta = To - start ?? defaultOriginValue - start;

            switch (EdgeBehavior)
            {
                case EdgeBehaviorEnum.EaseIn:
                    returnValue = EaseIn(clock.CurrentProgress.Value, start, delta, Bounciness, Bounces);
                    break;
                case EdgeBehaviorEnum.EaseOut:
                    returnValue = EaseOut(clock.CurrentProgress.Value, start, delta, Bounciness, Bounces);
                    break;
                default:
                    returnValue = EaseInOut(clock.CurrentProgress.Value, start, delta, Bounciness, Bounces);
                    break;
            }
            return returnValue;
        }

        protected override Freezable CreateInstanceCore() => new BounceDoubleAnimation();

        private static double EaseOut(double timeFraction, double start, double delta, double bounciness, int bounces)
        {
            // math magic: The cosine gives us the right wave, the timeFraction is the frequency of the wave, 
            // the absolute value keeps every value positive (so it "bounces" off the midpoint of the cosine 
            // wave, and the amplitude (the exponent) makes the sine wave get smaller and smaller at the end.
            var returnValue = Math.Abs(Math.Pow((1 - timeFraction), bounciness)
                                       *Math.Cos(2*Math.PI*timeFraction*bounces));
            returnValue = delta - (returnValue*delta);
            returnValue += start;
            return returnValue;
        }

        private static double EaseIn(double timeFraction, double start, double delta, double bounciness, int bounces)
        {
            // math magic: The cosine gives us the right wave, the timeFraction is the amplitude of the wave, 
            // the absolute value keeps every value positive (so it "bounces" off the midpoint of the cosine 
            // wave, and the amplitude (the exponent) makes the sine wave get bigger and bigger towards the end.
            var returnValue = Math.Abs(Math.Pow((timeFraction), bounciness)
                                       *Math.Cos(2*Math.PI*timeFraction*bounces));
            returnValue = returnValue*delta;
            returnValue += start;
            return returnValue;
        }

        private static double EaseInOut(double timeFraction, double start, double delta, double bounciness, int bounces)
        {
            double returnValue;

            // we cut each effect in half by multiplying the time fraction by two and halving the distance.
            if (timeFraction <= 0.5)
            {
                returnValue = EaseIn(timeFraction*2, start, delta/2, bounciness, bounces);
            }
            else
            {
                returnValue = EaseOut((timeFraction - 0.5)*2, start, delta/2, bounciness, bounces);
                returnValue += delta/2;
            }
            return returnValue;
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/WrappingXamlReader.cs<|end_filename|>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Xaml;

namespace BamlTools
{
    // Provides the 140 lines of boilerplate code that
    // will return infoset nodes from either a wrapped _reader
    // or from an XamlNodeQueue.

    // There is nothing in here the user could not write herself.

    abstract public class WrappingXamlReader : XamlReader
    {
        XamlNodeQueue _xamlNodeQueue;
        XamlReader _wrappedReader;
        bool _skipCurrentNode;

        public WrappingXamlReader(XamlSchemaContext xamlSchemaContext)
        {
            _xamlNodeQueue = new XamlNodeQueue(xamlSchemaContext);
        }

        public XamlNodeQueue XamlNodeQueue
        {
            get { return _xamlNodeQueue; }
        }

        protected void SetWrappedReader(XamlReader reader)
        {
            _wrappedReader = reader;
        }

        protected bool SkipCurrentNode
        {
            get { return _skipCurrentNode; }
            set { _skipCurrentNode = value; }
        }

        #region XamlReader Members

        // The Read method is left for the derived class to implement

        // abstract public bool Read();

        public override XamlNodeType NodeType
        {
            get
            {
                if (_skipCurrentNode)
                {
                    return _xamlNodeQueue.Reader.NodeType;
                }
                else
                {
                    return _wrappedReader.NodeType;
                }
            }
        }

        public override bool IsEof
        {
            get
            {
                if (_skipCurrentNode)
                {
                    return _xamlNodeQueue.Reader.IsEof;
                }
                else
                {
                    return _wrappedReader.IsEof;
                }
            }
        }


        public override NamespaceDeclaration Namespace
        {
            get
            {
                if (_skipCurrentNode)
                {
                    return _xamlNodeQueue.Reader.Namespace;
                }
                else
                {
                    return _wrappedReader.Namespace;
                }
            }
        }

        public override XamlType Type
        {
            get
            {
                if (_skipCurrentNode)
                {
                    return _xamlNodeQueue.Reader.Type;
                }
                else
                {
                    return _wrappedReader.Type;
                }
            }
        }

        public override object Value
        {
            get
            {
                if (_skipCurrentNode)
                {
                    return _xamlNodeQueue.Reader.Value;
                }
                else
                {
                    return _wrappedReader.Value;
                }
            }
        }

        public override XamlMember Member
        {
            get
            {
                if (_skipCurrentNode)
                {
                    return _xamlNodeQueue.Reader.Member;
                }
                else
                {
                    return _wrappedReader.Member;
                }
            }
        }

        public override XamlSchemaContext SchemaContext
        {
            get { return _wrappedReader.SchemaContext; }
        }

        #endregion
    }
}


<|start_filename|>Input and Commands/ICommandSourceImplementation/commandslider.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ICommandSourceImplementation
{
    public class CommandSlider : Slider, ICommandSource
    {
        // ICommand Interface Memembers
        // Make Command a dependency property so it can use databinding.
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register(
                "Command",
                typeof (ICommand),
                typeof (CommandSlider),
                new PropertyMetadata(null,
                    CommandChanged));

        // Make CommandTarget a dependency property so it can use databinding.
        public static readonly DependencyProperty CommandTargetProperty =
            DependencyProperty.Register(
                "CommandTarget",
                typeof (IInputElement),
                typeof (CommandSlider),
                new PropertyMetadata((IInputElement) null));

        // Make CommandParameter a dependency property so it can use databinding.
        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register(
                "CommandParameter",
                typeof (object),
                typeof (CommandSlider),
                new PropertyMetadata((object) null));

        // Keep a copy of the handler so it doesn't get garbage collected.
        private static EventHandler _canExecuteChangedHandler;

        public ICommand Command
        {
            get { return (ICommand) GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        public IInputElement CommandTarget
        {
            get { return (IInputElement) GetValue(CommandTargetProperty); }
            set { SetValue(CommandTargetProperty, value); }
        }

        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        // Command dependency property change callback.
        private static void CommandChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var cs = (CommandSlider) d;
            cs.HookUpCommand((ICommand) e.OldValue, (ICommand) e.NewValue);
        }

        // Add a new command to the Command Property.
        private void HookUpCommand(ICommand oldCommand, ICommand newCommand)
        {
            // If oldCommand is not null, then we need to remove the handlers.
            if (oldCommand != null)
            {
                RemoveCommand(oldCommand, newCommand);
            }
            AddCommand(oldCommand, newCommand);
        }

        // Remove an old command from the Command Property.
        private void RemoveCommand(ICommand oldCommand, ICommand newCommand)
        {
            EventHandler handler = CanExecuteChanged;
            oldCommand.CanExecuteChanged -= handler;
        }

        // Add the command.
        private void AddCommand(ICommand oldCommand, ICommand newCommand)
        {
            var handler = new EventHandler(CanExecuteChanged);
            _canExecuteChangedHandler = handler;
            if (newCommand != null)
            {
                newCommand.CanExecuteChanged += _canExecuteChangedHandler;
            }
        }

        private void CanExecuteChanged(object sender, EventArgs e)
        {
            if (Command != null)
            {
                var command = Command as RoutedCommand;

                // If a RoutedCommand.
                IsEnabled = command?.CanExecute(CommandParameter, CommandTarget) ?? Command.CanExecute(CommandParameter);
            }
        }

        // If Command is defined, moving the slider will invoke the command;
        // Otherwise, the slider will behave normally.
        protected override void OnValueChanged(double oldValue, double newValue)
        {
            base.OnValueChanged(oldValue, newValue);

            if (Command != null)
            {
                var command = Command as RoutedCommand;

                if (command != null)
                {
                    command.Execute(CommandParameter, CommandTarget);
                }
                else
                {
                    Command.Execute(CommandParameter);
                }
            }
        }
    }
}

<|start_filename|>Migration and Interoperability/WpfLayoutHostingWfWithXaml/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Drawing;
using System.Windows;
using System.Windows.Forms;

namespace WpfLayoutHostingWfWithXaml
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button1Click(object sender, EventArgs e)
        {
            var b = sender as Button;

            b.Top = 20;
            b.Left = 20;
        }

        private void Button2Click(object sender, EventArgs e)
        {
            host1.Visibility = Visibility.Hidden;
        }

        private void Button3Click(object sender, EventArgs e)
        {
            host1.Visibility = Visibility.Collapsed;
        }

        private void InitializeFlowLayoutPanel()
        {
            var flp =
                flowLayoutHost.Child as FlowLayoutPanel;

            flp.WrapContents = true;

            const int numButtons = 6;

            for (var i = 0; i < numButtons; i++)
            {
                var b = new Button
                {
                    Text = "Button",
                    BackColor = Color.AliceBlue,
                    FlatStyle = FlatStyle.Flat
                };

                flp.Controls.Add(b);
            }
        }
    }
}

<|start_filename|>Input and Commands/TouchKeyboard/TouchKeyboardNotifier/TouchKeyboardEventManager.cs<|end_filename|>
﻿// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows;
using System.Windows.Interop;
using Windows.Foundation;
using Windows.UI.ViewManagement;
using static Microsoft.Windows.Input.TouchKeyboard.Rcw.InputPaneRcw;

namespace Microsoft.Windows.Input.TouchKeyboard
{
    // Alias for neatness
    using WinRTVisibilityHandler = TypedEventHandler<InputPane, InputPaneVisibilityEventArgs>;

    /// <summary>
    /// A delegate for handlers to the showing and hiding events
    /// </summary>
    /// <param name="occludedWindow">The window that is being occluded</param>
    /// <param name="occludedRect">The rectangle that represents the occluded region</param>
    public delegate void TouchKeyboardVisibilityHandler(Window occludedWindow, System.Windows.Rect occludedRect);

    /// <summary>
    /// Provides access to registering a WPF window for notifications from the 
    /// touch keyboard.
    /// </summary>
    [CLSCompliant(true)]
    public static class TouchKeyboardEventManager
    {
        #region Helper Classes

        /// <summary>
        /// Hold event handlers for the WinRT events
        /// </summary>
        private class WinRTEventHandlers
        {
            public WinRTVisibilityHandler Showing;
            public WinRTVisibilityHandler Hiding;
        }

        #endregion

        #region Constants

        private const string ShowingEventName = "Showing";
        private const string HidingEventName = "Hiding";
        private const string InputPaneTypeName = "Windows.UI.ViewManagement.InputPane, Windows, ContentType=WindowsRuntime";

        #endregion

        #region Member Variables

        /// <summary>
        /// Holds an association from a window to the WinRT event handlers used to register for the showing/hiding events
        /// </summary>
        private static Dictionary<Window, List<WinRTEventHandlers>> _registrationTokens = new Dictionary<Window, List<WinRTEventHandlers>>();

        /// <summary>
        /// The WinRT InputPane type.
        /// </summary>
        private static Type _inputPaneType = null;

        /// <summary>
        /// Holds the event info queried from the InputPane type
        /// </summary>
        private static EventInfo _showingEvent = null;

        /// <summary>
        /// Holds the event info queried from the InputPane type
        /// </summary>
        private static EventInfo _hidingEvent = null;

        /// <summary>
        /// Indicates if calling the touch keyboard is supported
        /// </summary>
        private static bool _touchKeyboardSupported = false;

        #endregion

        #region Constructors

        /// <summary>
        /// Creates and caches some reflection
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
        static TouchKeyboardEventManager()
        {
            _inputPaneType = Type.GetType(InputPaneTypeName);

            if (_inputPaneType != null)
            {
                _showingEvent = _inputPaneType.GetRuntimeEvent(ShowingEventName);
                _hidingEvent = _inputPaneType.GetRuntimeEvent(HidingEventName);
            }

            _touchKeyboardSupported = (WindowsRuntimeMarshal.GetActivationFactory(_inputPaneType) as IInputPaneInterop) != null;
        }

        #endregion

        #region Event Registration

        /// <summary>
        /// Adds handlers for the showing and hiding events from the touch keyboard for the specific window.
        /// </summary>
        /// <param name="window">The window to add handlers for</param>
        /// <param name="showingHandler">The handler for the showing event</param>
        /// <param name="hidingHandler">The handler for the hiding event</param>
        [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
        [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Justification = "String interoplation is CurrentCulture by default.")]
        public static void AddHandlers(Window window, TouchKeyboardVisibilityHandler showingHandler, TouchKeyboardVisibilityHandler hidingHandler)
        {
            VerifySupported();

            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            if (showingHandler == null)
            {
                throw new ArgumentNullException(nameof(showingHandler));
            }

            if (hidingHandler == null)
            {
                throw new ArgumentNullException(nameof(hidingHandler));
            }

            var winRtShowingHandler = AddShowingHandler(window, showingHandler);
            var winRtHidingHandler = AddHidingHandler(window, hidingHandler);

            // Register to unregister the handlers if needed
            window.Closing += Window_Closing;

            if (!_registrationTokens.ContainsKey(window))
            {
                _registrationTokens[window] = new List<WinRTEventHandlers>();
            }

            // Keep track of the WinRT handlers
            _registrationTokens[window].Add(new WinRTEventHandlers()
            {
                Showing = winRtShowingHandler,
                Hiding = winRtHidingHandler
            });
        }

        /// <summary>
        /// Removes all touch keyboad showing/hiding handlers for the specific window.
        /// </summary>
        /// <param name="window">The window to remove handlers for</param>
        [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
        [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", Justification = "String interoplation is CurrentCulture by default.")]
        public static void RemoveHandlers(Window window)
        {
            VerifySupported();

            if (window == null)
            {
                throw new ArgumentNullException(nameof(window));
            }

            if (_registrationTokens.ContainsKey(window))
            {
                throw new ArgumentException(nameof(window), $"{nameof(window)}: {window.Title} is not registered for visibility events!");
            }

            RemoveShowingHandler(window);
            RemoveHidingHandler(window);

            window.Closing -= Window_Closing;
            _registrationTokens.Remove(window);
        }

        #endregion

        #region Window Handlers

        /// <summary>
        /// Subscribed on adding handlers for a window.  This function cleans up any references to that
        /// window and removes all event registrations as needed.
        /// </summary>
        /// <param name="sender">The window that is closing</param>
        /// <param name="e"></param>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private static void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Window w = sender as Window;

            if (w != null)
            {
                try
                {
                    RemoveHandlers(w);
                }
                catch
                {
                    // Don't want exceptions in the closing handler so eat them
                }
            }
        }

        #endregion

        #region Handler Utility Functions

        /// <summary>
        /// Adds a handler for the showing event
        /// </summary>
        /// <param name="window">The window to add the handler for</param>
        /// <param name="handler">The handler</param>
        /// <returns>The WinRT handler</returns>
        private static WinRTVisibilityHandler AddShowingHandler(Window window, TouchKeyboardVisibilityHandler handler)
        {
            return AddVisibilityHandler(_showingEvent, window, handler);
        }

        /// <summary>
        /// Adds a handler for the hiding event
        /// </summary>
        /// <param name="window">The window to add the handler for</param>
        /// <param name="handler">The handler</param>
        /// <returns>The WinRT handler</returns>
        private static WinRTVisibilityHandler AddHidingHandler(Window window, TouchKeyboardVisibilityHandler handler)
        {
            return AddVisibilityHandler(_hidingEvent, window, handler);
        }

        /// <summary>
        /// Remove the handler for the showing event.
        /// </summary>
        /// <param name="window">The window to remove the handler for</param>
        private static void RemoveShowingHandler(Window window)
        {
            foreach (WinRTEventHandlers handlers in _registrationTokens[window])
            {
                RemoveVisibilityHandler(_showingEvent, window, handlers.Showing);
            }
        }

        /// <summary>
        /// Remove the handler for the hiding event.
        /// </summary>
        /// <param name="window">The window to remove the handler for</param>
        private static void RemoveHidingHandler(Window window)
        {
            foreach (WinRTEventHandlers handlers in _registrationTokens[window])
            {
                RemoveVisibilityHandler(_hidingEvent, window, handlers.Hiding);
            }
        }

        /// <summary>
        /// Adds a handler for the specific visibility event
        /// </summary>
        /// <param name="visibilityEvent">The event to add a handler for</param>
        /// <param name="window">The window to add the handler for</param>
        /// <param name="handler">The handler</param>
        /// <returns>The WinRT handler</returns>
        private static WinRTVisibilityHandler AddVisibilityHandler(EventInfo visibilityEvent, Window window, TouchKeyboardVisibilityHandler handler)
        {
            IInputPane2 inputPane = GetInputPane(window);

            // This adds the event handler to the visibility event
            Func<WinRTVisibilityHandler, EventRegistrationToken> add =
                (addHandler) =>
                {
                    return (EventRegistrationToken)visibilityEvent.AddMethod.Invoke(inputPane, new object[] { addHandler });
                };

            // This removes the handler from the visibility event
            Action<EventRegistrationToken> remove =
                (removeHandler) =>
                {
                    visibilityEvent.RemoveMethod.Invoke(inputPane, new object[] { removeHandler });
                };

            // This is the WinRT called handler to translate to the local WPF delegate
            WinRTVisibilityHandler localHandler =
                (inputPaneInstance, visArgs) =>
                {
                    // We cannot reference System.Runtime.WindowsRuntime directly, so only access the Rect type via
                    // reflection to ensure the proper assembly loads with no issues.
                    var rect = visArgs.GetType().GetProperty("OccludedRect").GetValue(visArgs);

                    // Invoke the WPF specific handler to pass the occluded rectangle information
                    handler?.Invoke(
                        window,
                        new System.Windows.Rect(
                            (double)rect.GetType().GetRuntimeProperty("X").GetValue(rect),
                            (double)rect.GetType().GetRuntimeProperty("Y").GetValue(rect),
                            (double)rect.GetType().GetRuntimeProperty("Width").GetValue(rect),
                            (double)rect.GetType().GetRuntimeProperty("Height").GetValue(rect)));
                };

            // Add the event handlers
            WindowsRuntimeMarshal.AddEventHandler<WinRTVisibilityHandler>(add, remove, localHandler);

            // Return the WinRT handler in order to use it to un-register later
            return localHandler;
        }

        /// <summary>
        /// Removes a handler for the specific visibility event
        /// </summary>
        /// <param name="visibilityEvent">The event to remove the handler for</param>
        /// <param name="window">The window to remove the handler for</param>
        /// <param name="winRtHandler">The WinRT handler</param>
        private static void RemoveVisibilityHandler(EventInfo visibilityEvent, Window window, WinRTVisibilityHandler winRtHandler)
        {
            IInputPane2 inputPane = GetInputPane(window);

            Action<EventRegistrationToken> remove =
                (removeHandler) =>
                {
                    visibilityEvent.RemoveMethod.Invoke(inputPane, new object[] { removeHandler });
                };

            WindowsRuntimeMarshal.RemoveEventHandler<WinRTVisibilityHandler>(remove, winRtHandler);
        }

        #endregion

        #region Utility Functions

        /// <summary>
        /// Returns an instance of the InputPane
        /// </summary>
        /// <param name="window">The window to get the InputPane for</param>
        /// <returns>The InputPane</returns>
        private static IInputPane2 GetInputPane(Window window)
        {
            // Need the HWND for the native interop call into IInputPaneInterop
            IntPtr handle = new WindowInteropHelper(window).Handle;

            // Get and cast an InputPane COM instance
            var inputPaneInterop = WindowsRuntimeMarshal.GetActivationFactory(_inputPaneType) as IInputPaneInterop;

            // Get the actual input pane for this HWND
            return inputPaneInterop.GetForWindow(handle, typeof(IInputPane2).GUID);
        }

        /// <summary>
        /// Determines if the calls to the touch keyboard APIs are supported.
        /// </summary>
        private static void VerifySupported()
        {
            if (!_touchKeyboardSupported)
            {
                throw new PlatformNotSupportedException("Native access to touch keyboard APIs not supported on this OS!");
            }
        }

        #endregion
    }
}


<|start_filename|>Application Management/ExceptionHandlingSecondaryUIThread/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace ExceptionHandlingSecondaryUIThread
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Title = $"Running on Main UI Thread {Thread.CurrentThread.ManagedThreadId}";
        }

        // THIS EVENT HANDLER RUNS ON THE MAIN UI THREAD
        private void startSecondaryUIThreadButton_Click(object sender, RoutedEventArgs e)
        {
            // Creates and starts a secondary thread in a single threaded apartment (STA)
            var thread = new Thread(MethodRunningOnSecondaryUIThread);
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
        }

        // THIS METHOD RUNS ON A SECONDARY UI THREAD (THREAD WITH A DISPATCHER)
        private void MethodRunningOnSecondaryUIThread()
        {
            var secondaryUiThreadId = Thread.CurrentThread.ManagedThreadId;
            try
            {
                // On secondary thread, show a new Window before starting a new Dispatcher
                // ie turn secondary thread into a UI thread
                var window = new SecondaryUIThreadWindow();
                window.Show();
                Dispatcher.Run();
            }
            catch (Exception ex)
            {
                // Dispatch the exception back to the main ui thread and reraise it
                Application.Current.Dispatcher.Invoke(
                    DispatcherPriority.Send,
                    (DispatcherOperationCallback) delegate
                    {
                        // THIS CODE RUNS BACK ON THE MAIN UI THREAD
                        string msg = $"Exception forwarded from secondary UI thread {secondaryUiThreadId}.";
                        throw new Exception(msg, ex);
                    }
                    , null);

                // NOTE - Application execution will only continue from this point
                //        onwards if the exception was handled on the main UI thread
                //        by Application.DispatcherUnhandledException
            }
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/baseencoder.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of BaseEncoder
//----------------------------------------------------------------------------------------
#pragma once

#include "UnknownImpl.h"

class BaseFrameEncode : public IWICBitmapFrameEncode
{
public:
    BaseFrameEncode(IWICImagingFactory *factory, IStream *pIStream, UINT num);
    ~BaseFrameEncode();


    // IUnknown Interface
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv);
    STDMETHOD_(ULONG, AddRef)();
    STDMETHOD_(ULONG, Release)();


    // IWICBitmapFrameEncode
    STDMETHOD(Initialize)( 
        /* [in] [optional] */ IPropertyBag2 *pIEncoderOptions);

    STDMETHOD(SetSize)(
        /* [in] */ UINT width,
        /* [in] */ UINT height);

    STDMETHOD(SetResolution)( 
        /* [in] */ double dpiX,
        /* [in] */ double dpiY);

    STDMETHOD(SetPixelFormat)( 
        /* [out][in] */ WICPixelFormatGUID *pPixelFormat);

    STDMETHOD(SetColorContexts)(
        /* [in] */ UINT cCount,
        /* [in] */ IWICColorContext **ppIColorContext);

    STDMETHOD(SetPalette)(
        /* [in] */ IWICPalette *pIPalette);

    STDMETHOD(SetThumbnail)( 
        /* [in] */ IWICBitmapSource *pIThumbnail);

    STDMETHOD(WritePixels)( 
        /* [in] */ UINT lineCount,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbBufferSize,
        /* [in] */ BYTE *pbPixels);

    STDMETHOD(WriteSource)( 
        /* [in] */ IWICBitmapSource *pIWICBitmapSource,
        /* [in] */ WICRect *prc);

    STDMETHOD(Commit)();

    STDMETHOD(GetMetadataQueryWriter)( 
        /* [out] */ IWICMetadataQueryWriter **ppIMetadataQueryWriter);

public :
    IWICImagingFactory *factory;
    IStream            *stream;
    UINT                frameNumber;    
    IWICBitmapSource   *destSource;
    UINT                destWidth, destHeight;
    double              destDpiX, destDpiY;
    WICPixelFormatGUID  destPixelFormat;
    std::vector<IWICColorContext*>  colorContexts;
    IWICPalette        *destPalette;
    IWICBitmapSource   *destThumbnail;
    IWICBitmapSource   *destPreview;

private:
    void ReleaseMembers();
    UnknownImpl         unknownImpl;
};


class BaseEncoder : public IWICBitmapEncoder
{
public:
    BaseEncoder(GUID Me, GUID Container);
    ~BaseEncoder();


    // IUnknown Interface
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv);
    STDMETHOD_(ULONG, AddRef)();
    STDMETHOD_(ULONG, Release)();

    // IWICBitmapEncoder Interface
    STDMETHOD(Initialize)( 
        /* [in] */ IStream *pIStream,
        /* [in] */ WICBitmapEncoderCacheOption cacheOption)=0;

    STDMETHOD(GetContainerFormat)( 
        /* [out] */ GUID *pguidContainerFormat);

    STDMETHOD(GetEncoderInfo)( 
        /* [out] */ IWICBitmapEncoderInfo **ppIEncoderInfo);

    STDMETHOD(SetColorContexts)(
        /* [in] */ UINT cCount,
        /* [in] */ IWICColorContext **ppIColorContext);

    STDMETHOD(SetPalette)( 
        /* [in] */ IWICPalette *pIPalette);

    STDMETHOD(SetThumbnail)( 
        /* [in] */ IWICBitmapSource *pIThumbnail);

    STDMETHOD(SetPreview)( 
        /* [in] */ IWICBitmapSource *pIPreview);

    STDMETHOD(CreateNewFrame)( 
        /* [out] */ IWICBitmapFrameEncode **ppIFrameEncode,
        /* [out] [optional] */ IPropertyBag2 **ppIEncoderOptions);

    STDMETHOD(Commit)()=0;

    STDMETHOD(GetMetadataQueryWriter)( 
        /* [out] */ IWICMetadataQueryWriter **ppIMetadataQueryWriter)=0;

protected :
    //Additional functions
    virtual BaseFrameEncode* CreateNewEncoderFrame(
        /* [in] */  IWICImagingFactory *pIFactory,
        /* [in] */ IStream *pIStream, 
        /* [in] */ UINT num) = 0;
    virtual void AddEncoderFrame(BaseFrameEncode* frame); 

    HRESULT VerifyFactory();
     
    IWICImagingFactory           *factory;
    IStream                      *stream;
    std::vector<BaseFrameEncode*>  frames;
    IWICPalette                  *destPalette;
    std::vector<IWICColorContext*>  colorContexts;
    IWICBitmapSource             *destThumbnail;
    IWICBitmapSource             *destPreview;

    ULARGE_INTEGER                headerPos;

    GUID CLSID_Container;
    GUID CLSID_This;
private:
    void ReleaseMembers();
    UnknownImpl                   unknownImpl;
};


<|start_filename|>Sample Applications/ParticlesDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Threading;

namespace ParticlesDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly ParticleSystemManager _pm;
        private readonly Random _rand;
        private int _currentTick;
        private double _elapsed;
        private int _frameCount;
        private double _frameCountTime;
        private int _frameRate;
        private int _lastTick;
        private Point3D _spawnPoint;
        private double _totalElapsed;

        public MainWindow()
        {
            InitializeComponent();

            var frameTimer = new DispatcherTimer();
            frameTimer.Tick += OnFrame;
            frameTimer.Interval = TimeSpan.FromSeconds(1.0/60.0);
            frameTimer.Start();

            _spawnPoint = new Point3D(0.0, 0.0, 0.0);
            _lastTick = Environment.TickCount;

            _pm = new ParticleSystemManager();

            WorldModels.Children.Add(_pm.CreateParticleSystem(1000, Colors.Gray));
            WorldModels.Children.Add(_pm.CreateParticleSystem(1000, Colors.Red));
            WorldModels.Children.Add(_pm.CreateParticleSystem(1000, Colors.Silver));
            WorldModels.Children.Add(_pm.CreateParticleSystem(1000, Colors.Orange));
            WorldModels.Children.Add(_pm.CreateParticleSystem(1000, Colors.Yellow));

            _rand = new Random(GetHashCode());

            KeyDown += Window1_KeyDown;
            Cursor = Cursors.None;
        }

        private void Window1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
                Close();
        }

        private void OnFrame(object sender, EventArgs e)
        {
            // Calculate frame time;
            _currentTick = Environment.TickCount;
            _elapsed = (_currentTick - _lastTick)/1000.0;
            _totalElapsed += _elapsed;
            _lastTick = _currentTick;

            _frameCount++;
            _frameCountTime += _elapsed;
            if (_frameCountTime >= 1.0)
            {
                _frameCountTime -= 1.0;
                _frameRate = _frameCount;
                _frameCount = 0;
                FrameRateLabel.Content = "FPS: " + _frameRate + "  Particles: " + _pm.ActiveParticleCount;
            }

            _pm.Update((float) _elapsed);
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Red, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Orange, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Silver, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Gray, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Red, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Orange, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Silver, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Gray, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Red, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Yellow, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Silver, _rand.NextDouble(), 2.5*_rand.NextDouble());
            _pm.SpawnParticle(_spawnPoint, 10.0, Colors.Yellow, _rand.NextDouble(), 2.5*_rand.NextDouble());

            var c = Math.Cos(_totalElapsed);
            var s = Math.Sin(_totalElapsed);

            _spawnPoint = new Point3D(s*32.0, c*32.0, 0.0);
        }
    }
}

<|start_filename|>Input and Commands/MouseState/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MouseState
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void HandleButtonDown(object sender, MouseButtonEventArgs e)
        {
            //Casting the source to a StackPanel
            var sourceStackPanel = e.Source as StackPanel;

            //If the button is pressed then make dimensions larger.
            if (e.ButtonState == MouseButtonState.Pressed)
            {
                sourceStackPanel.Width = 200;
                sourceStackPanel.Height = 200;
            }

            //If the button is released then make dimensions smaller.
            else if (e.ButtonState == MouseButtonState.Released)
            {
                sourceStackPanel.Width = 100;
                sourceStackPanel.Height = 100;
            }
        }
    }
}

<|start_filename|>Animation/LocalAnimations/App.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace LocalAnimations
{
    // Displays the sample.
    public class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            CreateAndShowMainWindow();
        }

        private void CreateAndShowMainWindow()
        {
            // Create the application's main window.
            Window sViewer = new SampleViewer();
            MainWindow = sViewer;
            sViewer.Show();
        }
    }

    // Starts the application.
}

<|start_filename|>Input and Commands/ICommandSourceImplementation/FontDoubleValueConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace ICommandSourceImplementation
{
    [ValueConversion(typeof (double), typeof (int))]
    public class FontDoubleValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var fontSize = (double) value;
            return (int) fontSize;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}

<|start_filename|>Sample Applications/CubeAnimationDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace CubeAnimationDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Globals

        private Trackball _trackball;

        #endregion

        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnLoaded(object sender, EventArgs e)
        {
            // setup trackball for moving the model around
            _trackball = new Trackball();
            _trackball.Attach(this);
            _trackball.Slaves.Add(myViewport3D);
            _trackball.Enabled = true;
        }

        #region Events

        private void OnImage1Animate(object sender, RoutedEventArgs e)
        {
            var s = (Storyboard) FindResource("RotateStoryboard");
            BeginStoryboard(s);
        }

        #endregion
    }
}

<|start_filename|>Element Tree/OverridingLogicalTree/SingletonPanel.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
using System.Windows;
using System.Windows.Controls;

namespace OverridingLogicalTree
{
    public class SingletonPanel : StackPanel
    {
        //private UIElementCollection _children; 
        private FrameworkElement _child;

        public FrameworkElement SingleChild
        {
            get { return _child; }
            set
            {
                if (value == null)
                {
                    RemoveLogicalChild(_child);
                }
                else
                {
                    if (_child == null)
                    {
                        _child = value;
                    }
                    else
                    {
                        // raise an exception?
                        MessageBox.Show("Needs to be a single element");
                    }
                }
            }
        }

        protected override IEnumerator LogicalChildren
        {
            get
            {
                // cheat, make a list with one member and return the enumerator
                var list = new ArrayList {_child};
                return list.GetEnumerator();
            }
        }

        public void SetSingleChild(object child)
        {
            AddLogicalChild(child);
        }

        public new void AddLogicalChild(object child)
        {
            _child = (FrameworkElement) child;
            if (Children.Count == 1)
            {
                RemoveLogicalChild(Children[0]);
                Children.Add((UIElement) child);
            }
            else
            {
                Children.Add((UIElement) child);
            }
        }

        public new void RemoveLogicalChild(object child)

        {
            _child = null;
            Children.Clear();
        }
    }
}

<|start_filename|>Drag and Drop/DragDropThumbOps/Pane.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace DragDropThumbOps
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Pane : Canvas
    {
        private void OnDragDelta(object sender, DragDeltaEventArgs e)
        {
            //Move the Thumb to the mouse position during the drag operation
            var yadjust = myCanvasStretch.Height + e.VerticalChange;
            var xadjust = myCanvasStretch.Width + e.HorizontalChange;
            if ((xadjust >= 0) && (yadjust >= 0))
            {
                myCanvasStretch.Width = xadjust;
                myCanvasStretch.Height = yadjust;
                SetLeft(myThumb, GetLeft(myThumb) +
                                 e.HorizontalChange);
                SetTop(myThumb, GetTop(myThumb) +
                                e.VerticalChange);
                changes.Text = "Size: " +
                               myCanvasStretch.Width.ToString(CultureInfo.InvariantCulture) +
                               ", " +
                               myCanvasStretch.Height.ToString(CultureInfo.InvariantCulture);
            }
        }

        private void OnDragStarted(object sender, DragStartedEventArgs e)
        {
            myThumb.Background = Brushes.Orange;
        }

        private void OnDragCompleted(object sender, DragCompletedEventArgs e)
        {
            myThumb.Background = Brushes.Blue;
        }
    }
}

<|start_filename|>Graphics/ImageBrush/InteractiveExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ImageBrush
{
    /// <summary>
    ///     Interaction logic for TextFillsExample.xaml
    /// </summary>
    public partial class InteractiveExample : Page
    {
        private RadioButton _selectedButton;

        private void InteractiveExampleLoaded(object sender, RoutedEventArgs args)
        {
            LoadInteractiveMenus();
            MyDefaultImageButton.IsChecked = true;
        }

        // Initializes the image brush menu options.
        private void LoadInteractiveMenus()
        {
            var values = Enum.GetNames(typeof (Stretch));
            foreach (var stretchMode in values)
                stretchSelector.Items.Add(stretchMode);
            stretchSelector.SelectedItem = myImageBrush.Stretch.ToString();

            values = Enum.GetNames(typeof (AlignmentX));
            foreach (var hAlign in values)
                horizontalAlignmentSelector.Items.Add(hAlign);
            horizontalAlignmentSelector.SelectedItem = myImageBrush.AlignmentX.ToString();

            values = Enum.GetNames(typeof (AlignmentY));
            foreach (var vAlign in values)
                verticalAlignmentSelector.Items.Add(vAlign);
            verticalAlignmentSelector.SelectedItem = myImageBrush.AlignmentY.ToString();

            values = Enum.GetNames(typeof (TileMode));
            foreach (var tileMode in values)
                tileSelector.Items.Add(tileMode);
            tileSelector.SelectedItem = myImageBrush.TileMode.ToString();

            values = Enum.GetNames(typeof (BrushMappingMode));
            foreach (var mappingMode in values)
            {
                viewportUnitsSelector.Items.Add(mappingMode);
                viewboxUnitsSelector.Items.Add(mappingMode);
            }
            viewportUnitsSelector.SelectedItem = myImageBrush.ViewportUnits.ToString();
            viewboxUnitsSelector.SelectedItem = myImageBrush.ViewboxUnits.ToString();
            viewportEntry.Text = myImageBrush.Viewport.ToString();
            viewboxEntry.Text = myImageBrush.Viewbox.ToString();
        }

        private void SetSelectedButton(object sender, RoutedEventArgs args)
        {
            _selectedButton = sender as RadioButton;
        }

        // Applies the selected options to the image brush.
        private void UpdateBrush(object sender, RoutedEventArgs args)
        {
            try
            {
                myImageBrush.ImageSource = (_selectedButton.Content as Image).Source;
                myImageBrush.Stretch = (Stretch) Enum.Parse(typeof (Stretch), (string) stretchSelector.SelectedItem);
                myImageBrush.AlignmentX =
                    (AlignmentX) Enum.Parse(typeof (AlignmentX), (string) horizontalAlignmentSelector.SelectedItem);
                myImageBrush.AlignmentY =
                    (AlignmentY) Enum.Parse(typeof (AlignmentY), (string) verticalAlignmentSelector.SelectedItem);
                myImageBrush.TileMode = (TileMode) Enum.Parse(typeof (TileMode), (string) tileSelector.SelectedItem);
                myImageBrush.ViewportUnits =
                    (BrushMappingMode)
                        Enum.Parse(typeof (BrushMappingMode), (string) viewportUnitsSelector.SelectedItem);
                myImageBrush.ViewboxUnits =
                    (BrushMappingMode) Enum.Parse(typeof (BrushMappingMode), (string) viewboxUnitsSelector.SelectedItem);

                var myRectConverter = new RectConverter();
                var parseString = viewportEntry.Text;

                if (!string.IsNullOrEmpty(parseString))
                    myImageBrush.Viewport = (Rect) myRectConverter.ConvertFromString(parseString);
                else
                {
                    myImageBrush.Viewport = Rect.Empty;
                    viewportEntry.Text = "Empty";
                }

                parseString = viewboxEntry.Text;

                if (!string.IsNullOrEmpty(parseString) && parseString.ToLower() != "(auto)")
                    myImageBrush.Viewbox = (Rect) myRectConverter.ConvertFromString(parseString);
                else
                {
                    viewboxEntry.Text = "Empty";
                    myImageBrush.Viewbox = Rect.Empty;
                }
            }
            catch (InvalidOperationException invalidOpEx)
            {
                MessageBox.Show("Invalid Viewport or Viewbox. " + invalidOpEx);
            }
            catch (FormatException formatEx)
            {
                MessageBox.Show("Invalid Viewport or Viewbox. " + formatEx);
            }
        }
    }
}

<|start_filename|>Data Binding/ValidateItemSample/ValidateDateAndPrice.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;

namespace ValidateItemSample
{
    public class ValidateDateAndPrice : ValidationRule
    {
        // Ensure that an item over $100 is available for at least 7 days.
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var bg = value as BindingGroup;

            // Get the source object.
            var item = bg?.Items[0] as PurchaseItem;

            object doubleValue;
            object dateTimeValue;

            // Get the proposed values for Price and OfferExpires.
            var priceResult = bg.TryGetValue(item, "Price", out doubleValue);
            var dateResult = bg.TryGetValue(item, "OfferExpires", out dateTimeValue);

            if (!priceResult || !dateResult)
            {
                return new ValidationResult(false, "Properties not found");
            }

            var price = (double) doubleValue;
            var offerExpires = (DateTime) dateTimeValue;

            // Check that an item over $100 is available for at least 7 days.
            if (price > 100)
            {
                if (offerExpires < DateTime.Today + new TimeSpan(7, 0, 0, 0))
                {
                    return new ValidationResult(false, "Items over $100 must be available for at least 7 days.");
                }
            }

            return ValidationResult.ValidResult;
        }
    }


    //Ensure that the price is positive.

    // Ensure that the date is in the future.

    // PurchaseItem implements INotifyPropertyChanged and IEditableObject
    // to support edit transactions, which enable users to cancel pending changes.
}

<|start_filename|>Sample Applications/CalculatorDemo/MyTextBox.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Controls;
using System.Windows.Input;

namespace CalculatorDemo
{
    internal sealed class MyTextBox : TextBox
    {
        protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e)
        {
            e.Handled = true;
            base.OnPreviewGotKeyboardFocus(e);
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/TypeInfoTableEntry.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace BamlTools
{
    public class TypeInfoTableEntry
    {
        int _typeId;
        String _fullName;

        public TypeInfoTableEntry(int typeId, string fullName)
        {
            _typeId = typeId;
            _fullName = fullName;
        }

        public int TypeId
        {
            get { return _typeId; }
        }

        public String FullName
        {
            get { return _fullName; }
        }

    }
}


<|start_filename|>Migration and Interoperability/Win32HostingWPFPage/cpp/wpfpage.cpp<|end_filename|>
#include "stdafx.h"
#include "WPFPage.h"

WPFPage::WPFPage() {}
WPFPage::WPFPage(int allottedWidth, int allotedHeight)
{
  array<ColumnDefinition ^> ^ columnDef = gcnew array<ColumnDefinition ^> (4);
  array<RowDefinition ^> ^ rowDef = gcnew array<RowDefinition ^> (6);

  this->Height = allotedHeight;
  this->Width = allottedWidth;
  this->Background = gcnew SolidColorBrush(Colors::LightGray);
  
  //Set up the Grid's row and column definitions
  for(int i=0; i<4; i++)
  {
    columnDef[i] = gcnew ColumnDefinition();
    columnDef[i]->Width = GridLength(1, GridUnitType::Auto);
    this->ColumnDefinitions->Add(columnDef[i]);
  }
  for(int i=0; i<6; i++)
  {
    rowDef[i] = gcnew RowDefinition();
    rowDef[i]->Height = GridLength(1, GridUnitType::Auto);
    this->RowDefinitions->Add(rowDef[i]);
  }
  //Add the title
  titleText = gcnew Label();
  titleText->Content = "Simple WPF Control";
  titleText->HorizontalAlignment = System::Windows::HorizontalAlignment::Center;
  titleText->Margin = Thickness(10, 5, 10, 0);
  titleText->FontWeight = FontWeights::Bold;
  titleText->FontSize = 14;
  Grid::SetColumn(titleText, 0);
  Grid::SetRow(titleText, 0);
  Grid::SetColumnSpan(titleText, 4);
  this->Children->Add(titleText);
  //Add the Name Label and TextBox
  nameLabel = CreateLabel(0, 1, "Name");
  this->Children->Add(nameLabel);
  nameTextBox = CreateTextBox(1, 1, 3);
  this->Children->Add(nameTextBox);
  //Add the Address Label and TextBox
  addressLabel = CreateLabel(0, 2, "Address");
  this->Children->Add(addressLabel);
  addressTextBox = CreateTextBox(1, 2, 3);
  this->Children->Add(addressTextBox);

  //Add the City Label and TextBox
  cityLabel = CreateLabel(0, 3, "City");
  this->Children->Add(cityLabel);
  cityTextBox = CreateTextBox(1, 3, 1);
  cityTextBox->Width = 100;
  this->Children->Add(cityTextBox);

  //Add the State Label and TextBox
  stateLabel = CreateLabel(2, 3, "State");
  this->Children->Add(stateLabel);
  stateTextBox = CreateTextBox(3, 3, 1);
  stateTextBox->Width = 50;
  this->Children->Add(stateTextBox);

  //Add the Zip Label and TextBox
  zipLabel = CreateLabel(0, 4, "Zip");
  this->Children->Add(zipLabel);
  zipTextBox = CreateTextBox(1, 4, 1);
  this->Children->Add(zipTextBox);
  //Add the Buttons and atttach event handlers
  okButton = CreateButton(0, 5, "OK");
  cancelButton = CreateButton(1, 5, "Cancel");
  this->Children->Add(okButton);
  this->Children->Add(cancelButton);
  okButton->Click += gcnew RoutedEventHandler(this, &WPFPage::ButtonClicked);
  cancelButton->Click += gcnew RoutedEventHandler(this, &WPFPage::ButtonClicked);
  //Set the default font properties
  DefaultFontFamily = nameLabel->FontFamily;
  DefaultFontStyle = nameLabel->FontStyle;
  DefaultFontSize = nameLabel->FontSize;
  DefaultFontWeight = nameLabel->FontWeight;
  DefaultForeBrush = nameLabel->Foreground;

}
Label ^WPFPage::CreateLabel(int column, int row, String ^ text)
{
  Label ^ newLabel = gcnew Label();
  newLabel->Content = text;
  newLabel->Margin = Thickness(10, 5, 10, 0);
  newLabel->FontWeight = FontWeights::Normal;
  newLabel->FontSize = 12;
  Grid::SetColumn(newLabel, column);
  Grid::SetRow(newLabel, row);
  return newLabel;
}
TextBox ^WPFPage::CreateTextBox(int column, int row, int span)
{
  TextBox ^newTextBox = gcnew TextBox();
  newTextBox->Margin = Thickness(10, 5, 10, 0);
  Grid::SetColumn(newTextBox, column);
  Grid::SetRow(newTextBox, row);
  Grid::SetColumnSpan(newTextBox, span);
  return newTextBox;
}
Button ^WPFPage::CreateButton(int column, int row, String ^text)
{
  Button ^newButton = gcnew Button();
  newButton->Content = text;
  newButton->Margin = Thickness(10, 10, 10, 10);
  newButton->Width = 60;
  Grid::SetColumn(newButton, column);
  Grid::SetRow(newButton, row);
  return newButton;
}
void WPFPage::ButtonClicked(Object ^sender, RoutedEventArgs ^args)
{

  //TODO: validate input data
  bool okClicked = true;
  if(sender == cancelButton)
    okClicked = false;
  EnteredName = nameTextBox->Text;
  EnteredAddress = addressTextBox->Text;
  EnteredCity = cityTextBox->Text;
  EnteredState = stateTextBox->Text;
  EnteredZip = zipTextBox->Text;
  OnButtonClicked(this, gcnew MyPageEventArgs(okClicked));
}
void WPFPage::SetFontFamily(FontFamily^ newFontFamily)
{
  _defaultFontFamily = newFontFamily;
  titleText->FontFamily = newFontFamily;
  nameLabel->FontFamily = newFontFamily;
  addressLabel->FontFamily = newFontFamily;
  cityLabel->FontFamily = newFontFamily;
  stateLabel->FontFamily = newFontFamily;
  zipLabel->FontFamily = newFontFamily;
}
void WPFPage::SetFontStyle(FontStyle newFontStyle)
{
  _defaultFontStyle = newFontStyle;
  titleText->FontStyle = newFontStyle;
  nameLabel->FontStyle = newFontStyle;
  addressLabel->FontStyle = newFontStyle;
  cityLabel->FontStyle = newFontStyle;
  stateLabel->FontStyle = newFontStyle;
  zipLabel->FontStyle = newFontStyle;
}

void WPFPage::SetFontSize(double newFontSize)
{
  _defaultFontSize = newFontSize;
  titleText->FontSize = newFontSize;
  nameLabel->FontSize = newFontSize;
  addressLabel->FontSize = newFontSize;
  cityLabel->FontSize = newFontSize;
  stateLabel->FontSize = newFontSize;
  zipLabel->FontSize = newFontSize;
}

void WPFPage::SetFontWeight(FontWeight newFontWeight)
{
  _defaultFontWeight = newFontWeight;
  titleText->FontWeight = newFontWeight;
  nameLabel->FontWeight = newFontWeight;
  addressLabel->FontWeight = newFontWeight;
  cityLabel->FontWeight = newFontWeight;
  stateLabel->FontWeight = newFontWeight;
  zipLabel->FontWeight = newFontWeight;
}

void WPFPage::SetForeBrush(Brush^ newForeBrush)
{
  _defaultForeBrush = newForeBrush;
  titleText->Foreground = newForeBrush;
  nameLabel->Foreground = newForeBrush;
  addressLabel->Foreground = newForeBrush;
  cityLabel->Foreground = newForeBrush;
  stateLabel->Foreground = newForeBrush;
  zipLabel->Foreground = newForeBrush;
}

MyPageEventArgs::MyPageEventArgs() {}

MyPageEventArgs::MyPageEventArgs(bool okClicked)
{
  IsOK = okClicked;
}


<|start_filename|>Animation/Per-FrameAnimation/ParticleEffects/FireworkEffect.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace PerFrameAnimation
{
    //uielement
    //visual operations
    //animation effect stuff
    //LayoutOverrideDecorator

    public class FireworkEffect : OverlayRenderDecorator
    {
        private readonly Vector _gravity = new Vector(0.0, 10.0);
        private readonly List<Particle> _particles = new List<Particle>();
        private Point _lastMousePosition = new Point(0, 0);
        private double _secondsUntilDrop;
        private ParticleEffectsTimeTracker _timeTracker;
        protected Random Random = new Random();

        protected override void OnAttachChild(UIElement child)
        {
            CompositionTarget.Rendering += OnFrameCallback;

            child.PreviewMouseLeftButtonUp += OnMouseLeftButtonUp;
            child.PreviewMouseMove += OnMouseMove;

            _timeTracker = new ParticleEffectsTimeTracker();
        }

        protected override void OnDetachChild(UIElement child)
        {
            CompositionTarget.Rendering -= OnFrameCallback;

            child.PreviewMouseLeftButtonUp -= OnMouseLeftButtonUp;
            child.PreviewMouseMove -= OnMouseMove;

            _timeTracker = null;
        }

        protected void OnFrameCallback(object sender, EventArgs e)
        {
            UpdateParticles(_timeTracker.Update());
        }

        protected virtual void UpdateParticles(double deltatime)
        {
            //drop particles from mouse position
            if (MouseDropsParticles && IsMouseOver)
            {
                _secondsUntilDrop -= deltatime;
                if (_secondsUntilDrop < 0.0)
                {
                    AddRandomBurst(_lastMousePosition - new Vector(Radius/2.0, Radius/2.0), 1);
                    _secondsUntilDrop = MouseDropDelay + (Random.NextDouble()*2.0 - 1.0)*MouseDropDelayVariation;
                }
            }

            if (_particles.Count > 0)
                InvalidateVisual();

            //update all particles
            for (var i = 0; i < _particles.Count;)
            {
                //_particles[i]
                var p = _particles[i];

                if (GravitateToMouse)
                {
                    p.Velocity += (_lastMousePosition - p.Location)*GravitateScale;
                }
                else
                {
                    p.Velocity += _gravity;
                }
                p.Location += p.Velocity*deltatime;

                if (BounceOffContainer)
                {
                    var radius = p.Diameter/2.0;
                    if (p.Location.X - radius < 0.0)
                    {
                        p.Location.X = radius;
                        p.Velocity.X *= -0.9;
                    }
                    else if (p.Location.X > ActualWidth - radius)
                    {
                        p.Location.X = ActualWidth - radius;
                        p.Velocity.X *= -0.9;
                    }
                    if (p.Location.Y - radius < 0.0)
                    {
                        p.Location.Y = radius;
                        p.Velocity.Y *= -0.9;
                    }
                    else if (p.Location.Y > ActualHeight - radius)
                    {
                        p.Location.Y = ActualHeight - radius;
                        p.Velocity.Y *= -0.9;
                    }
                }

                //only increment counter for live particles
                if (_timeTracker.ElapsedTime > p.DeathTime)
                    _particles.RemoveAt(i);
                else
                    i++;
            }
        }

        protected override void OnOverlayRender(DrawingContext drawingContext)
        {
            foreach (var p in _particles)
            {
                //figure out where in the particles life we are
                var particlelife = (_timeTracker.ElapsedTime - p.LifeTime).TotalSeconds/
                                   (p.DeathTime - p.LifeTime).TotalSeconds;
                var currentcolor = Color.Multiply(p.StartColor, (float) (1.0 - particlelife)) +
                                   Color.Multiply(p.EndColor, (float) particlelife);
                Brush brush = new RadialGradientBrush(currentcolor,
                    Color.FromArgb(0, currentcolor.R, currentcolor.G, currentcolor.B));

                var rect =
                    new RectangleGeometry(
                        new Rect(new Point(p.Location.X - p.Diameter/2.0, p.Location.Y - p.Diameter/2.0),
                            new Size(p.Diameter, p.Diameter)));
                drawingContext.DrawGeometry(brush, null, rect);
            }
        }

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            _lastMousePosition = e.GetPosition(this);
        }

        private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            AddRandomBurst(e.GetPosition(this));
        }

        public void AddRandomBurst()
        {
            var point = new Point(Random.NextDouble()*ActualWidth, Random.NextDouble()*ActualHeight);
            AddRandomBurst(point, ClickBurstSize);
        }

        public void AddRandomBurst(Point location)
        {
            AddRandomBurst(location, ClickBurstSize);
        }

        public void AddRandomBurst(Point location, int count)
        {
            for (var i = 0; i < count; i++)
            {
                var p = new Particle();

                var radius = Radius + (Random.NextDouble()*2.0 - 1.0)*RadiusVariation;
                var lifetime = Random.NextDouble()*3.0 + 1.0;

                p.Location = location;
                p.Velocity = new Vector(Random.NextDouble()*200.0 - 100.0, Random.NextDouble()*-200 + 100.0);
                p.LifeTime = _timeTracker.ElapsedTime;
                p.DeathTime = _timeTracker.ElapsedTime + TimeSpan.FromSeconds(lifetime);
                p.Diameter = 2.0*radius;

                var startColor = StartColor;
                var startColorVariation = StartColorVariation;
                var endColor = EndColor;
                var endColorVariation = EndColorVariation;

                var startRandColor = Color.FromScRgb(startColorVariation.ScA*(float) (Random.NextDouble()*2.0 - 1.0),
                    startColorVariation.ScR*(float) (Random.NextDouble()*2.0 - 1.0),
                    startColorVariation.ScG*(float) (Random.NextDouble()*2.0 - 1.0),
                    startColorVariation.ScB*(float) (Random.NextDouble()*2.0 - 1.0));
                var endRandColor = Color.FromScRgb(endColorVariation.ScA*(float) (Random.NextDouble()*2.0 - 1.0),
                    endColorVariation.ScR*(float) (Random.NextDouble()*2.0 - 1.0),
                    endColorVariation.ScG*(float) (Random.NextDouble()*2.0 - 1.0),
                    endColorVariation.ScB*(float) (Random.NextDouble()*2.0 - 1.0));

                p.StartColor = startColor + startRandColor;
                p.EndColor = endColor + endRandColor;
                _particles.Add(p);
            }
        }

        #region Dependency Properties

        public static readonly DependencyProperty RadiusProperty =
            DependencyProperty.Register(
                "RadiusBase",
                typeof (double),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(15.0)
                );

        public static readonly DependencyProperty RadiusVariationProperty =
            DependencyProperty.Register(
                "RadiusVariation",
                typeof (double),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(5.0)
                );

        public static readonly DependencyProperty StartColorProperty =
            DependencyProperty.Register(
                "StartColor",
                typeof (Color),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(Color.FromArgb(245, 200, 50, 20))
                );

        public static readonly DependencyProperty EndColorProperty =
            DependencyProperty.Register(
                "EndColor",
                typeof (Color),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(Color.FromArgb(100, 200, 255, 20))
                );

        public static readonly DependencyProperty StartColorVariationProperty =
            DependencyProperty.Register(
                "StartColorVariation",
                typeof (Color),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(Color.FromArgb(10, 55, 50, 20))
                );

        public static readonly DependencyProperty EndColorVariationProperty =
            DependencyProperty.Register(
                "EndColorVariation",
                typeof (Color),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(Color.FromArgb(50, 20, 100, 20))
                );

        public static readonly DependencyProperty MouseDropDelayProperty =
            DependencyProperty.Register(
                "MouseDropDelay",
                typeof (double),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(0.1)
                );

        public static readonly DependencyProperty MouseDropDelayVariationProperty =
            DependencyProperty.Register(
                "MouseDropDelayVariation",
                typeof (double),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(0.05)
                );

        public static readonly DependencyProperty ClickBurstSizeProperty =
            DependencyProperty.Register(
                "ClickBurstSize",
                typeof (int),
                typeof (FireworkEffect),
                new FrameworkPropertyMetadata(30)
                );

        #endregion

        #region Properties

        public double Radius
        {
            get { return (double) GetValue(RadiusProperty); }
            set { SetValue(RadiusProperty, value); }
        }

        public double RadiusVariation
        {
            get { return (double) GetValue(RadiusVariationProperty); }
            set { SetValue(RadiusVariationProperty, value); }
        }

        public Color StartColor
        {
            get { return (Color) GetValue(StartColorProperty); }
            set { SetValue(StartColorProperty, value); }
        }

        public Color EndColor
        {
            get { return (Color) GetValue(EndColorProperty); }
            set { SetValue(EndColorProperty, value); }
        }

        public Color StartColorVariation
        {
            get { return (Color) GetValue(StartColorVariationProperty); }
            set { SetValue(StartColorVariationProperty, value); }
        }

        public Color EndColorVariation
        {
            get { return (Color) GetValue(EndColorVariationProperty); }
            set { SetValue(EndColorVariationProperty, value); }
        }


        public bool BounceOffContainer { get; set; } = false;

        public bool GravitateToMouse { get; set; } = false;

        public double GravitateScale { get; set; } = 0.1;

        public bool MouseDropsParticles { get; set; } = false;

        public double MouseDropDelay
        {
            get { return (double) GetValue(MouseDropDelayProperty); }
            set { SetValue(MouseDropDelayProperty, value); }
        }

        public double MouseDropDelayVariation
        {
            get { return (double) GetValue(MouseDropDelayVariationProperty); }
            set { SetValue(MouseDropDelayVariationProperty, value); }
        }

        public int ClickBurstSize
        {
            get { return (int) GetValue(ClickBurstSizeProperty); }
            set { SetValue(ClickBurstSizeProperty, value); }
        }

        #endregion
    }
}

<|start_filename|>Threading/UsingDispatcher/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace UsingDispatcher
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Storyboard _hideClockFaceStoryboard;
        private Storyboard _hideWeatherImageStoryboard;
        // Storyboards for the animations.
        private Storyboard _showClockFaceStoryboard;
        private Storyboard _showWeatherImageStoryboard;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Load the storyboard resources.
            _showClockFaceStoryboard =
                (Storyboard) Resources["ShowClockFaceStoryboard"];
            _hideClockFaceStoryboard =
                (Storyboard) Resources["HideClockFaceStoryboard"];
            _showWeatherImageStoryboard =
                (Storyboard) Resources["ShowWeatherImageStoryboard"];
            _hideWeatherImageStoryboard =
                (Storyboard) Resources["HideWeatherImageStoryboard"];
        }

        private void ForecastButtonHandler(object sender, RoutedEventArgs e)
        {
            // Change the status image and start the rotation animation.
            fetchButton.IsEnabled = false;
            fetchButton.Content = "Contacting Server";
            weatherText.Text = "";
            _hideWeatherImageStoryboard.Begin(this);

            // Start fetching the weather forecast asynchronously.
            var fetcher = new NoArgDelegate(
                FetchWeatherFromServer);

            fetcher.BeginInvoke(null, null);
        }

        private void FetchWeatherFromServer()
        {
            // Simulate the delay from network access.
            Thread.Sleep(4000);

            // Tried and true method for weather forecasting - random numbers.
            var rand = new Random();
            string weather;

            weather = rand.Next(2) == 0 ? "rainy" : "sunny";

            // Schedule the update function in the UI thread.
            tomorrowsWeather.Dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                new OneArgDelegate(UpdateUserInterface),
                weather);
        }

        private void UpdateUserInterface(string weather)
        {
            //Set the weather image
            if (weather == "sunny")
            {
                weatherIndicatorImage.Source = (ImageSource) Resources[
                    "SunnyImageSource"];
            }
            else if (weather == "rainy")
            {
                weatherIndicatorImage.Source = (ImageSource) Resources[
                    "RainingImageSource"];
            }

            //Stop clock animation
            _showClockFaceStoryboard.Stop(this);
            _hideClockFaceStoryboard.Begin(this);

            //Update UI text
            fetchButton.IsEnabled = true;
            fetchButton.Content = "Fetch Forecast";
            weatherText.Text = weather;
        }

        private void HideClockFaceStoryboard_Completed(object sender,
            EventArgs args)
        {
            _showWeatherImageStoryboard.Begin(this);
        }

        private void HideWeatherImageStoryboard_Completed(object sender,
            EventArgs args)
        {
            _showClockFaceStoryboard.Begin(this, true);
        }

        private delegate void NoArgDelegate();

        private delegate void OneArgDelegate(string arg);
    }
}

<|start_filename|>Speech and Media/MediaGallery/PositionConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace MediaGallery
{
    public class PositionConverter : IValueConverter
    {
        public object Convert(object o, Type type, object param, CultureInfo cul)
        {
            var currPosition = (TimeSpan) o;
            return currPosition.Seconds;
        }

        public object ConvertBack(object o, Type type, object param, CultureInfo cul) => null;
    }
}

<|start_filename|>Accessibility/SelectionPattern/SelectionPatternSample/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Application = System.Windows.Forms.Application;

namespace SelectionPatternSample
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// --------------------------------------------------------------------
        /// <summary>
        ///     The various permutations of client controls.
        /// </summary>
        /// <remarks>
        ///     The state of the client application impacts which client controls
        ///     are available.
        /// </remarks>
        /// --------------------------------------------------------------------
        public enum ControlState
        {
            /// <summary>
            ///     Initial state of the client.
            /// </summary>
            Initial,

            /// <summary>
            ///     Target is available.
            /// </summary>
            TargetStarted,

            /// <summary>
            ///     The UI Automation worker has started.
            /// </summary>
            UIAStarted,

            /// <summary>
            ///     The UI Automation worker has stopped or target has been closed.
            /// </summary>
            UIAStopped
        };

        private readonly string _filePath =
            Application.StartupPath +
            "\\SelectionTarget.exe";

        private GroupBox[] _clientGroupBox;
        private ListBox[] _clientListBox;
        private TextBlock[] _clientTextBlockMultiple;
        private TextBlock[] _clientTextBlockRequired;
        private TextBlock[] _clientTextBlockSelected;
        private StringBuilder _feedbackText;
        private int _selectionControlCounter;
        private AutomationElement _targetApp;
        private TargetHandler _targetHandler;

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handle window loaded event.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments</param>
        /// --------------------------------------------------------------------
        private void Client_OnLoad(object sender, RoutedEventArgs e)
        {
            SetClientControlState(ControlState.Initial);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the click event for the Start App button.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void buttonStartTarget_Click(object sender, RoutedEventArgs e)
        {
            _targetApp = StartTargetApp(_filePath);

            if (_targetApp == null)
            {
                Feedback("Unable to start target application.");
                SetClientControlState(ControlState.UIAStopped);
                return;
            }
            Feedback("Target started.");

            _targetHandler = new TargetHandler(this, _targetApp);
            _targetHandler.StartWork();

            SetClientControlState(ControlState.TargetStarted);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Echo the target selection controls in the client.
        /// </summary>
        /// --------------------------------------------------------------------
        internal void EchoTargetControls()
        {
            textControlsCounter.Text =
                _targetHandler.TargetControls.Count.ToString();
            if (_targetHandler.TargetControls.Count <= 0)
            {
                return;
            }

            _clientGroupBox = new GroupBox[_targetHandler.TargetControls.Count];
            _clientListBox = new ListBox[_targetHandler.TargetControls.Count];
            _clientTextBlockMultiple = new TextBlock[_targetHandler.TargetControls.Count];
            _clientTextBlockRequired = new TextBlock[_targetHandler.TargetControls.Count];
            _clientTextBlockSelected = new TextBlock[_targetHandler.TargetControls.Count];

            for (var controlCounter = 0;
                controlCounter < _targetHandler.TargetControls.Count;
                controlCounter++)
            {
                // You can set the cache request tree scope to cache the 
                // children of the selection control at the same time.
                // However, this presents a problem with the combo box. 
                // Since the combo box is an aggregate control
                // the children include more than just the selection items.
                var selectionItemControls =
                    _targetHandler.GetSelectionItemsFromTarget(
                        _targetHandler.TargetControls[controlCounter]);

                // Initialize the control mappings.
                _clientGroupBox[controlCounter] = new GroupBox
                {
                    Padding = new Thickness(2),
                    Margin = new Thickness(10),
                    Header = _targetHandler.TargetControls[controlCounter].Current.AutomationId
                };
                stackControls.Children.Add(_clientGroupBox[controlCounter]);

                _clientTextBlockMultiple[controlCounter] = new TextBlock();
                _clientTextBlockRequired[controlCounter] = new TextBlock();
                _clientTextBlockSelected[controlCounter] = new TextBlock();
                SetControlPropertiesText(controlCounter);

                _clientListBox[controlCounter] = new ListBox();
                EchoTargetControlProperties(_targetHandler.TargetControls[controlCounter], controlCounter);

                var clientStackPanel = new StackPanel();
                clientStackPanel.Children.Add(_clientTextBlockMultiple[controlCounter]);
                clientStackPanel.Children.Add(_clientTextBlockRequired[controlCounter]);
                clientStackPanel.Children.Add(_clientTextBlockSelected[controlCounter]);
                clientStackPanel.Children.Add(_clientListBox[controlCounter]);
                _clientGroupBox[controlCounter].Content = clientStackPanel;

                _targetHandler.SetTargetSelectionEventHandlers();

                for (var selectionItem = 0;
                    selectionItem < selectionItemControls.Count;
                    selectionItem++)
                {
                    _clientListBox[controlCounter].Items.Add(
                        selectionItemControls[selectionItem].Current.Name);
                }
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Display the relevant target control properties.
        /// </summary>
        /// <param name="controlCounter">
        ///     Current selection control in target.
        /// </param>
        /// --------------------------------------------------------------------
        internal void SetControlPropertiesText(int controlCounter)
        {
            // Check if we need to call BeginInvoke.
            if (Dispatcher.CheckAccess() == false)
            {
                // Pass the same function to BeginInvoke,
                // but the call would come on the correct
                // thread and InvokeRequired will be false.
                Dispatcher.BeginInvoke(
                    DispatcherPriority.Send,
                    new SetControlPropertiesTextDelegate(SetControlPropertiesText),
                    controlCounter);
                return;
            }

            string propertyText;
            propertyText =
                "Can select multiple: " +
                _targetHandler.TargetControls[controlCounter].GetCurrentPropertyValue(
                    SelectionPattern.CanSelectMultipleProperty);

            _clientTextBlockMultiple[controlCounter].Text = propertyText;
            _clientTextBlockMultiple[controlCounter].Foreground =
                Brushes.Black;
            _clientTextBlockMultiple[controlCounter].Background =
                ((bool) _targetHandler.TargetControls[controlCounter].GetCurrentPropertyValue(
                    SelectionPattern.CanSelectMultipleProperty))
                    ? Brushes.White
                    : Brushes.LightYellow;

            propertyText =
                "Is selection required: " +
                _targetHandler.TargetControls[controlCounter].GetCurrentPropertyValue(
                    SelectionPattern.IsSelectionRequiredProperty);
            _clientTextBlockRequired[controlCounter].Text = propertyText;
            _clientTextBlockRequired[controlCounter].Foreground =
                ((bool) _targetHandler.TargetControls[controlCounter].GetCurrentPropertyValue(
                    SelectionPattern.IsSelectionRequiredProperty))
                    ? Brushes.Blue
                    : Brushes.Black;

            propertyText =
                "Items selected: " +
                _targetHandler.GetTargetCurrentSelection(
                    _targetHandler.TargetControls[controlCounter]).Length;
            _clientTextBlockSelected[controlCounter].Text = propertyText;
            _clientTextBlockSelected[controlCounter].Foreground =
                Brushes.Black;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Echo the target control properties in the client.
        /// </summary>
        /// <param name="targetSelectionControl">
        ///     Current selection control in target.
        /// </param>
        /// <param name="controlCounter">
        ///     Index of current selection control.
        /// </param>
        /// --------------------------------------------------------------------
        internal void EchoTargetControlProperties(
            AutomationElement targetSelectionControl,
            int controlCounter)
        {
            // Check if we need to call BeginInvoke.
            if (Dispatcher.CheckAccess() == false)
            {
                // Pass the same function to BeginInvoke,
                // but the call would come on the correct
                // thread and InvokeRequired will be false.
                Dispatcher.BeginInvoke(
                    DispatcherPriority.Send,
                    new EchoTargetControlPropertiesDelegate(EchoTargetControlProperties),
                    targetSelectionControl, controlCounter);
                return;
            }

            _clientListBox[controlCounter].Name =
                targetSelectionControl.Current.AutomationId;

            _clientListBox[controlCounter].SelectionMode =
                ((bool) targetSelectionControl.GetCurrentPropertyValue(
                    SelectionPattern.CanSelectMultipleProperty))
                    ? SelectionMode.Multiple
                    : SelectionMode.Single;

            _clientListBox[controlCounter].Background =
                (_clientListBox[controlCounter].SelectionMode ==
                 SelectionMode.Single)
                    ? Brushes.LightYellow
                    : Brushes.White;

            _clientListBox[controlCounter].Foreground =
                ((bool) targetSelectionControl.GetCurrentPropertyValue(
                    SelectionPattern.IsSelectionRequiredProperty))
                    ? Brushes.Blue
                    : Brushes.Black;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Mirrors target selections in client list boxes.
        /// </summary>
        /// <param name="targetSelectionControl">
        ///     Current target selection control.
        /// </param>
        /// <param name="controlCounter">
        ///     Index of current selection control.
        /// </param>
        /// --------------------------------------------------------------------
        internal void EchoTargetControlSelections(
            AutomationElement targetSelectionControl,
            int controlCounter)
        {
            // Check if we need to call BeginInvoke.
            if (Dispatcher.CheckAccess() == false)
            {
                // Pass the same function to BeginInvoke,
                // but the call would come on the correct
                // thread and InvokeRequired will be false.
                Dispatcher.BeginInvoke(
                    DispatcherPriority.Send,
                    new EchoTargetControlSelectionsDelegate(EchoTargetControlSelections),
                    targetSelectionControl, controlCounter);
                return;
            }
            var targetSelectionItems =
                _targetHandler.GetSelectionItemsFromTarget(targetSelectionControl);
            for (var itemCounter = 0;
                itemCounter < targetSelectionItems.Count;
                itemCounter++)
            {
                var selectionItemPattern =
                    targetSelectionItems[itemCounter].GetCurrentPattern(
                        SelectionItemPattern.Pattern) as SelectionItemPattern;
                var listboxItem =
                    GetClientItemFromIndex(_clientListBox[controlCounter], itemCounter);
                listboxItem.IsSelected =
                    selectionItemPattern.Current.IsSelected;
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Gets an item from a WPF list box based on index.
        /// </summary>
        /// <param name="listBox">
        ///     Current client list box.
        /// </param>
        /// <param name="index">
        ///     Index of current list box item.
        /// </param>
        /// --------------------------------------------------------------------
        internal ListBoxItem GetClientItemFromIndex(ListBox listBox, int index) => (ListBoxItem)(listBox.ItemContainerGenerator.ContainerFromIndex(index));

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the request to change the direction of user input from
        ///     client to target and vice versa.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void ChangeEchoDirection(object sender, RoutedEventArgs e)
        {
            Feedback("");

            var echoDirection = ((RadioButton) sender).Content.ToString();

            ResetSelectionHandlers(_clientListBox, echoDirection);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Manages the selection handlers for client and target.
        /// </summary>
        /// <param name="clientListBox">
        ///     The array of ListBox controls in the client.
        /// </param>
        /// <param name="echoDirection">
        ///     The direction to echo selection events (that is, client or target).
        /// </param>
        /// --------------------------------------------------------------------
        internal void ResetSelectionHandlers(ListBox[] clientListBox, string echoDirection)
        {
            for (var controlCounter = 0;
                controlCounter < _targetHandler.TargetControls.Count;
                controlCounter++)
            {
                _targetHandler.RemoveTargetSelectionEventHandlers();

                clientListBox[controlCounter].SelectionChanged -=
                    ClientSelectionHandler;

                if (echoDirection == "Client")
                {
                    _targetHandler.SetTargetSelectionEventHandlers();
                }
                else
                {
                    clientListBox[controlCounter].SelectionChanged +=
                        ClientSelectionHandler;
                }
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles user input in the client.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        internal void ClientSelectionHandler(
            object sender, SelectionChangedEventArgs e)
        {
            _feedbackText = new StringBuilder();
            var clientListBox = sender as ListBox;

            foreach (
                AutomationElement targetControl in
                    _targetHandler.TargetControls)
            {
                if (clientListBox.Name ==
                    targetControl.Current.AutomationId)
                {
                    var selectionPattern =
                        targetControl.GetCurrentPattern(
                            SelectionPattern.Pattern) as SelectionPattern;
                    var targetSelectionItems =
                        _targetHandler.GetSelectionItemsFromTarget(targetControl);

                    if (e.AddedItems.Count > 0)
                    {
                        for (var itemCounter = 0;
                            itemCounter < clientListBox.Items.Count;
                            itemCounter++)
                        {
                            var listboxItem =
                                GetClientItemFromIndex(
                                    clientListBox, itemCounter);
                            var selectionItemPattern =
                                targetSelectionItems[itemCounter].GetCurrentPattern(
                                    SelectionItemPattern.Pattern) as
                                    SelectionItemPattern;

                            if (!(selectionItemPattern.Current.IsSelected) &&
                                listboxItem.IsSelected)
                            {
                                if (selectionPattern.Current.GetSelection().Length < 1)
                                {
                                    try
                                    {
                                        selectionItemPattern.Select();
                                        _feedbackText.Append(
                                            targetSelectionItems[itemCounter].Current.Name)
                                            .Append(" of the ")
                                            .Append(
                                                targetControl.Current.AutomationId)
                                            .Append(" control was selected.");
                                        Feedback(_feedbackText.ToString());
                                    }
                                    catch (InvalidOperationException exc)
                                    {
                                        Feedback(exc.Message);
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        if (selectionPattern.Current.CanSelectMultiple)
                                        {
                                            selectionItemPattern.AddToSelection();
                                            _feedbackText.Append(
                                                targetSelectionItems[itemCounter].Current.Name)
                                                .Append(" of the ")
                                                .Append(
                                                    targetControl.Current.AutomationId)
                                                .Append(
                                                    " control was added to the selection.");
                                            Feedback(_feedbackText.ToString());
                                        }
                                        else
                                        {
                                            selectionItemPattern.Select();
                                            _feedbackText.Append(
                                                targetSelectionItems[itemCounter].Current.Name)
                                                .Append(" of the ")
                                                .Append(
                                                    targetControl.Current.AutomationId)
                                                .Append(" control was selected.");
                                            Feedback(_feedbackText.ToString());
                                        }
                                    }
                                    catch (InvalidOperationException exc)
                                    {
                                        Feedback(exc.Message);
                                    }
                                }
                                break;
                            }
                        }
                    }
                    else if (e.RemovedItems.Count > 0)
                    {
                        for (var itemCounter = 0;
                            itemCounter < clientListBox.Items.Count;
                            itemCounter++)
                        {
                            var listboxItem =
                                GetClientItemFromIndex(clientListBox, itemCounter);
                            var selectionItemPattern =
                                targetSelectionItems[itemCounter].GetCurrentPattern(
                                    SelectionItemPattern.Pattern) as
                                    SelectionItemPattern;

                            if ((selectionItemPattern.Current.IsSelected)
                                && !listboxItem.IsSelected)
                            {
                                try
                                {
                                    selectionItemPattern.RemoveFromSelection();
                                    _feedbackText.Append(
                                        targetSelectionItems[itemCounter].Current.Name)
                                        .Append(" of the ")
                                        .Append(
                                            targetControl.Current.AutomationId)
                                        .Append(
                                            " control was removed from the selection.");
                                    Feedback(_feedbackText.ToString());
                                    break;
                                }
                                catch (InvalidOperationException exc)
                                {
                                    Feedback(exc.Message);
                                }
                            }
                        }
                    }
                }
                for (var controlCounter = 0;
                    controlCounter < _targetHandler.TargetControls.Count;
                    controlCounter++)
                {
                    SetControlPropertiesText(controlCounter);
                    EchoTargetControlProperties(
                        _targetHandler.TargetControls[controlCounter],
                        controlCounter);
                }
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Starts the target application.
        /// </summary>
        /// <returns>The target automation element.</returns>
        /// --------------------------------------------------------------------
        private AutomationElement StartTargetApp(string target)
        {
            if (!File.Exists(target))
            {
                _feedbackText.Append(target);
                _feedbackText.Append(" not found.");
                Feedback(_feedbackText.ToString());
                return null;
            }
            try
            {
                // Start target application.
                var startInfo = new ProcessStartInfo(target)
                {
                    WindowStyle = ProcessWindowStyle.Normal,
                    UseShellExecute = true
                };

                var p = Process.Start(startInfo);

                // Give the target application some time to startup.
                // For Win32 applications, WaitForInputIdle can be used instead.
                // Another alternative is to listen for WindowOpened events.
                // Otherwise, an ArgumentException results when you try to
                // retrieve an automation element from the window handle.
                Thread.Sleep(5000);

                // Return the automation element
                var windowHandle = p.MainWindowHandle;
                return (AutomationElement.FromHandle(windowHandle));
            }
            catch (ArgumentException)
            {
                // To do: error handling
                return null;
            }
            catch (Win32Exception)
            {
                // To do: error handling
                return null;
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Outputs information to the client window.
        /// </summary>
        /// <param name="message">The string to display.</param>
        /// --------------------------------------------------------------------
        internal void Feedback(string message)
        {
            // Check if we need to call BeginInvoke.
            if (Dispatcher.CheckAccess() == false)
            {
                // Pass the same function to BeginInvoke,
                // but the call would come on the correct
                // thread and InvokeRequired will be false.
                Dispatcher.BeginInvoke(
                    DispatcherPriority.Send,
                    new FeedbackDelegate(Feedback),
                    message);
                return;
            }
            textFeedback.Text = message + Environment.NewLine;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Modifies the state of the controls on the form.
        /// </summary>
        /// <param name="controlState">
        ///     The current state of the target application.
        /// </param>
        /// <remarks>
        ///     Check thread safety for client updates based on target events.
        /// </remarks>
        /// --------------------------------------------------------------------
        internal void SetClientControlState(ControlState controlState)
        {
            // Check if we need to call BeginInvoke.
            if (Dispatcher.CheckAccess() == false)
            {
                // Pass the same function to BeginInvoke,
                // but the call would come on the correct
                // thread and InvokeRequired will be false.
                Dispatcher.BeginInvoke(
                    DispatcherPriority.Send,
                    new SetClientControlStateDelegate(SetClientControlState),
                    controlState);
                return;
            }
            switch (controlState)
            {
                case ControlState.Initial:
                    buttonStartTarget.IsEnabled = true;
                    textControlsCounter.Text = _selectionControlCounter.ToString();
                    Echo.Visibility = Visibility.Hidden;
                    break;
                case ControlState.TargetStarted:
                    buttonStartTarget.IsEnabled = false;
                    Echo.Visibility = Visibility.Visible;
                    break;
                case ControlState.UIAStarted:
                    buttonStartTarget.IsEnabled = false;
                    textControlsCounter.Text = _selectionControlCounter.ToString();
                    Echo.Visibility = Visibility.Visible;
                    break;
                case ControlState.UIAStopped:
                    buttonStartTarget.IsEnabled = true;
                    buttonStartTarget.Content = "Target has been closed - Restart";
                    echoClient.IsChecked = true;
                    _selectionControlCounter = 0;
                    stackControls.Children.Clear();
                    textControlsCounter.Text = _selectionControlCounter.ToString();
                    Echo.Visibility = Visibility.Hidden;
                    break;
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Thread-safe delegate.
        /// </summary>
        /// <param name="controlCounter">
        ///     Index of current selection control.
        /// </param>
        /// --------------------------------------------------------------------
        internal delegate void SetControlPropertiesTextDelegate(int controlCounter);

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Thread-safe delegate.
        /// </summary>
        /// <param name="targetSelectionControl">
        ///     Current selection control in target.
        /// </param>
        /// <param name="controlCounter">
        ///     Index of current selection control.
        /// </param>
        /// --------------------------------------------------------------------
        internal delegate void EchoTargetControlPropertiesDelegate(
            AutomationElement targetSelectionControl,
            int controlCounter);

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Thread-safe delegate.
        /// </summary>
        /// <param name="targetSelectionControl">
        ///     Current selection control in target.
        /// </param>
        /// <param name="controlCounter">
        ///     Index of current selection control.
        /// </param>
        /// --------------------------------------------------------------------
        internal delegate void EchoTargetControlSelectionsDelegate(
            AutomationElement targetSelectionControl,
            int controlCounter);

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Thread-safe delegate.
        /// </summary>
        /// <param name="message">The string to display.</param>
        /// --------------------------------------------------------------------
        internal delegate void FeedbackDelegate(string message);

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Thread-safe delegate.
        /// </summary>
        /// <param name="controlState">
        ///     The current state of the target application.
        /// </param>
        /// --------------------------------------------------------------------
        internal delegate void SetClientControlStateDelegate(ControlState controlState);
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/ApplicationResource.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Resources;

namespace BamlTools
{
    public class ApplicationResource
    {
        private readonly string _resourceName;
        private readonly Assembly _assembly;
        private readonly ObservableCollection<BamlResource> _bamlResources = new ObservableCollection<BamlResource>();

        public ApplicationResource(Assembly assembly, string resourceName)
        {
            _assembly = assembly;
            _resourceName = resourceName;
            Stream resourceStream = assembly.GetManifestResourceStream(resourceName);

            using ResourceReader reader = new ResourceReader(resourceStream);
            List<BamlResource> bamlResourceList = new List<BamlResource>();

            if (reader != null)
            {
                foreach (DictionaryEntry entry in reader)
                {
                    string keyName = entry.Key as string;
                    if (keyName.EndsWith(".baml", StringComparison.InvariantCultureIgnoreCase)
                        || keyName.EndsWith(".xaml", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Type valuesType = entry.Value.GetType();
                        if (typeof(Stream).IsAssignableFrom(valuesType))
                        {
                            Stream source = entry.Value as Stream;
                            bamlResourceList.Add(new BamlResource(keyName, source, assembly));
                        }
                    }
                }
            }
            bamlResourceList.Sort(BamlResource.SortCompare);
            foreach (BamlResource br in bamlResourceList)
            {
                BamlResources.Add(br);
            }
        }

        public string ResourceName { get { return _resourceName; } }

        public ObservableCollection<BamlResource> BamlResources
        {
            get { return _bamlResources; }
        }

        public Assembly Assembly
        {
            get { return _assembly; }
        }
    }
}


<|start_filename|>Elements/FindingElementInPanel/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace FindingElementInPanel
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int _cCounter;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void FindIndex(object sender, RoutedEventArgs e)
        {
            _cCounter += 1;
            // Create a new Text element.
            var newText = new TextBlock();
            // Add this element to the UIElementCollection of the DockPanel element.
            MainDisplayPanel.Children.Add(newText);
            // Add a text node under the Text element. This text is displayed. 
            newText.Text = "New element #" + _cCounter;
            DockPanel.SetDock(newText, Dock.Top);
            // Display the Index number of the new element.    
            TxtDisplay.Text = "The Index of the new element is " + MainDisplayPanel.Children.IndexOf(newText);
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/aitencoder.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Declaration of AitEncoder
//----------------------------------------------------------------------------------------
#include "precomp.hpp"
static const GUID CLSID_AitEncoder             = { 0xEEC50239, 0x14BB, 0x4F70, { 0xAD, 0x2A, 0xB7, 0x12, 0x62, 0x19, 0xA6, 0xDC } };
//----------------------------------------------------------------------------------------
// UTILITY FUNCTIONS
//----------------------------------------------------------------------------------------

static ULARGE_INTEGER lastBlockPos = { 0 };

static HRESULT BeginBlock(IStream *stream, LPCSTR name, UINT frameNum)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    // Remember where we are
    if (SUCCEEDED(result))
    {
        LARGE_INTEGER zero = { 0 };
        result = stream->Seek(zero, STREAM_SEEK_CUR, &lastBlockPos);
    }

    // The number of bytes is stored as zero for now. The function EndBlock will write the
    // correct value later.
    UINT numBytes = 0;

    // Output the name
    if (SUCCEEDED(result))
    {
        result = OutputValues(stream, name, 4);                        
    }

    // Output the frame number
    if (SUCCEEDED(result))
    {
        result = OutputValue(stream, frameNum);
    }

    // Output the size
    if (SUCCEEDED(result))
    {
        result = OutputValue(stream, numBytes);
    }

    return result;
}

static HRESULT EndBlock(IStream *stream)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    // Remember where we are
    ULARGE_INTEGER curPos = { 0 };

    if (SUCCEEDED(result))
    {
        LARGE_INTEGER zero = { 0 };
        result = stream->Seek(zero, STREAM_SEEK_CUR, &curPos);
    }

    // Move to where the size of the last block is stored
    if (SUCCEEDED(result))
    {
        LARGE_INTEGER newPos;
        newPos.QuadPart = static_cast<LONGLONG>(lastBlockPos.QuadPart) + 2*sizeof(UINT);

        result = stream->Seek(newPos, STREAM_SEEK_SET, NULL);
    }

    // Store the size
    if (SUCCEEDED(result))
    {
        UINT size = static_cast<UINT>(curPos.QuadPart - lastBlockPos.QuadPart) - 3*sizeof(UINT);

        result = OutputValue(stream, size);
    }

    // Move back to where we should be
    if (SUCCEEDED(result))
    {
        LARGE_INTEGER cp;
        cp.QuadPart = static_cast<LONGLONG>(curPos.QuadPart);

        result = stream->Seek(cp, STREAM_SEEK_SET, NULL);
    }

    return result;
}

static HRESULT OutputBitmapSource(IStream *stream, LPCSTR name, UINT frameNum,
                                  double dpiX, double dpiY,
                                  IWICBitmapSource *source)
{
    HRESULT result = E_INVALIDARG;

    if (stream && source)
    {
        UINT width = 0, height = 0;
        UINT stride = 0;
        WICPixelFormatGUID pixelFormat;
        BYTE *pixels = NULL;

        result = S_OK;

        // Retrieve the dimensions of the source
        if (SUCCEEDED(result))
        {
            result = source->GetSize(&width, &height);
        }

        // Optionally retrieve the resolution
        if (SUCCEEDED(result) && (dpiX == 0 || dpiY == 0))
        {
            result = source->GetResolution(&dpiX, &dpiY);
        }

        // Get the pixel format
        if (SUCCEEDED(result))
        {
            result = source->GetPixelFormat(&pixelFormat);
        }

        // Get the stride
        if (SUCCEEDED(result))
        {
            stride = GetScanlineStride(width, pixelFormat);

            if (stride < 1)
            {
                result = E_UNEXPECTED;
            }
        }

        // Allocate the pixels
        if (SUCCEEDED(result))
        {
            pixels = new BYTE[stride * height];

            if (NULL == pixels)
            {
                result = E_OUTOFMEMORY;
            }
        }

        // Get the pixels
        if (SUCCEEDED(result))
        {
            WICRect rct;
            rct.X = 0;
            rct.Y = 0;
            rct.Width = width;
            rct.Height = height;

            result = source->CopyPixels(&rct, stride, stride * height, pixels);
        }

        // Output everything
        if (SUCCEEDED(result))
        {
            BeginBlock(stream, name, frameNum);
            OutputValue(stream, width);
            OutputValue(stream, height);
            OutputValue(stream, dpiX);
            OutputValue(stream, dpiY);
            OutputValue(stream, stride);
            OutputValue(stream, pixelFormat);
            OutputValues(stream, pixels, stride*height);
            result = EndBlock(stream);
        }

        if (pixels)
        {
            delete[] pixels;
        }
    }

    return result;
}

static HRESULT OutputBitmapPalette(IStream *stream, UINT frameNum, IWICPalette *palette)
{
    HRESULT result = E_INVALIDARG;

    if (stream && palette)
    {
        UINT colorCount = 0;
        WICColor *colors = NULL;

        result = S_OK;

        if (SUCCEEDED(result))
        {
            result = palette->GetColorCount(&colorCount);
        }

        if (colorCount > 0)
        {

            if (SUCCEEDED(result))
            {
                colors = new WICColor[colorCount];

                if (NULL == colors)
                {
                    result = E_OUTOFMEMORY;
                }
            }

            if (SUCCEEDED(result))
            {
                UINT cActualColors = 0;
                result = palette->GetColors(colorCount, colors, &cActualColors);
            }

            if (SUCCEEDED(result))
            {
                BeginBlock(stream, "PAL", frameNum);
                OutputValue(stream, colorCount);
                OutputValues(stream, colors, colorCount);
                result = EndBlock(stream);
            }

            if (colors)
            {
                delete[] colors;
            }
        }
    }

    return result;
}

static HRESULT OutputColorContext(IStream *stream, UINT frameNum, UINT colorContextCount, IWICColorContext **colorContext)
{
    HRESULT result = E_INVALIDARG;
    if (stream && colorContext)
    {
        BeginBlock(stream, "COL", frameNum);
        for(int i = 0; i < colorContextCount; i++)
        {
            UINT numBytes = 0;
            BYTE *bytes = NULL;
    
            result = S_OK;

            if (SUCCEEDED(result))
            {
                result = colorContext[i]->GetProfileBytes(0, NULL, &numBytes);
            }

            if (numBytes > 0)
            {
                if (SUCCEEDED(result))
                {
                    bytes = new BYTE[numBytes];
    
                    if (NULL == bytes)
                    {
                        result = E_OUTOFMEMORY;
                    }
                }

                if (SUCCEEDED(result))
                {
                    result = colorContext[i]->GetProfileBytes(numBytes, bytes, &numBytes);
                }

                if (SUCCEEDED(result))
                {                    
                    OutputValue(stream, numBytes);
                    OutputValues(stream, bytes, numBytes);                    
                }

                if (bytes)
                {
                    delete[] bytes;
                }
            }
       }
       result = EndBlock(stream);
    }
    return result;
}


//----------------------------------------------------------------------------------------
// FRAME ENCODE
//----------------------------------------------------------------------------------------

AitFrameEncode::AitFrameEncode(IWICImagingFactory *pIFactory, IStream *pIStream, UINT num)
    : BaseFrameEncode(pIFactory, pIStream, num)
{
   
}

AitFrameEncode::~AitFrameEncode()
{
}

STDMETHODIMP AitFrameEncode::Commit()
{
    HRESULT result = E_UNEXPECTED;
    result = BaseFrameEncode::Commit();

    if (SUCCEEDED(result))
    {
        result = OutputBitmapSource(stream, "FRA", frameNumber, destDpiX, destDpiY, destSource);
    }

    if (SUCCEEDED(result) && (NULL != destPalette))
    {
        result = OutputBitmapPalette(stream, frameNumber, destPalette);
    }

    if (SUCCEEDED(result) && (colorContexts.size() != 0))
    {
        IWICColorContext** ppIColorContext = new IWICColorContext*[colorContexts.size()];
        for (int i = 0; i < (UINT)colorContexts.size(); i++)
        {
            ppIColorContext[i] = colorContexts[i];            
        }  
        result = OutputColorContext(stream, frameNumber, (UINT)colorContexts.size(), ppIColorContext);
        delete[] ppIColorContext;
    }

    if (SUCCEEDED(result) && (NULL != destThumbnail))
    {
        result = OutputBitmapSource(stream, "THU", frameNumber, 0, 0, destThumbnail);
    }

    if (SUCCEEDED(result) && (NULL != destPreview))
    {
        result = OutputBitmapSource(stream, "PRE", frameNumber, 0, 0, destPreview);
    }

    return result;
}

STDMETHODIMP AitFrameEncode::GetMetadataQueryWriter(IWICMetadataQueryWriter **ppIMetadataQueryWriter)
{
    return E_NOTIMPL;
}


//----------------------------------------------------------------------------------------
// ENCODER
//----------------------------------------------------------------------------------------

AitEncoder::AitEncoder()
    : BaseEncoder(CLSID_AitEncoder, CLSID_AitContainer)
{
}

AitEncoder::~AitEncoder()
{  
}


STDMETHODIMP AitEncoder::Initialize(IStream *pIStream, WICBitmapEncoderCacheOption cacheOption)
{
    HRESULT result = E_INVALIDARG;

    if (pIStream)
    {
        result = S_OK;

        stream = pIStream;

        if (SUCCEEDED(result))
        {
            result = VerifyFactory();
        }

        // Remember the position of the header for later reference
        if (SUCCEEDED(result))
        {
            LARGE_INTEGER zero = { 0 };
            result = stream->Seek(zero, STREAM_SEEK_CUR, &headerPos);
        }

        // Write the header with a placeholder for the number of frames
        if (SUCCEEDED(result))
        {
            BeginBlock(stream, "AIT", 0xFFFFFFFF);            
            OutputValue(stream, (UINT)0);
            result = EndBlock(stream);
        }
    }    
    return result;
}

BaseFrameEncode* AitEncoder::CreateNewEncoderFrame(
        /* [in] */  IWICImagingFactory *pIFactory,
        /* [in] */ IStream *pIStream, 
        /* [in] */ UINT num)
{
    return new AitFrameEncode(factory, pIStream, frames.size());
};
STDMETHODIMP AitEncoder::Commit()
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        ULARGE_INTEGER curPos = { 0 };

        result = S_OK;

        // Go back and insert the number of frames
        
        // Remember this position
        if (SUCCEEDED(result))
        {
            LARGE_INTEGER zero = { 0 };
            result = stream->Seek(zero, STREAM_SEEK_CUR, NULL);
        }

        // Seek to the numFrames member of the header
        if (SUCCEEDED(result))
        {
            LARGE_INTEGER pos;
            pos.QuadPart = static_cast<LONGLONG>(headerPos.QuadPart) + 3*sizeof(UINT);

            result = stream->Seek(pos, STREAM_SEEK_SET, NULL);
        }

        // Write the proper value
        if (SUCCEEDED(result))
        {
            UINT numFrames = frames.size();

            result = OutputValue(stream, numFrames);
        }

        // Seek back to where we were
        if (SUCCEEDED(result))
        {
            LARGE_INTEGER pos;
            pos.QuadPart = static_cast<LONGLONG>(curPos.QuadPart);

            result = stream->Seek(pos, STREAM_SEEK_SET, NULL);
        }

        if (SUCCEEDED(result) && (NULL != destPalette))
        {
            result = OutputBitmapPalette(stream, 0xFFFFFFFF, destPalette);
        }

        if (SUCCEEDED(result) && (UINT)colorContexts.size() != 0)
        {
            IWICColorContext** ppIColorContext = new IWICColorContext*[colorContexts.size()];
            for (int i = 0; i < (UINT)colorContexts.size(); i++)
            {
                ppIColorContext[i] = colorContexts[i];            
            }  
            result = OutputColorContext(stream, 0xFFFFFFFF, colorContexts.size(), (IWICColorContext**)ppIColorContext);
            delete[] ppIColorContext;
        }

        if (SUCCEEDED(result) && (NULL != destThumbnail))
        {
            result = OutputBitmapSource(stream, "THU", 0xFFFFFFFF, 0, 0, destThumbnail);
        }

        if (SUCCEEDED(result) && (NULL != destPreview))
        {
            result = OutputBitmapSource(stream, "PRE", 0xFFFFFFFF, 0, 0, destPreview);
        }
    }

    return result;
}

STDMETHODIMP AitEncoder::GetMetadataQueryWriter(IWICMetadataQueryWriter **ppIMetadataQueryWriter)
{
    return E_NOTIMPL;
}


<|start_filename|>Input and Commands/MoveObjectWithMouse/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Input;

namespace MoveObjectWithMouse
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MouseMoveHandler(object sender, MouseEventArgs e)
        {
            // Get the x and y coordinates of the mouse pointer.
            var position = e.GetPosition(this);
            var pX = position.X;
            var pY = position.Y;

            // Sets the Height/Width of the circle to the mouse coordinates.
            ellipse.Width = pX;
            ellipse.Height = pY;
        }
    }
}

<|start_filename|>Sample Applications/FontDialog/TypefaceListItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace FontDialog
{
    internal class TypefaceListItem : TextBlock, IComparable
    {
        private readonly string _displayName;
        private readonly bool _simulated;

        public TypefaceListItem(Typeface typeface)
        {
            _displayName = GetDisplayName(typeface);
            _simulated = typeface.IsBoldSimulated || typeface.IsObliqueSimulated;

            FontFamily = typeface.FontFamily;
            FontWeight = typeface.Weight;
            FontStyle = typeface.Style;
            FontStretch = typeface.Stretch;

            var itemLabel = _displayName;

            if (_simulated)
            {
                var formatString = Properties.Resources.ResourceManager.GetString(
                    "simulated",
                    CultureInfo.CurrentUICulture
                    );
                itemLabel = string.Format(formatString, itemLabel);
            }

            Text = itemLabel;
            ToolTip = itemLabel;

            // In the case of symbol font, apply the default message font to the text so it can be read.
            if (FontFamilyListItem.IsSymbolFont(typeface.FontFamily))
            {
                var range = new TextRange(ContentStart, ContentEnd);
                range.ApplyPropertyValue(FontFamilyProperty, SystemFonts.MessageFontFamily);
            }
        }

        public Typeface Typeface => new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);

        int IComparable.CompareTo(object obj)
        {
            var item = obj as TypefaceListItem;
            if (item == null)
            {
                return -1;
            }

            // Sort all simulated faces after all non-simulated faces.
            if (_simulated != item._simulated)
            {
                return _simulated ? 1 : -1;
            }

            // If weight differs then sort based on weight (lightest first).
            var difference = FontWeight.ToOpenTypeWeight() - item.FontWeight.ToOpenTypeWeight();
            if (difference != 0)
            {
                return difference > 0 ? 1 : -1;
            }

            // If style differs then sort based on style (Normal, Italic, then Oblique).
            var thisStyle = FontStyle;
            var otherStyle = item.FontStyle;

            if (thisStyle != otherStyle)
            {
                if (thisStyle == FontStyles.Normal)
                {
                    // This item is normal style and should come first.
                    return -1;
                }
                if (otherStyle == FontStyles.Normal)
                {
                    // The other item is normal style and should come first.
                    return 1;
                }
                // Neither is normal so sort italic before oblique.
                return (thisStyle == FontStyles.Italic) ? -1 : 1;
            }

            // If stretch differs then sort based on stretch (Normal first, then numerically).
            var thisStretch = FontStretch;
            var otherStretch = item.FontStretch;

            if (thisStretch != otherStretch)
            {
                if (thisStretch == FontStretches.Normal)
                {
                    // This item is normal stretch and should come first.
                    return -1;
                }
                if (otherStretch == FontStretches.Normal)
                {
                    // The other item is normal stretch and should come first.
                    return 1;
                }
                // Neither is normal so sort numerically.
                return thisStretch.ToOpenTypeStretch() < otherStretch.ToOpenTypeStretch() ? -1 : 0;
            }

            // They're the same.
            return 0;
        }

        public override string ToString() => _displayName;

        internal static string GetDisplayName(Typeface typeface) => NameDictionaryHelper.GetDisplayName(typeface.FaceNames);
    }
}

<|start_filename|>Globalization and Localization/NumbersMultipleLangauges/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;
using System.Windows;
using System.Windows.Markup;

namespace NumbersMultipleLangauges
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var currentLanguage =
                CultureInfo.CurrentCulture.IetfLanguageTag;

            text1.Language = XmlLanguage.GetLanguage(currentLanguage);

            text1.FlowDirection = currentLanguage.ToLower().StartsWith("ar")
                ? FlowDirection.RightToLeft
                : FlowDirection.LeftToRight;
        }
    }
}

<|start_filename|>Data Binding/CodeOnlyBinding/MyData.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;

namespace CodeOnlyBinding
{
    public class MyData : INotifyPropertyChanged
    {
        private string _myDataProperty;

        public MyData()
        {
        }

        public MyData(DateTime dateTime)
        {
            _myDataProperty = "Last bound time was " + dateTime.ToLongTimeString();
        }

        public string MyDataProperty
        {
            get { return _myDataProperty; }
            set
            {
                _myDataProperty = value;
                OnPropertyChanged("MyDataProperty");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string info)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}

<|start_filename|>Documents/Flow Content/TextWrapProperty/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace TextWrapProperty
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Wrap(object sender, RoutedEventArgs e)
        {
            txt2.TextWrapping = TextWrapping.Wrap;
            txt1.Text = "The TextWrap property is currently set to Wrap.";
        }

        private void NoWrap(object sender, RoutedEventArgs e)
        {
            txt2.TextWrapping = TextWrapping.NoWrap;
            txt1.Text = "The TextWrap property is currently set to NoWrap.";
        }

        private void WrapWithOverflow(object sender, RoutedEventArgs e)
        {
            txt2.TextWrapping = TextWrapping.WrapWithOverflow;
            txt1.Text = "The TextWrap property is currently set to WrapWithOverflow.";
        }
    }
}

<|start_filename|>Windows/WindowHiding/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;
using System.Windows;

namespace WindowHiding
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ChildWindow _childWindow;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ShowChildWindowButton_Click(object sender, RoutedEventArgs e)
        {
            // Create the window if it's not already created
            if (_childWindow == null)
                _childWindow = new ChildWindow();

            // Show the window
            _childWindow.Show();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            // Close the child window only when this window closes
            _childWindow.Close();
        }
    }
}

<|start_filename|>Windows/SaveWindowState/RECT.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;

namespace SaveWindowState
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    // RECT structure required by WINDOWPLACEMENT structure
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public struct Rect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;

        public Rect(int left, int top, int right, int bottom)
        {
            Left = left;
            Top = top;
            Right = right;
            Bottom = bottom;
        }
    }
}

<|start_filename|>Migration and Interoperability/LocalizingWpfInWf/form1.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;

namespace LocalizingWpfInWf
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES");

            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var sc = new SimpleControlA();

            elementHost1.Child = sc;
        }
    }
}

<|start_filename|>Accessibility/Highlighter/ClientForm.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Drawing;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Forms;
using Timer = System.Timers.Timer;

namespace Highlighter
{
    /// <summary>
    ///     The form for the client application.
    /// </summary>
    public partial class ClientForm : Form
    {
        private readonly Timer _eventTimer;
        private readonly HighlightRectangle _highlight;
        private AutomationElement _focusedElement;
        private Rect _focusedRect;
        private AutomationFocusChangedEventHandler _focusHandler;
        private int _timerInterval;
        private bool _useTimer = true;

        /// <summary>
        ///     Constructor.
        /// </summary>
        public ClientForm()
        {
            // Make the process DPI-aware. Doing this ensures that when the
            // screen is set to a nonstandard DPI, all coordinates are 
            // correctly scaled and the highlight rectangle is displayed
            // in the correct place.
            try
            {
                NativeMethods.SetProcessDPIAware();
            }
            catch (EntryPointNotFoundException)
            {
                // Not running under Vista.
            }
            InitializeComponent();

            // Create timer.
            _timerInterval = tbInterval.Value;
            _eventTimer = new Timer();
            _eventTimer.Elapsed += OnTimerTick;
            _eventTimer.Enabled = false;
            _eventTimer.AutoReset = false;
            _timerInterval = tbInterval.Value;
            _eventTimer.Interval = _timerInterval;

            // Create highlight rectangle.
            _highlight = new HighlightRectangle();

            // Start a new thread to subscribe to UI Automation events.
            var threadDelegate = new ThreadStart(StartListening);
            var uiAutoThread = new Thread(threadDelegate);
            uiAutoThread.Start();
        }

        /// <summary>
        ///     Subscribe to UI Automation events.
        /// </summary>
        /// <remarks>
        ///     Do not call from the UI thread.
        /// </remarks>
        private void StartListening()
        {
            _focusHandler = OnFocusChanged;
            Automation.AddAutomationFocusChangedEventHandler(_focusHandler);
        }

        /// <summary>
        ///     Unsubscribe to UI Automation events.
        /// </summary>
        private void StopListening()
        {
            _eventTimer.Stop();
            Automation.RemoveAutomationFocusChangedEventHandler(_focusHandler);
        }

        /// <summary>
        ///     Responds to focus changes. Starts the timer so that the highlight
        ///     will be updated, or updates the highlight immediately if the timer
        ///     interval is set to 0.
        /// </summary>
        /// <param name="src">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void OnFocusChanged(object src, AutomationFocusChangedEventArgs e)
        {
            _focusedElement = src as AutomationElement;
            _focusedRect = _focusedElement.Current.BoundingRectangle;

#if DEBUG
            Console.WriteLine("Focus moved to: " + _focusedElement.Current.Name);
#endif

            if (_useTimer)
            {
                _eventTimer.Interval = _timerInterval;
                _eventTimer.Start();
            }
            else
            {
                UpdateHighlight();
            }
        }

        /// <summary>
        ///     Hides the old rectangle and creates a new one.
        /// </summary>
        private void UpdateHighlight()
        {
            // Hide old rectangle.
            _highlight.Visible = false;

            // Show new rectangle.
            _highlight.Location = new Rectangle(
                (int) _focusedRect.Left, (int) _focusedRect.Top,
                (int) _focusedRect.Width, (int) _focusedRect.Height);
            _highlight.Visible = true;
        }

        /// <summary>
        ///     Updates the highlight rectangle.
        /// </summary>
        /// <param name="sender">Ojbect that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>The timer stops because AutoReset is false.</remarks>
        private void OnTimerTick(object sender, EventArgs e)
        {
            UpdateHighlight();
        }

        /// <summary>
        ///     Responds to a change in the trackbar.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Setting the value to 0 is equivalent to turning off the timer.
        /// </remarks>
        private void tbInterval_ValueChanged(object sender, EventArgs e)
        {
            if (tbInterval.Value > 0)
            {
                _timerInterval = tbInterval.Value;
                _useTimer = true;
            }
            else
            {
                _useTimer = false;
            }
        }

        /// <summary>
        ///     Responds to Exit button click.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        ///     Responds to form closing. Unsubscribes to UI Automation events.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Start a new thread to unsubscribe to UI Automation events.
            var threadDelegate = new ThreadStart(StopListening);
            var uiAutoThread = new Thread(threadDelegate);
            uiAutoThread.Start();
        }

        /// <summary>
        ///     The entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new ClientForm());
        }
    } // class
} // namespace

<|start_filename|>Tools/BamlReflector/BamlReflector/NewDisassemblyCache.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BamlTools;
using System.Collections.Generic;

namespace BamlReflector
{
    class NewDisassemblyCache
    {
        public string Disassembly { get; set; }

        public List<TypeInfoTableEntry> TypeInfoTable { get; set; }
        public List<AttributeInfoTableEntry> AttributeInfoTable { get; set; }
        //public List<AssemblyInfoTableEntry> AssemblyInfoTable { get; set; }
    }
}


<|start_filename|>Data Binding/ValidateItemSample/PriceIsAPositiveNumber.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Controls;

namespace ValidateItemSample
{
    public class PriceIsAPositiveNumber : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            try
            {
                var price = Convert.ToDouble(value);

                if (price < 0)
                {
                    return new ValidationResult(false, "Price must be positive.");
                }
                return ValidationResult.ValidResult;
            }
            catch (Exception)
            {
                // Exception thrown by Conversion - value is not a number.
                return new ValidationResult(false, "Price must be a number.");
            }
        }
    }
}

<|start_filename|>Speech and Media/MediaGallery/MediaTimelineExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace MediaGallery
{
    public partial class MediaTimelineExample : INotifyPropertyChanged
    {
        private DispatcherTimer _timer;

        public MediaTimelineExample()
        {
            InitializeComponent();
        }

        public double MyProp
        {
            get { return ClickedBSB.Storyboard.GetCurrentTime(DocumentRoot).Value.TotalSeconds; }

            set
            {
                ClickedBSB.Storyboard.SeekAlignedToLastTick(DocumentRoot,
                    new TimeSpan((long) Math.Floor(value*TimeSpan.TicksPerSecond)), TimeSeekOrigin.BeginTime);
                OnPropertyChanged("MyProp");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnWindowLoaded(object sender, RoutedEventArgs e)
        {
            var b2 = new Binding
            {
                Source = this,
                Path = new PropertyPath("MyProp")
            };

            // Bind to the slider and the textbox
            BindingOperations.SetBinding(ClockSlider, RangeBase.ValueProperty, b2);
            BindingOperations.SetBinding(PositionTextBox, TextBox.TextProperty, b2);

            _timer = new DispatcherTimer {Interval = new TimeSpan(0, 0, 0, 0, 100)};

            // Every tick, the timer_Tick event handler is fired.
            _timer.Tick += timer_Tick;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            OnPropertyChanged("MyProp");
        }

        private void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public void OnMediaOpened(object sender, RoutedEventArgs e)
        {
            if (MediaElement1.Clock != null)
            {
                StatusBar.Text = MediaElement1.Clock.NaturalDuration.ToString();
                ClockSlider.Maximum = MediaElement1.Clock.NaturalDuration.TimeSpan.TotalSeconds + 10;
            }
            _timer.Start();
        }


        public object Convert(object o, Type type, object param, CultureInfo cul)
        {
            var currPosition = (TimeSpan) o;
            double numMSecs = currPosition.Milliseconds;

            var newValue = (numMSecs/MediaElement1.Clock.NaturalDuration.TimeSpan.TotalMilliseconds)*ClockSlider.Maximum;
            return newValue;
        }

        public object ConvertBack(object o, Type type, object param, CultureInfo cul) => null;
    }
}

<|start_filename|>Migration and Interoperability/WPFHostingWin32Control/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;

namespace WPFHostingWin32Control
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        internal const int
            LbnSelchange = 0x00000001,
            WmCommand = 0x00000111,
            LbGetcursel = 0x00000188,
            LbGettextlen = 0x0000018A,
            LbAddstring = 0x00000180,
            LbGettext = 0x00000189,
            LbDeletestring = 0x00000182,
            LbGetcount = 0x0000018B;

        private Application _app;
        private IntPtr _hwndListBox;
        private int _itemCount;
        private ControlHost _listControl;
        private Window _myWindow;
        private int _selectedItem;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void On_UIReady(object sender, EventArgs e)
        {
            _app = Application.Current;
            _myWindow = _app.MainWindow;
            _myWindow.SizeToContent = SizeToContent.WidthAndHeight;
            _listControl = new ControlHost(ControlHostElement.ActualHeight, ControlHostElement.ActualWidth);
            ControlHostElement.Child = _listControl;
            _listControl.MessageHook += ControlMsgFilter;
            _hwndListBox = _listControl.HwndListBox;
            for (var i = 0; i < 15; i++) //populate listbox
            {
                var itemText = "Item" + i;
                SendMessage(_hwndListBox, LbAddstring, IntPtr.Zero, itemText);
            }
            _itemCount = SendMessage(_hwndListBox, LbGetcount, IntPtr.Zero, IntPtr.Zero);
            numItems.Text = "" + _itemCount;
        }

        private void AppendText(object sender, EventArgs args)
        {
            if (txtAppend.Text != string.Empty)
            {
                SendMessage(_hwndListBox, LbAddstring, IntPtr.Zero, txtAppend.Text);
            }
            _itemCount = SendMessage(_hwndListBox, LbGetcount, IntPtr.Zero, IntPtr.Zero);
            numItems.Text = "" + _itemCount;
        }

        private void DeleteText(object sender, EventArgs args)
        {
            _selectedItem = SendMessage(_listControl.HwndListBox, LbGetcursel, IntPtr.Zero, IntPtr.Zero);
            if (_selectedItem != -1) //check for selected item
            {
                SendMessage(_hwndListBox, LbDeletestring, (IntPtr) _selectedItem, IntPtr.Zero);
            }
            _itemCount = SendMessage(_hwndListBox, LbGetcount, IntPtr.Zero, IntPtr.Zero);
            numItems.Text = "" + _itemCount;
        }

        private IntPtr ControlMsgFilter(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            int textLength;

            handled = false;
            if (msg == WmCommand)
            {
                switch ((uint) wParam.ToInt32() >> 16 & 0xFFFF) //extract the HIWORD
                {
                    case LbnSelchange: //Get the item text and display it
                        _selectedItem = SendMessage(_listControl.HwndListBox, LbGetcursel, IntPtr.Zero, IntPtr.Zero);
                        textLength = SendMessage(_listControl.HwndListBox, LbGettextlen, IntPtr.Zero, IntPtr.Zero);
                        var itemText = new StringBuilder();
                        SendMessage(_hwndListBox, LbGettext, _selectedItem, itemText);
                        selectedText.Text = itemText.ToString();
                        handled = true;
                        break;
                }
            }
            return IntPtr.Zero;
        }

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]
        internal static extern int SendMessage(IntPtr hwnd,
            int msg,
            IntPtr wParam,
            IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]
        internal static extern int SendMessage(IntPtr hwnd,
            int msg,
            int wParam,
            [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(IntPtr hwnd,
            int msg,
            IntPtr wParam,
            string lParam);
    }
}

<|start_filename|>Graphics/Brushes/PointToStringConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace Brushes
{
    [ValueConversion(typeof (Point), typeof (string))]
    public class PointToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var p = (Point) value;
            return p.X.ToString("F4") + "," + p.Y.ToString("F4");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                return Point.Parse((string) value);
            }
            catch (InvalidOperationException)
            {
                return null;
            }
        }
    }
}

<|start_filename|>Windows/Wizard/WizardLauncher.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Navigation;

namespace Wizard
{
    public class WizardLauncher : PageFunction<WizardResult>
    {
        private readonly WizardData _wizardData = new WizardData();
        public event WizardReturnEventHandler WizardReturn;

        protected override void Start()
        {
            base.Start();

            // So we remember the WizardCompleted event registration
            KeepAlive = true;

            // Launch the wizard
            var wizardPage1 = new WizardPage1(_wizardData);
            wizardPage1.Return += wizardPage_Return;
            NavigationService?.Navigate(wizardPage1);
        }

        public void wizardPage_Return(object sender, ReturnEventArgs<WizardResult> e)
        {
            // Notify client that wizard has completed
            // NOTE: We need this custom event because the Return event cannot be
            // registered by window code - if WizardDialogBox registers an event handler with
            // the WizardLauncher's Return event, the event is not raised.
            WizardReturn?.Invoke(this, new WizardReturnEventArgs(e.Result, _wizardData));
            OnReturn(null);
        }
    }
}

<|start_filename|>Graphics/Brushes/InteractiveLinearGradientBrushExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Brushes
{
    /// <summary>
    ///     Enables the user to configure a LinearGradientBrush interactively.
    /// </summary>
    public partial class InteractiveLinearGradientBrushExample : Page
    {
        public static readonly DependencyProperty SelectedMarkerProperty =
            DependencyProperty.Register
                ("SelectedMarker", typeof (Shape), typeof (InteractiveLinearGradientBrushExample),
                    new PropertyMetadata(null));

        public InteractiveLinearGradientBrushExample()
        {
            InitializeComponent();
        }

        private void OnPageLoaded(object sender, RoutedEventArgs s)
        {
            MappingModeComboBox.SelectionChanged += MappingModeChanged;
            OnStartPointTextBoxKeyUp(StartPointTextBox, null);
            OnEndPointTextBoxKeyUp(EndPointTextBox, null);
        }

        // Update the StartPoint and EndPoint markers when the gradient display
        // element's size changes.
        private void GradientDisplaySizeChanged(object sender, SizeChangedEventArgs e)
        {
            // The marker positions only need recalcutated if the brush's MappingMode
            // is RelativeToBoundingBox.
            if (InteractiveLinearGradientBrush.MappingMode ==
                BrushMappingMode.RelativeToBoundingBox)
            {
                StartPointMarkerTranslateTransform.X =
                    InteractiveLinearGradientBrush.StartPoint.X*e.NewSize.Width;
                StartPointMarkerTranslateTransform.Y =
                    InteractiveLinearGradientBrush.StartPoint.Y*e.NewSize.Height;

                EndPointMarkerTranslateTransform.X =
                    InteractiveLinearGradientBrush.EndPoint.X*e.NewSize.Width;
                EndPointMarkerTranslateTransform.Y =
                    InteractiveLinearGradientBrush.EndPoint.Y*e.NewSize.Height;
            }
        }

        private void OnStartPointTextBoxKeyUp(object sender, KeyEventArgs args)
        {
            var t = (TextBox) sender;
            try
            {
                var p = Point.Parse(t.Text);
                if (InteractiveLinearGradientBrush.MappingMode == BrushMappingMode.RelativeToBoundingBox)
                {
                    StartPointMarkerTranslateTransform.X = p.X*GradientDisplayElement.ActualWidth;
                    StartPointMarkerTranslateTransform.Y = p.Y*GradientDisplayElement.ActualHeight;
                }
                else
                {
                    StartPointMarkerTranslateTransform.X = p.X;
                    StartPointMarkerTranslateTransform.Y = p.Y;
                }
            }
            catch (InvalidOperationException)
            {
                // Ignore errors.
            }
            catch (FormatException)
            {
                // Ignore errors.
            }
        }

        private void OnEndPointTextBoxKeyUp(object sender, KeyEventArgs args)
        {
            var t = (TextBox) sender;
            try
            {
                var p = Point.Parse(t.Text);
                if (InteractiveLinearGradientBrush.MappingMode == BrushMappingMode.RelativeToBoundingBox)
                {
                    EndPointMarkerTranslateTransform.X = p.X*GradientDisplayElement.ActualWidth;
                    EndPointMarkerTranslateTransform.Y = p.Y*GradientDisplayElement.ActualHeight;
                }
                else
                {
                    EndPointMarkerTranslateTransform.X = p.X;
                    EndPointMarkerTranslateTransform.Y = p.Y;
                }
            }
            catch (InvalidOperationException)
            {
                // Ignore errors.
            }
            catch (FormatException)
            {
                // Ignore errors.
            }
        }

        // Determine whether the user clicked a marker.
        private void GradientDisplayMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.OriginalSource is Shape)
            {
                SetValue(SelectedMarkerProperty, (Shape) e.OriginalSource);
            }
            else
                SetValue(SelectedMarkerProperty, null);
        }

        // Determines whether the user just finished dragging a marker. If so,
        // this method updates the brush's StartPoint or EndPoint property,
        // depending on which marker was dragged. 
        private void GradientDisplayMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var clickPoint = e.GetPosition(GradientDisplayElement);
            var s = (Shape) GetValue(SelectedMarkerProperty);
            if (s == EndPointMarker || s == StartPointMarker)
            {
                var translation = (TranslateTransform) s.RenderTransform;
                translation.X = clickPoint.X;
                translation.Y = clickPoint.Y;
                SetValue(SelectedMarkerProperty, null);
                Mouse.Synchronize();

                Point p;
                if (InteractiveLinearGradientBrush.MappingMode == BrushMappingMode.RelativeToBoundingBox)
                {
                    p = new Point(clickPoint.X/GradientDisplayElement.ActualWidth,
                        clickPoint.Y/GradientDisplayElement.ActualHeight);
                }
                else
                {
                    p = clickPoint;
                }

                if (s == StartPointMarker)
                {
                    InteractiveLinearGradientBrush.StartPoint = p;
                    StartPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
                }
                else
                {
                    InteractiveLinearGradientBrush.EndPoint = p;
                    EndPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
                }
            }
        }

        // Update the StartPoint or EndPoint when the user drags one of the
        // points with the mouse. 
        private void GradientDisplayMouseMove(object sender, MouseEventArgs e)
        {
            var currentPoint = e.GetPosition(GradientDisplayElement);
            var s = (Shape) GetValue(SelectedMarkerProperty);

            // Determine whether the user dragged a StartPoint or
            // EndPoint marker.
            if (s == EndPointMarker || s == StartPointMarker)
            {
                // Move the selected marker to the current mouse position.
                var translation = (TranslateTransform) s.RenderTransform;
                translation.X = currentPoint.X;
                translation.Y = currentPoint.Y;
                Mouse.Synchronize();

                Point p;

                // Calculate the StartPoint or EndPoint.
                if (InteractiveLinearGradientBrush.MappingMode ==
                    BrushMappingMode.RelativeToBoundingBox)
                {
                    // If the MappingMode is relative, compute the relative
                    // value of the new point.
                    p = new Point(currentPoint.X/GradientDisplayElement.ActualWidth,
                        currentPoint.Y/GradientDisplayElement.ActualHeight);
                }
                else
                {
                    // If the MappingMode is absolute, there's no more
                    // work to do.
                    p = currentPoint;
                }

                if (s == StartPointMarker)
                {
                    // If the selected marker is the StartPoint marker,
                    // update the brush's StartPoint.
                    InteractiveLinearGradientBrush.StartPoint = p;
                    StartPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
                }
                else
                {
                    // Otherwise, update the brush's EndPoint.
                    InteractiveLinearGradientBrush.EndPoint = p;
                    EndPointTextBox.Text = p.X.ToString("F4") + "," + p.Y.ToString("F4");
                }
            }
        }

        // Updates the StartPoint and EndPoint and their markers when
        // the user changes the brush's MappingMode.
        private void MappingModeChanged(object sender, SelectionChangedEventArgs e)
        {
            var oldStartPoint = InteractiveLinearGradientBrush.StartPoint;
            var newStartPoint = new Point();
            var oldEndPoint = InteractiveLinearGradientBrush.EndPoint;
            var newEndPoint = new Point();


            if (InteractiveLinearGradientBrush.MappingMode ==
                BrushMappingMode.RelativeToBoundingBox)
            {
                // The MappingMode changed from absolute to relative.
                // To find the new relative point, divide the old absolute points
                // by the painted area's width and height. 
                newStartPoint.X = oldStartPoint.X/GradientDisplayElement.ActualWidth;
                newStartPoint.Y = oldStartPoint.Y/GradientDisplayElement.ActualHeight;
                InteractiveLinearGradientBrush.StartPoint = newStartPoint;

                newEndPoint.X = oldEndPoint.X/GradientDisplayElement.ActualWidth;
                newEndPoint.Y = oldEndPoint.Y/GradientDisplayElement.ActualHeight;
                InteractiveLinearGradientBrush.EndPoint = newEndPoint;
            }
            else
            {
                // The MappingMode changed from relative to absolute.
                // To find the new absolute point, multiply the old relative points
                // by the painted area's width and height. 
                newStartPoint.X = oldStartPoint.X*GradientDisplayElement.ActualWidth;
                newStartPoint.Y = oldStartPoint.Y*GradientDisplayElement.ActualHeight;
                InteractiveLinearGradientBrush.StartPoint = newStartPoint;

                newEndPoint.X = oldEndPoint.X*GradientDisplayElement.ActualWidth;
                newEndPoint.Y = oldEndPoint.Y*GradientDisplayElement.ActualHeight;

                InteractiveLinearGradientBrush.EndPoint = newEndPoint;
            }

            // Update the StartPoint and EndPoint display text.
            StartPointTextBox.Text = newStartPoint.X.ToString("F4") +
                                     "," + newStartPoint.Y.ToString("F4");
            EndPointTextBox.Text = newEndPoint.X.ToString("F4") +
                                   "," + newEndPoint.Y.ToString("F4");
        }

        // Update the markup display whenever the brush changes.
        private void OnInteractiveLinearGradientBrushChanged(object sender, EventArgs e)
        {
            if (GradientDisplayElement != null)
            {
                markupOutputTextBlock.Text =
                    GenerateLinearGradientBrushMarkup(InteractiveLinearGradientBrush);
            }
        }

        // Helper method that displays the markup of interest for
        // creating the specified brush.
        private static string GenerateLinearGradientBrushMarkup(LinearGradientBrush theBrush)
        {
            var sBuilder = new StringBuilder();
            sBuilder.Append("<" + theBrush.GetType().Name + "\n" +
                            "  StartPoint=\"" + theBrush.StartPoint + "\"" +
                            "  EndPoint=\"" + theBrush.EndPoint + "\" \n" +
                            "  MappingMode=\"" + theBrush.MappingMode + "\"" +
                            "  SpreadMethod=\"" + theBrush.SpreadMethod + "\"\n" +
                            "  ColorInterpolationMode=\"" + theBrush.ColorInterpolationMode + "\"" +
                            "  Opacity=\"" + theBrush.Opacity.ToString(CultureInfo.InvariantCulture) + "\"" + ">\n");

            foreach (var stop in theBrush.GradientStops)
            {
                sBuilder.Append
                    (
                        "  <GradientStop Offset=\"" + stop.Offset.ToString("F4")
                        + "\" Color=\"" + stop.Color + "\" />\n"
                    );
            }
            sBuilder.Append("</LinearGradientBrush>");
            return sBuilder.ToString();
        }
    }
}

<|start_filename|>Visual Layer/VisualsHitTesting/Form1.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Forms;

namespace SDKSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void AddChildToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyWindow.CreateShape(Handle);
        }

        private void FillWithCirclesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyWindow.FillWithCircles(Handle);
        }

        private void SmallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyShape.Radius = 30.0d;
            SmallToolStripMenuItem.Checked = true;
            MediumToolStripMenuItem.Checked = false;
            LargeToolStripMenuItem.Checked = false;
            RandomToolStripMenuItem.Checked = false;
        }

        private void MediumToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyShape.Radius = 50.0d;
            SmallToolStripMenuItem.Checked = false;
            MediumToolStripMenuItem.Checked = true;
            LargeToolStripMenuItem.Checked = false;
            RandomToolStripMenuItem.Checked = false;
        }

        private void LargeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyShape.Radius = 100.0d;
            SmallToolStripMenuItem.Checked = false;
            MediumToolStripMenuItem.Checked = false;
            LargeToolStripMenuItem.Checked = true;
            RandomToolStripMenuItem.Checked = false;
        }

        private void RandomToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyShape.Radius = 0.0d;
            SmallToolStripMenuItem.Checked = false;
            MediumToolStripMenuItem.Checked = false;
            LargeToolStripMenuItem.Checked = false;
            RandomToolStripMenuItem.Checked = true;
        }

        private void ThreeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyShape.NumberCircles = 3;
            ThreeToolStripMenuItem.Checked = true;
            FiveToolStripMenuItem.Checked = false;
            EightToolStripMenuItem.Checked = false;
        }

        private void FiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyShape.NumberCircles = 5;
            ThreeToolStripMenuItem.Checked = false;
            FiveToolStripMenuItem.Checked = true;
            EightToolStripMenuItem.Checked = false;
        }

        private void EightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyShape.NumberCircles = 8;
            ThreeToolStripMenuItem.Checked = false;
            FiveToolStripMenuItem.Checked = false;
            EightToolStripMenuItem.Checked = true;
        }

        private void TopmostLayerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyWindow.TopmostLayer = true;
            TopmostLayerToolStripMenuItem.Checked = true;
            AllLayersToolStripMenuItem.Checked = false;
        }

        private void AllLayersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MyWindow.TopmostLayer = false;
            AllLayersToolStripMenuItem.Checked = true;
            TopmostLayerToolStripMenuItem.Checked = false;
        }
    }
}

<|start_filename|>Properties/CustomClassesWithDP/Shirt.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace CustomClassesWithDP
{
    public class Shirt : Canvas
    {
        public static readonly DependencyProperty ShirtColorProperty = DependencyProperty.Register("ShirtColor",
            typeof (ShirtColors), typeof (Shirt), new FrameworkPropertyMetadata(ShirtColors.None));

        public static readonly DependencyProperty ShirtTypeProperty = DependencyProperty.Register(
            "ShirtType",
            typeof (ShirtTypes),
            typeof (Shirt),
            new FrameworkPropertyMetadata(
                ShirtTypes.None,
                OnShirtTypeChangedCallback
                ), ShirtValidateCallback);

        public static readonly DependencyProperty ButtonColorProperty = DependencyProperty.Register(
            "ButtonColor",
            typeof (ButtonColors),
            typeof (Shirt),
            new FrameworkPropertyMetadata(
                ButtonColors.Black,
                OnButtonColorChangedCallback,
                CoerceButtonColor)
            );

        public static readonly RoutedEvent ButtonColorChangedEvent =
            EventManager.RegisterRoutedEvent("ButtonColorChanged", RoutingStrategy.Bubble,
                typeof (DependencyPropertyChangedEventHandler), typeof (Shirt));

        public ShirtColors ShirtColor
        {
            get { return (ShirtColors) GetValue(ShirtColorProperty); }
            set { SetValue(ShirtColorProperty, value); }
        }

        public ShirtTypes ShirtType
        {
            get { return (ShirtTypes) GetValue(ShirtTypeProperty); }
            set { SetValue(ShirtTypeProperty, value); }
        }

        public ButtonColors ButtonColor
        {
            get { return (ButtonColors) GetValue(ButtonColorProperty); }
            set { SetValue(ButtonColorProperty, value); }
        }

        private static bool ShirtValidateCallback(object value)
        {
            var sh = (ShirtTypes) value;
            return (sh == ShirtTypes.None || sh == ShirtTypes.Bowling || sh == ShirtTypes.Dress ||
                    sh == ShirtTypes.Rugby || sh == ShirtTypes.Tee);
        }

        private static void OnShirtTypeChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            d.CoerceValue(ButtonColorProperty);
        }

        private static void OnButtonColorChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var newargs = new RoutedEventArgs(ButtonColorChangedEvent);
            (d as FrameworkElement).RaiseEvent(newargs);
        }

        private static object CoerceButtonColor(DependencyObject d, object value)
        {
            var newShirtType = (d as Shirt).ShirtType;
            if (newShirtType == ShirtTypes.Dress || newShirtType == ShirtTypes.Bowling)
            {
                return ButtonColors.Black;
            }
            return ButtonColors.None;
        }

        public event RoutedEventHandler ButtonColorChanged
        {
            add { AddHandler(ButtonColorChangedEvent, value); }
            remove { RemoveHandler(ButtonColorChangedEvent, value); }
        }
    }
}

<|start_filename|>Graphics/ShapesGallery/app.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace ShapesGallery
{
    public class App : Application
    {
        private Border _myBorder;
        private ColumnDefinition _myColDef1;
        private ColumnDefinition _myColDef2;
        private Ellipse _myEllipse;
        private Grid _myGrid;
        private Line _myLine;
        private Path _myPath;
        private Polygon _myPolygon;
        private Polyline _myPolyline;
        private Rectangle _myRect;
        private RowDefinition _myRowDef;
        private RowDefinition _myRowDef1;
        private RowDefinition _myRowDef2;
        private RowDefinition _myRowDef3;
        private RowDefinition _myRowDef4;
        private RowDefinition _myRowDef5;
        private RowDefinition _myRowDef6;
        private TextBlock _myTextBlock;
        private Window _myWindow;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            CreateAndShowMainWindow();
        }

        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _myWindow = new Window();

            // Add a Border
            _myBorder = new Border
            {
                BorderBrush = Brushes.Black,
                BorderThickness = new Thickness(2),
                Width = 400,
                Height = 600,
                Padding = new Thickness(15),
                Background = Brushes.White
            };

            // Create a Grid to host the Shapes
            _myGrid = new Grid {Margin = new Thickness(15)};
            _myColDef1 = new ColumnDefinition {Width = new GridLength(125)};
            _myColDef2 = new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)};
            _myGrid.ColumnDefinitions.Add(_myColDef1);
            _myGrid.ColumnDefinitions.Add(_myColDef2);
            _myRowDef = new RowDefinition();
            _myRowDef1 = new RowDefinition();
            _myRowDef2 = new RowDefinition();
            _myRowDef3 = new RowDefinition();
            _myRowDef4 = new RowDefinition();
            _myRowDef5 = new RowDefinition();
            _myRowDef6 = new RowDefinition();
            _myGrid.RowDefinitions.Add(_myRowDef);
            _myGrid.RowDefinitions.Add(_myRowDef1);
            _myGrid.RowDefinitions.Add(_myRowDef2);
            _myGrid.RowDefinitions.Add(_myRowDef3);
            _myGrid.RowDefinitions.Add(_myRowDef4);
            _myGrid.RowDefinitions.Add(_myRowDef5);
            _myGrid.RowDefinitions.Add(_myRowDef6);
            _myTextBlock = new TextBlock
            {
                FontSize = 20,
                Text = "WPF Shapes Gallery",
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center
            };
            _myGrid.Children.Add(_myTextBlock);
            Grid.SetRow(_myTextBlock, 0);
            Grid.SetColumnSpan(_myTextBlock, 2);


            // Add a Rectangle Element
            _myRect = new Rectangle
            {
                Stroke = Brushes.Black,
                Fill = Brushes.SkyBlue,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center,
                Height = 50,
                Width = 50
            };
            _myGrid.Children.Add(_myRect);
            Grid.SetRow(_myRect, 1);
            Grid.SetColumn(_myRect, 0);
            var myTextBlock1 = new TextBlock
            {
                FontSize = 14,
                Text = "A Rectangle Element",
                VerticalAlignment = VerticalAlignment.Center
            };
            _myGrid.Children.Add(myTextBlock1);
            Grid.SetRow(myTextBlock1, 1);
            Grid.SetColumn(myTextBlock1, 1);


            // Add an Ellipse Element
            _myEllipse = new Ellipse
            {
                Stroke = Brushes.Black,
                Fill = Brushes.DarkBlue,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center,
                Width = 50,
                Height = 75
            };
            _myGrid.Children.Add(_myEllipse);
            Grid.SetRow(_myEllipse, 2);
            Grid.SetColumn(_myEllipse, 0);
            var myTextBlock2 = new TextBlock
            {
                FontSize = 14,
                Text = "An Ellipse Element",
                VerticalAlignment = VerticalAlignment.Center
            };
            _myGrid.Children.Add(myTextBlock2);
            Grid.SetRow(myTextBlock2, 2);
            Grid.SetColumn(myTextBlock2, 1);


            // Add a Line Element
            _myLine = new Line
            {
                Stroke = Brushes.LightSteelBlue,
                X1 = 1,
                X2 = 50,
                Y1 = 1,
                Y2 = 50,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center,
                StrokeThickness = 2
            };
            _myGrid.Children.Add(_myLine);
            Grid.SetRow(_myLine, 3);
            Grid.SetColumn(_myLine, 0);
            var myTextBlock3 = new TextBlock
            {
                FontSize = 14,
                Text = "A Line Element",
                VerticalAlignment = VerticalAlignment.Center
            };
            _myGrid.Children.Add(myTextBlock3);
            Grid.SetRow(myTextBlock3, 3);
            Grid.SetColumn(myTextBlock3, 1);


            //Add the Path Element
            _myPath = new Path
            {
                Stroke = Brushes.Black,
                Fill = Brushes.MediumSlateBlue,
                StrokeThickness = 4,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center
            };
            var myEllipseGeometry = new EllipseGeometry
            {
                Center = new Point(50, 50),
                RadiusX = 25,
                RadiusY = 25
            };
            _myPath.Data = myEllipseGeometry;
            _myGrid.Children.Add(_myPath);
            Grid.SetRow(_myPath, 4);
            Grid.SetColumn(_myPath, 0);
            var myTextBlock4 = new TextBlock
            {
                FontSize = 14,
                Text = "A Path Element",
                VerticalAlignment = VerticalAlignment.Center
            };
            _myGrid.Children.Add(myTextBlock4);
            Grid.SetRow(myTextBlock4, 4);
            Grid.SetColumn(myTextBlock4, 1);


            //Add the Polygon Element
            _myPolygon = new Polygon
            {
                Stroke = Brushes.Black,
                Fill = Brushes.LightSeaGreen,
                StrokeThickness = 2,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Center
            };
            var point1 = new Point(1, 50);
            var point2 = new Point(10, 80);
            var point3 = new Point(50, 50);
            var myPointCollection = new PointCollection {point1, point2, point3};
            _myPolygon.Points = myPointCollection;
            _myGrid.Children.Add(_myPolygon);
            Grid.SetRow(_myPolygon, 5);
            Grid.SetColumn(_myPolygon, 0);
            var myTextBlock5 = new TextBlock
            {
                Text = "A Polygon Element",
                FontSize = 14,
                VerticalAlignment = VerticalAlignment.Center
            };
            _myGrid.Children.Add(myTextBlock5);
            Grid.SetRow(myTextBlock5, 5);
            Grid.SetColumn(myTextBlock5, 1);


            // Add the Polyline Element
            _myPolyline = new Polyline
            {
                Stroke = Brushes.SlateGray,
                StrokeThickness = 2,
                FillRule = FillRule.EvenOdd
            };
            var point4 = new Point(1, 50);
            var point5 = new Point(10, 80);
            var point6 = new Point(20, 40);
            var myPointCollection2 = new PointCollection {point4, point5, point6};
            _myPolyline.Points = myPointCollection2;
            _myGrid.Children.Add(_myPolyline);
            Grid.SetRow(_myPolyline, 6);
            Grid.SetColumn(_myPolyline, 0);
            var myTextBlock6 = new TextBlock
            {
                FontSize = 14,
                Text = "A Polyline Element",
                VerticalAlignment = VerticalAlignment.Center
            };
            _myGrid.Children.Add(myTextBlock6);
            Grid.SetRow(myTextBlock6, 6);
            Grid.SetColumn(myTextBlock6, 1);

            // Add the Grid to the Window as Content and show the Window
            _myBorder.Child = _myGrid;
            _myWindow.Content = _myBorder;
            _myWindow.Background = Brushes.LightSlateGray;
            _myWindow.Title = "Shapes Sample";
            _myWindow.Show();
        }
    }
}

<|start_filename|>Tools/LocBaml/InputBamlStreamList.cs<|end_filename|>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//---------------------------------------------------------------------------
//
// Description: InputBamlStreamList class
//              It enumerates all the baml streams in the input file for parsing
//
//---------------------------------------------------------------------------
using System;
using System.IO;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Resources;

namespace BamlLocalization
{
    /// <summary>
    /// Class that enumerates all the baml streams in the input file
    /// </summary>
    internal class InputBamlStreamList
    {
        /// <summary>
        /// constructor
        /// </summary>        
        internal InputBamlStreamList(LocBamlOptions options)
        {
            _bamlStreams  = new ArrayList();
            switch(options.InputType)
            {
                case FileType.BAML:
                {
                    _bamlStreams.Add(
                        new BamlStream(
                            Path.GetFileName(options.Input),
                            File.OpenRead(options.Input)
                            )
                    );
                    break;
                }
                case FileType.RESOURCES:
                {
                    using (ResourceReader resourceReader = new ResourceReader(options.Input))
                    {
                        // enumerate all bamls in a resources
                        EnumerateBamlInResources(resourceReader, options.Input);
                    }
                    break;
                }
		case FileType.EXE:
                case FileType.DLL:
                {
                    // for a dll, it is the same idea
                    Assembly assembly = Assembly.LoadFrom(options.Input);
                    foreach (string resourceName in assembly.GetManifestResourceNames())
                    {
                        ResourceLocation resourceLocation = assembly.GetManifestResourceInfo(resourceName).ResourceLocation;
                               
                        // if this resource is in another assemlby, we will skip it
                        if ((resourceLocation & ResourceLocation.ContainedInAnotherAssembly) != 0)
                        {
                            continue;   // in resource assembly, we don't have resource that is contained in another assembly
                        }
 
                        Stream resourceStream = assembly.GetManifestResourceStream(resourceName);
                        using (ResourceReader reader = new ResourceReader(resourceStream))
                        {
                            EnumerateBamlInResources(reader, resourceName);                              
                        }
                    }                    
                    break;
                }
                default:
                {
                    
                    Debug.Assert(false, "Not supported type");
                    break;
                }                    
            }                  
        }

        /// <summary>
        /// return the number of baml streams found
        /// </summary>
        internal int Count
        {
            get{return _bamlStreams.Count;}
        }

        /// <summary>
        /// Gets the baml stream in the input file through indexer
        /// </summary>        
        internal BamlStream this[int i]
        {
            get { return (BamlStream) _bamlStreams[i];}
        }

        /// <summary>
        /// Close the baml streams enumerated
        /// </summary>
        internal void Close()
        {
            for (int i = 0; i < _bamlStreams.Count; i++)
            {
               ((BamlStream) _bamlStreams[i]).Close();
            }            
        }

        //--------------------------------
        // private function
        //--------------------------------
        /// <summary>
        /// Enumerate baml streams in a resources file
        /// </summary>        
        private void EnumerateBamlInResources(ResourceReader reader, string resourceName)
        {                       
            foreach (DictionaryEntry entry in reader)
            {
                string name = entry.Key as string;
                if (BamlStream.IsResourceEntryBamlStream(name, entry.Value))
                {    
                    _bamlStreams.Add( 
                        new BamlStream(
                            BamlStream.CombineBamlStreamName(resourceName, name),
                            (Stream) entry.Value
                        )
                    );
                }    
            }
        }
        
        ArrayList    _bamlStreams;
    }

    /// <summary>
    /// BamlStream class which represents a baml stream
    /// </summary>
    internal class BamlStream
    {
        private string _name;
        private Stream _stream;

        /// <summary>
        /// constructor
        /// </summary>
        internal BamlStream(string name, Stream stream)
        {
            _name = name;
            _stream = stream;
        }
        
        /// <summary>
        /// name of the baml 
        /// </summary>
        internal string Name 
        { 
            get { return _name;}
        }

        /// <summary>
        /// The actual Baml stream
        /// </summary>
        internal Stream Stream
        {
            get { return _stream;}
        }

        /// <summary>
        /// close the stream
        /// </summary>
        internal void Close()
        {
            if (_stream != null)
            {
                _stream.Close();
            }           
        }

        /// <summary>
        /// Helper method which determines whether a stream name and value pair indicates a baml stream
        /// </summary>
        internal static bool IsResourceEntryBamlStream(string name, object value)
        {             
            string extension = Path.GetExtension(name);
            if (string.Compare(
                    extension, 
                    "." + FileType.BAML.ToString(), 
                    true, 
                    CultureInfo.InvariantCulture
                    ) == 0
                )                            
            {
                   //it has .Baml at the end
                Type type = value.GetType();

                if (typeof(Stream).IsAssignableFrom(type))
                return true;
            }            
            return false;                
        }

        /// <summary>
        /// Combine baml stream name and resource name to uniquely identify a baml within a 
        /// localization project
        /// </summary>
        internal static string CombineBamlStreamName(string resource, string bamlName)
        {
            Debug.Assert(resource != null && bamlName != null, "Resource name and baml name can't be null");

            string suffix = Path.GetFileName(bamlName);
            string prefix = Path.GetFileName(resource);

            return prefix + LocBamlConst.BamlAndResourceSeperator + suffix;
        }
    }
}


<|start_filename|>Input and Commands/EventOnGainAndLooseFocus/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace EventOnGainAndLooseFocus
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnGotFocusHandler(object sender, RoutedEventArgs e)
        {
            var tb = e.Source as Button;
            tb.Background = Brushes.Red;
        }

        // Raised when Button losses focus. 
        // Changes the color of the Button back to white.
        private void OnLostFocusHandler(object sender, RoutedEventArgs e)
        {
            var tb = e.Source as Button;
            tb.Background = Brushes.White;
        }
    }
}

<|start_filename|>Sample Applications/LayoutTransitionsDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;

namespace LayoutTransitionsDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly int _numItems = 8;
        private int _counter;
        private int _gridSize = 5;
        public ArrayList Buttons = new ArrayList();
        public ArrayList Hosts = new ArrayList();
        public ArrayList Panels = new ArrayList();
        public ArrayList Targets = new ArrayList();

        private void OnLoad(object sender, RoutedEventArgs e)
        {
            var app = Application.Current;

            Panels.Add(LTLGrid);
            Panels.Add(LTLGrid2);
            Panels.Add(LTLStackPanel);
            Panels.Add(LTLWrapPanel);

            Debug.WriteLine("Grid children: " + ButtonGrid.Children.Count);

            for (var i = 0; i < _numItems; i++)
            {
                var target = new LayoutToLayoutTarget();
                Targets.Add(target);
                target.Margin = new Thickness(5);
                target.MinWidth = 80;
                target.MinHeight = 50;
                target.BorderThickness = new Thickness(0);

                Grid.SetRow(target, i/5);
                Grid.SetColumn(target, i%5);
                LTLGrid.Children.Add(target);

                var host = new LayoutToLayoutHost();
                Hosts.Add(host);
                host.BorderThickness = new Thickness(0);

                var demoButton = new Button {Content = "# " + i};
                demoButton.Click += OnAdvanceClick;
                host.Child = demoButton;
                //host.Child = Buttons[i] as Button;

                Canvas.SetLeft(host, 0);
                Canvas.SetTop(host, 0);
                LTLCanvas.Children.Add(host);

                host.BindToTarget(target);
            }
        }

        /*
         * Increase the starting location in the grid by one
         * */

        private void OnAdvanceClick(object sender, RoutedEventArgs e)
        {
            _counter++;

            for (var i = 0; i < Hosts.Count; i++)
                MoveObject(Hosts[i] as LayoutToLayoutHost, _counter + i);
        }

        /*
         * Decrease the starting location in the grid by one
         * */

        private void OnRetreatClick(object sender, RoutedEventArgs e)
        {
            _counter--;

            for (var i = 0; i < Hosts.Count; i++)
                MoveObject(Hosts[i] as LayoutToLayoutHost, _counter + i);
        }

        /*
         * Set the Stackpanel's orientation to vertical
         * */

        private void OnStackVertical(object sender, RoutedEventArgs e)
        {
            foreach (var host in Hosts)
                (host as LayoutToLayoutHost)?.BeginAnimating(false);

            LTLStackPanel.Orientation = Orientation.Vertical;
        }

        /*
         * Set the stackpanel's orientation to vertical
         * */

        private void OnStackHorizontal(object sender, RoutedEventArgs e)
        {
            foreach (var host in Hosts)
                (host as LayoutToLayoutHost)?.BeginAnimating(false);

            LTLStackPanel.Orientation = Orientation.Horizontal;
        }

        /*
         * Set the wrappanel's orientation to vertical
         * */

        private void OnWrapVertical(object sender, RoutedEventArgs e)
        {
            foreach (var t in Hosts)
                (t as LayoutToLayoutHost)?.BeginAnimating(false);

            LTLWrapPanel.Orientation = Orientation.Vertical;
        }

        /*
         * Set the wrappanel's orientation to vertical
         * */

        private void OnWrapHorizontal(object sender, RoutedEventArgs e)
        {
            foreach (var host in Hosts)
                (host as LayoutToLayoutHost)?.BeginAnimating(false);

            LTLWrapPanel.Orientation = Orientation.Horizontal;
        }

        /*
         * Move all buttons into the 5x5 grid
         * */

        private void OnGrid5(object sender, RoutedEventArgs e)
        {
            ClearPanels();
            _gridSize = 5;
            _counter = 0;

            for (var i = 0; i < _numItems; i++)
            {
                var target = Targets[i] as LayoutToLayoutTarget;
                (Hosts[i] as LayoutToLayoutHost)?.BeginAnimating(false);
                Grid.SetRow(target, i/5);
                Grid.SetColumn(target, i%5);
                LTLGrid.Children.Add(target);
            }
        }

        /*
         * Move all buttons into the 3x3 grid
         * */

        private void OnGrid3(object sender, RoutedEventArgs e)
        {
            ClearPanels();
            _gridSize = 3;
            _counter = 0;

            for (var i = 0; i < _numItems; i++)
            {
                var target = Targets[i] as LayoutToLayoutTarget;
                (Hosts[i] as LayoutToLayoutHost)?.BeginAnimating(false);
                Grid.SetRow(target, i/3);
                Grid.SetColumn(target, i%3);
                LTLGrid2.Children.Add(target);
            }
        }

        /*
         * Move all buttons into the stack panel
         * */

        private void OnStackPanel(object sender, RoutedEventArgs e)
        {
            ClearPanels();
            for (var i = 0; i < _numItems; i++)
            {
                var target = Targets[i] as LayoutToLayoutTarget;
                (Hosts[i] as LayoutToLayoutHost)?.BeginAnimating(false);
                LTLStackPanel.Children.Add(target);
            }
        }

        /*
         * Move all buttons into the wrap panel
         * */

        private void OnWrapPanel(object sender, RoutedEventArgs e)
        {
            ClearPanels();
            for (var i = 0; i < _numItems; i++)
            {
                var target = Targets[i] as LayoutToLayoutTarget;
                (Hosts[i] as LayoutToLayoutHost).BeginAnimating(false);
                LTLWrapPanel.Children.Add(target);
            }
        }

        /*
         * move an object from one grid cell to another
         * */

        private void MoveObject(LayoutToLayoutHost obj, int position)
        {
            var max = _gridSize*_gridSize - 1;
            if (position > max)
                position = max;
            if (position < 0)
                position = 0;

            obj.BeginAnimating(false);
            Grid.SetRow(obj.Target, position/_gridSize);
            Grid.SetColumn(obj.Target, position%_gridSize);
        }

        /*
         * Remove all elements from all panels
         * */

        private void ClearPanels()
        {
            foreach (var panel in Panels)
            {
                (panel as Panel)?.Children.Clear();
            }
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/DiagnosticWriter.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Text;
using System.Xaml;

namespace BamlTools
{
    public class DiagnosticWriter : XamlWriter, IXamlLineInfoConsumer
    {
        const string _nullString = "*null*";

        XamlSchemaContext _schemaContext;
        String _nodeText;
        String _indentedNodeText;
        int _indent;
        string _indentUnit = " . ";
        StringBuilder _stringbuilder;
        XamlWriter _wrappedWriter = null;

        IXamlLineInfoConsumer _wrappedWriterLineInfoConsumer = null;
        int _lineNumber;
        int _linePosition;
        bool _lineInfoIsNew;

        public DiagnosticWriter(XamlSchemaContext schemaContext)
        {
            _schemaContext = schemaContext;
            _nodeText = String.Empty;
            _indent = 0;

            _stringbuilder = null;
            _wrappedWriter = null;
            _wrappedWriterLineInfoConsumer = null;
        }

        public DiagnosticWriter(StringBuilder stringbuilder, XamlSchemaContext schemaContext)
            : this(schemaContext)
        {
            _stringbuilder = stringbuilder;
        }

        public DiagnosticWriter(StringBuilder stringbuilder, XamlWriter wrappedWriter, XamlSchemaContext xamlSchemaContext)
            : this(stringbuilder, xamlSchemaContext)
        {
            _wrappedWriter = wrappedWriter;
            _wrappedWriterLineInfoConsumer = _wrappedWriter as IXamlLineInfoConsumer;
        }

        public String IndentUnit
        {
            get { return _indentUnit; }
            set { _indentUnit = value; }
        }

        // ------ XamlWriter implementation  -------------

        public override XamlSchemaContext SchemaContext
        {
            get { return _schemaContext; }
        }

        public override void WriteNamespace(NamespaceDeclaration namespaceDeclaration)
        {
            CurrentNodeText = String.Format("NS prefix={0} Uri={1}", namespaceDeclaration.Prefix, namespaceDeclaration.Namespace);
            BuildString();

            if (_wrappedWriter != null)
            {
                _wrappedWriter.WriteNamespace(namespaceDeclaration);
            }
        }

        public override void WriteStartObject(XamlType type)
        {
            CurrentNodeText = String.Format("SO {0}", type.Name);
            BuildString();
            _indent += 1;

            if (_wrappedWriter != null)
            {
                _wrappedWriter.WriteStartObject(type);
            }
        }

        public override void WriteGetObject()
        {
            CurrentNodeText = "GO";
            BuildString();
            _indent += 1;

            if (_wrappedWriter != null)
            {
                _wrappedWriter.WriteGetObject();
            }
        }

        public override void WriteEndObject()
        {
            _indent -= 1;
            CurrentNodeText = "EO";
            BuildString();

            if (_wrappedWriter != null)
            {
                _wrappedWriter.WriteEndObject();
            }
        }

        public override void WriteStartMember(XamlMember xamlMember)
        {
            CurrentNodeText = String.Format("SM {0}", xamlMember.Name);
            BuildString();
            _indent += 1;

            if (_wrappedWriter != null)
            {
                _wrappedWriter.WriteStartMember(xamlMember);
            }
        }

        public override void WriteEndMember()
        {
            _indent -= 1;
            CurrentNodeText = "EM";
            BuildString();

            if (_wrappedWriter != null)
            {
                _wrappedWriter.WriteEndMember();
            }
        }

        public override void WriteValue(object value)
        {
            string valueString = value as string;
            if (value == null)  // null values
            {
                valueString = _nullString;
            }
            else if (valueString != null)  // string values
            {
                if (ShowLinebreaks)
                {
                    valueString = valueString.Replace("\n", "\\n");
                }
            }
            else  // Non-string Values
            {
                valueString = String.Format("({0}) [{1}]", value.ToString(), value.GetType().Name);
            }

            CurrentNodeText = String.Format("V '{0}'", valueString);
            BuildString();

            if (_wrappedWriter != null)
            {
                _wrappedWriter.WriteValue(value);
            }
        }

        // --------------------------

        protected override void Dispose(bool disposing)
        {
            try
            {
                if (disposing && !IsDisposed)
                {
                    CurrentNodeText = "Closed.";
                    BuildString();

                    if (_wrappedWriter != null)
                    {
                        _wrappedWriter.Close();
                    }
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        public object Result
        {
            get
            {
                XamlObjectWriter objectWriter = _wrappedWriter as XamlObjectWriter;
                if (objectWriter != null)
                {
                    return objectWriter.Result;
                }
                else
                {
                    return null;
                }
            }
        }

        #region IXamlLineInfoConsumer Members

        public void SetLineInfo(int lineNumber, int linePosition)
        {
            {
                _lineNumber = lineNumber;
                _linePosition = linePosition;
                _lineInfoIsNew = true;

                if (_wrappedWriterLineInfoConsumer != null && _wrappedWriterLineInfoConsumer.ShouldProvideLineInfo)
                {
                    _wrappedWriterLineInfoConsumer.SetLineInfo(lineNumber, linePosition);
                }
            }
        }

        public bool ShouldProvideLineInfo
        {
            get { return true; }
        }

        #endregion

        public string LineInfoString
        {
            get
            {
                if (_lineInfoIsNew)
                {
                    _lineInfoIsNew = false;
                    return String.Format("   ({0},{1})", _lineNumber, _linePosition);
                }
                return String.Empty;
            }
        }

        // -----------------------------

        public String CurrentNodeText
        {
            get { return _nodeText; }

            private set
            {
                _nodeText = value;
                if (_lineInfoIsNew)
                {
                    _nodeText += LineInfoString;
                }
            }
        }

        public int IndentLevel
        {
            get { return _indent; }
        }

        public String CurrentIndentedNodeText
        {
            get
            {
                return _indentedNodeText;
            }
        }

        public bool ShowLinebreaks { set; get; }

        private string CurrentIndentString
        {
            get
            {
                string indent = String.Empty;
                for (int i = 0; i < _indent; i += 1)
                {
                    indent += _indentUnit;
                }
                return indent;
            }
        }

        private void BuildString()
        {
            _indentedNodeText = CurrentIndentString + CurrentNodeText;
            if (_stringbuilder != null)
            {
                _stringbuilder.AppendLine(_indentedNodeText);
            }
        }

    }
}


<|start_filename|>Sample Applications/GeometryDesignerDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace GeometryDesignerDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnUiReady(object sender, EventArgs e)
        {
            LinePane.Width = ((StackPanel) LinePane.Parent).ActualWidth;
            LinePane.Height = ((StackPanel) LinePane.Parent).ActualHeight;
            DesignerPane.MouseLeave += DesignerPane_MouseLeave;
            SizeChanged += Window1_SizeChanged;
        }

        private void Window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            XAMLPane.BeginAnimation(Canvas.TopProperty, null);
            if (_isShow)
            {
                XAMLPane.SetValue(Canvas.TopProperty, e.NewSize.Height - 70);
            }
            else
            {
                XAMLPane.SetValue(Canvas.TopProperty, e.NewSize.Height);
            }
            XAMLPane.Width = e.NewSize.Width - 205;
        }

        private void OnShowHideXaml(object sender, RoutedEventArgs e)
        {
            var xamlstring = XamlWriter.Save(DrawingPane);
            ((TextBox) XAMLPane.Children[0]).Text = xamlstring;

            if (!_isShow)
            {
                _isShow = !_isShow;
                XAMLPane.Width = ActualWidth - 205;
                XAMLPane.Height = 50;
                var yLocation = DesignerPane.ActualHeight;
                XAMLPane.SetValue(Canvas.LeftProperty, DesignerPane.GetValue(Canvas.LeftProperty));
                XAMLPane.SetValue(Canvas.TopProperty, yLocation);
                ((Label) ((Button) sender).Content).Content = "Hide XAML";

                //Start animation
                var db = new DoubleAnimation
                {
                    Duration = TimeSpan.FromMilliseconds(500),
                    FillBehavior = FillBehavior.HoldEnd,
                    To = yLocation - 50
                };

                XAMLPane.BeginAnimation(Canvas.TopProperty, db);
            }
            else
            {
                _isShow = !_isShow;
                ((Label) ((Button) sender).Content).Content = "Show XAML";

                var dbShrink = new DoubleAnimation
                {
                    Duration = TimeSpan.FromMilliseconds(500),
                    FillBehavior = FillBehavior.HoldEnd,
                    To = DesignerPane.ActualHeight,
                    From = DesignerPane.ActualHeight - 50
                };

                XAMLPane.BeginAnimation(Canvas.TopProperty, dbShrink);
            }
        }

        private void OnGeometrySelectionChange(object sender, SelectionChangedEventArgs e)
        {
            var box = sender as ComboBox;

            if (box.Name != "GeometryTypeCB")
                return;

            if (_initialSelection)
            {
                _initialSelection = !_initialSelection;
            }
            else
            {
                GeometryPaneChange(((ComboBoxItem) box.SelectedItem).Content, true);
            }
        }

        public abstract class GeometryBase
        {
            protected GeometryBase(FrameworkElement pane)
            {
                ParentPane = pane;
            }

            public abstract void Parse();
            public abstract Geometry CreateGeometry();

            protected double DoubleParser(string s) => double.Parse(s);

            protected Point PointParser(string o)
            {
                try
                {
                    return Point.Parse(o);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    throw new ApplicationException(
                        "Error: please enter two numeric values separated  by a comma or a space; for example, 10,30.");
                }
            }

            protected Size SizeParser(string o)
            {
                var retval = new Size();

                var sizeString = o.Split(' ', ',', ';');
                if (sizeString.Length == 0 || sizeString.Length != 2)
                    throw new ApplicationException(
                        "Error: a size should contain two double that seperated by a space or ',' or ';'");

                try
                {
                    var d1 = Convert.ToDouble(sizeString[0], CultureInfo.InvariantCulture);
                    var d2 = Convert.ToDouble(sizeString[1], CultureInfo.InvariantCulture);
                    retval.Width = d1;
                    retval.Height = d2;
                }
                catch (Exception)
                {
                    throw new ApplicationException("Error: please enter only two numeric values into the field");
                }

                return retval;
            }

            #region Data member

            protected FrameworkElement ParentPane;
            public ArrayList ControlPoints;
            public string GeometryType;

            #endregion
        }

        public class LineG : GeometryBase
        {
            public LineG(FrameworkElement pane)
                : base(pane)
            {
                ControlPoints = new ArrayList();
                GeometryType = "Line";
                Parse();
            }

            public override void Parse()
            {
                var tbStartPoint = LogicalTreeHelper.FindLogicalNode(ParentPane, "LineStartPoint") as TextBox;
                var tbEndPoint = LogicalTreeHelper.FindLogicalNode(ParentPane, "LineEndPoint") as TextBox;

                _startPoint = PointParser(tbStartPoint.Text);
                _endPoint = PointParser(tbEndPoint.Text);

                ControlPoints.Add(_startPoint);
                ControlPoints.Add(_endPoint);
            }

            public override Geometry CreateGeometry()
            {
                var lg = new LineGeometry(_startPoint, _endPoint);
                return lg;
            }

            #region Data members

            private Point _startPoint;
            private Point _endPoint;

            #endregion
        }

        public class EllipseG : GeometryBase
        {
            public EllipseG(FrameworkElement pane) : base(pane)
            {
                ControlPoints = new ArrayList();
                GeometryType = "Ellipse";
                Parse();
            }

            public override void Parse()
            {
                var tbCenter = LogicalTreeHelper.FindLogicalNode(ParentPane, "EllipseCenterPoint") as TextBox;
                var tbRadiusx = LogicalTreeHelper.FindLogicalNode(ParentPane, "EllipseRadiusX") as TextBox;
                var tbRadiusy = LogicalTreeHelper.FindLogicalNode(ParentPane, "EllipseRadiusY") as TextBox;

                _center = PointParser(tbCenter.Text);
                _radiusx = DoubleParser(tbRadiusx.Text);
                _radiusy = DoubleParser(tbRadiusy.Text);

                //Center point
                ControlPoints.Add(_center);

                //TopLeft
                ControlPoints.Add(new Point(_center.X - _radiusx, _center.Y));

                //TopMiddle
                ControlPoints.Add(new Point(_center.X, _center.Y - _radiusy));

                //TopRight
                ControlPoints.Add(new Point(_center.X + _radiusx, _center.Y));

                //BottomMiddle
                ControlPoints.Add(new Point(_center.X, _center.Y + _radiusy));
            }

            public override Geometry CreateGeometry()
            {
                var retval = new EllipseGeometry(_center, _radiusx, _radiusy);
                return retval;
            }

            #region Data Members

            private Point _center;
            private double _radiusx;
            private double _radiusy;

            #endregion
        }

        public class RectanlgeG : GeometryBase
        {
            public RectanlgeG(FrameworkElement pane)
                : base(pane)
            {
                ControlPoints = new ArrayList();
                GeometryType = "Rectangle";
                Parse();
            }

            public override Geometry CreateGeometry()
            {
                var retval = new RectangleGeometry(new Rect(_topleft.X, _topleft.Y, _width, _height), _radiusx, _radiusy);

                return retval;
            }

            public override void Parse()
            {
                var tbTopleft = LogicalTreeHelper.FindLogicalNode(ParentPane, "RectangleTopLeftPoint") as TextBox;
                var tbRadiusx = LogicalTreeHelper.FindLogicalNode(ParentPane, "RectangleRadiusX") as TextBox;
                var tbRadiusy = LogicalTreeHelper.FindLogicalNode(ParentPane, "RectangleRadiusY") as TextBox;
                var tbWidth = LogicalTreeHelper.FindLogicalNode(ParentPane, "RectangleWidth") as TextBox;
                var tbHeight = LogicalTreeHelper.FindLogicalNode(ParentPane, "RectangleHeight") as TextBox;

                _topleft = PointParser(tbTopleft.Text);
                _radiusx = DoubleParser(tbRadiusx.Text);
                _radiusy = DoubleParser(tbRadiusy.Text);
                _width = DoubleParser(tbWidth.Text);
                _height = DoubleParser(tbHeight.Text);

                //TopLeft point
                ControlPoints.Add(_topleft);

                //TopRight
                ControlPoints.Add(new Point(_topleft.X + _width, _topleft.Y));

                //BottomLeft
                ControlPoints.Add(new Point(_topleft.X, _topleft.Y + _height));

                //BottomRight
                ControlPoints.Add(new Point(_topleft.X + _width, _topleft.Y + _height));

                if (_radiusx != 0 && _radiusy != 0)
                {
                    ControlPoints.Add(new Point(_topleft.X + _radiusx, _topleft.Y + _radiusy));
                }
            }

            #region Data Members

            private Point _topleft;
            private double _width;
            private double _height;
            private double _radiusx;
            private double _radiusy;

            #endregion
        }

        public class BezierG : GeometryBase
        {
            #region Data Members

            private Point _startpoint, _p1, _p2, _p3;

            #endregion

            public BezierG(FrameworkElement pane)
                : base(pane)
            {
                ControlPoints = new ArrayList();
                GeometryType = "Bezier";
                Parse();
            }

            public override Geometry CreateGeometry()
            {
                var retval = new PathGeometry();
                var pf = new PathFigure {StartPoint = _startpoint};
                pf.Segments.Add(new BezierSegment(_p1, _p2, _p3, true));
                retval.Figures.Add(pf);
                return retval;
            }

            public override void Parse()
            {
                var tbStartpoint = LogicalTreeHelper.FindLogicalNode(ParentPane, "BezierStartPoint") as TextBox;
                var tbPoint1 = LogicalTreeHelper.FindLogicalNode(ParentPane, "BezierPoint1") as TextBox;
                var tbPoint2 = LogicalTreeHelper.FindLogicalNode(ParentPane, "BezierPoint2") as TextBox;
                var tbPoint3 = LogicalTreeHelper.FindLogicalNode(ParentPane, "BezierPoint3") as TextBox;

                _startpoint = PointParser(tbStartpoint.Text);
                _p1 = PointParser(tbPoint1.Text);
                _p2 = PointParser(tbPoint2.Text);
                _p3 = PointParser(tbPoint3.Text);

                ControlPoints.Add(_startpoint);
                ControlPoints.Add(_p1);
                ControlPoints.Add(_p2);
                ControlPoints.Add(_p3);
            }
        }

        public class ArcG : GeometryBase
        {
            public ArcG(FrameworkElement pane)
                : base(pane)
            {
                ControlPoints = new ArrayList();
                GeometryType = "Arc";
                Parse();
            }

            public override Geometry CreateGeometry()
            {
                var retval = new PathGeometry();
                var pf = new PathFigure {StartPoint = _startpoint};
                pf.Segments.Add(new ArcSegment(_point, _size, _xrotation, _largearc, _sweepArcDirection, true));
                retval.Figures.Add(pf);
                return retval;
            }

            public override void Parse()
            {
                var tbStartpoint = LogicalTreeHelper.FindLogicalNode(ParentPane, "ArcStartPoint") as TextBox;
                var tbPoint = LogicalTreeHelper.FindLogicalNode(ParentPane, "ArcPoint") as TextBox;
                var tbSize = LogicalTreeHelper.FindLogicalNode(ParentPane, "ArcSize") as TextBox;
                var tbXrotation = LogicalTreeHelper.FindLogicalNode(ParentPane, "ArcXRotation") as TextBox;
                var cbSweeparc = LogicalTreeHelper.FindLogicalNode(ParentPane, "ArcSweepArc") as ComboBox;
                var cbLargearc = LogicalTreeHelper.FindLogicalNode(ParentPane, "ArcLargeArc") as ComboBox;

                _startpoint = PointParser(tbStartpoint.Text);
                _point = PointParser(tbPoint.Text);
                _size = SizeParser(tbSize.Text);
                _xrotation = DoubleParser(tbXrotation.Text);
                _sweepArcDirection = (SweepDirection) Enum.Parse(
                    typeof (SweepDirection),
                    (
                        (string)
                            (
                                (ComboBoxItem) cbSweeparc.SelectedItem
                                ).Content
                        )
                    );

                _largearc = bool.Parse(((string) ((ComboBoxItem) cbLargearc.SelectedItem).Content));
                ControlPoints.Add(_startpoint);
                ControlPoints.Add(_point);
            }

            #region Data Members

            private Point _startpoint, _point;
            private Size _size;
            private bool _largearc;
            private SweepDirection _sweepArcDirection;
            private double _xrotation;

            #endregion
        }

        // ---------------------------------------------------------------------------------

        #region private action functions

        private void GeometryPaneChange(object geometryName, bool allowInsert)
        {
            foreach (Canvas c in ControlPointPane.Children)
            {
                if (string.Compare(c.Name, (string) geometryName + "Pane", false, CultureInfo.InvariantCulture) == 0)
                {
                    c.Width = ((StackPanel) c.Parent).ActualWidth;
                    c.Height = ((StackPanel) c.Parent).ActualHeight;
                    if (allowInsert)
                    {
                        foreach (var b in c.Children)
                        {
                            if (b is TextBox)
                            {
                                ((TextBox) b).Text = "";
                                continue;
                            }

                            if ((b as Button)?.Content is string &&
                                ((string) ((Button) b).Content == "Insert" || (string) ((Button) b).Content == "Update"))
                            {
                                ((Button) b).IsEnabled = true;
                                ((Button) b).Content = "Insert";
                                _isInsert = true;
                            }
                        }
                    }
                    else
                    {
                        foreach (var b in c.Children)
                        {
                            if ((b as Button)?.Content is string && (string) ((Button) b).Content == "Insert")
                            {
                                ((Button) b).IsEnabled = false;
                            }
                        }
                    }
                }
                else
                {
                    c.Width = 0;
                    c.Height = 0;
                }
            }
        }


        //If mouse leaves the DesignerPane, hide all of the control points
        private void DesignerPane_MouseLeave(object sender, MouseEventArgs e)
        {
            foreach (var o in DesignerPane.Children)
            {
                if (o is Ellipse)
                {
                    ((Ellipse) o).Visibility = Visibility.Hidden;
                }
            }
        }


        private void path_MouseEnter(object sender, MouseEventArgs e)
        {
            var pathId = ((Path) sender).Name;

            //Search and set visibility on all of the related control points
            foreach (var o in DesignerPane.Children)
            {
                //Search for the control point that contains the element's ID
                //e.g Line1_StartPoint for Line1 element
                if (o is Ellipse)
                {
                    ((Ellipse) o).Visibility = ((Ellipse) o).Name.Contains(pathId)
                        ? Visibility.Visible
                        : Visibility.Hidden;
                }
            }
        }


        private void OnInsertGeometry(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_isInsert)
                {
                    var path = new Path
                    {
                        Stroke = Brushes.Black,
                        StrokeThickness = 2
                    };

                    var gb = GeometryFactory((FrameworkElement) ((Button) sender).Parent);


                    switch (gb.GeometryType)
                    {
                        case "Line":
                            path.Name = "Line" + _lineCount;
                            AddControlPoints(gb.ControlPoints, "Line");
                            _lineCount++;
                            break;
                        case "Rectangle":
                            path.Name = "Rectangle" + _rectangleCount;
                            AddControlPoints(gb.ControlPoints, "Rectangle");
                            _rectangleCount++;
                            break;
                        case "Ellipse":
                            path.Name = "Ellipse" + _elliipseCount;
                            AddControlPoints(gb.ControlPoints, "Ellipse");
                            _elliipseCount++;
                            break;
                        case "Arc":
                            path.Name = "Arc" + _arcCount;
                            AddControlPoints(gb.ControlPoints, "Arc");
                            _arcCount++;
                            break;
                        case "Bezier":
                            path.Name = "Bezier" + _bezierCount;
                            AddControlPoints(gb.ControlPoints, "Bezier");
                            _bezierCount++;
                            break;
                        default:
                            throw new ApplicationException("Error:  Incorrect Geometry type");
                    }

                    path.Data = gb.CreateGeometry();
                    path.MouseEnter += path_MouseEnter;
                    _currentElement = path;
                    DrawingPane.Children.Add(path);
                    ((Button) sender).Content = "Update";
                    _isInsert = !_isInsert;
                }
                else
                {
                    var gbUpdate = GeometryFactory((FrameworkElement) ((Button) sender).Parent);
                    _currentElement.Data = gbUpdate.CreateGeometry();
                    UpdateControlPoints(gbUpdate.ControlPoints);
                }
            }
            catch (ApplicationException argExcept)
            {
                MessageBox.Show(argExcept.Message);
            }
        }

        #endregion

        // ---------------------------------------------------------------------------------

        #region Drag and Move

        //Special variable for Drag and move actions
        private bool _isMoving;
        private Point _movingPreviousLocation;


        private void Ellipse_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var el = (Ellipse) sender;
            el.Cursor = Cursors.Hand;
            _isMoving = true;
            _movingPreviousLocation = e.GetPosition(DrawingPane);
        }

        private void Ellipse_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var el = (Ellipse) sender;
            el.Cursor = Cursors.Arrow;
            _isMoving = false;
        }


        private void Ellipse_MouseMove(object sender, MouseEventArgs e)
        {
            var el = (Ellipse) sender;
            Point movingEndLocation;
            if (_isMoving)
            {
                movingEndLocation = e.GetPosition(DrawingPane);


                Canvas.SetLeft(el, movingEndLocation.X - el.Width/2);
                Canvas.SetTop(el, movingEndLocation.Y - el.Height/2);

                UpdateGeometries(movingEndLocation, el.Name);
                _movingPreviousLocation = movingEndLocation;
            }
        }

        #endregion

        // ---------------------------------------------------------------------------------

        #region private helper functions

        private void UpdateControlPoints(ArrayList controlPoints)
        {
            var geometryType = GetGeometryTypeInId(_currentElement.Name);

            switch (geometryType)
            {
                case "Line":
                    UpdateLineGeometryControlPoints(controlPoints);
                    break;
                case "Ellipse":
                    UpdateEllipseGeometryControlPoints(controlPoints);
                    break;
                case "Rectangle":
                    UpdateRectangleGeometryControlPoints(controlPoints);
                    break;
                case "Arc":
                    UpdateArcGeometryControlPoints(controlPoints);
                    break;
                case "Bezier":
                    UpdateBezierGeometryControlPoints(controlPoints);
                    break;
                default:
                    throw new ApplicationException("Error: incorrect Element name");
            }
        }


        private void UpdateLineGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 2)
                throw new ApplicationException("Error:  incorrect # of control points for LineGeometry");

            for (var i = 0; i < controlPoints.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        var eStartPoint =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_StartPoint") as
                                Ellipse;
                        Canvas.SetLeft(eStartPoint, ((Point) controlPoints[i]).X - eStartPoint.Width/2);
                        Canvas.SetTop(eStartPoint, ((Point) controlPoints[i]).Y - eStartPoint.Height/2);
                        break;
                    case 1:
                        var eEndPoint =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_EndPoint") as
                                Ellipse;
                        Canvas.SetLeft(eEndPoint, ((Point) controlPoints[i]).X - eEndPoint.Width/2);
                        Canvas.SetTop(eEndPoint, ((Point) controlPoints[i]).Y - eEndPoint.Height/2);
                        break;
                    default:
                        throw new ApplicationException("Error: incorrect # of control points in LineG");
                }
            }
        }

        private void UpdateEllipseGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 5)
            {
                throw new ApplicationException("Error:  incorrect # of control points for EllipseGeometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        var eCenter =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_Center") as Ellipse;
                        Canvas.SetLeft(eCenter, ((Point) controlPoints[i]).X - eCenter.Width/2);
                        Canvas.SetTop(eCenter, ((Point) controlPoints[i]).Y - eCenter.Height/2);
                        break;
                    case 1:
                        var eTopLeft =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_TopLeft") as
                                Ellipse;
                        Canvas.SetLeft(eTopLeft, ((Point) controlPoints[i]).X - eTopLeft.Width/2);
                        Canvas.SetTop(eTopLeft, ((Point) controlPoints[i]).Y - eTopLeft.Height/2);
                        break;
                    case 2:
                        var eTopMiddle =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_TopMiddle") as
                                Ellipse;
                        Canvas.SetLeft(eTopMiddle, ((Point) controlPoints[i]).X - eTopMiddle.Width/2);
                        Canvas.SetTop(eTopMiddle, ((Point) controlPoints[i]).Y - eTopMiddle.Height/2);
                        break;
                    case 3:
                        var eTopRight =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_TopRight") as
                                Ellipse;
                        Canvas.SetLeft(eTopRight, ((Point) controlPoints[i]).X - eTopRight.Width/2);
                        Canvas.SetTop(eTopRight, ((Point) controlPoints[i]).Y - eTopRight.Height/2);
                        break;
                    case 4:
                        var eBottomMiddle =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_BottomMiddle") as
                                Ellipse;
                        Canvas.SetLeft(eBottomMiddle, ((Point) controlPoints[i]).X - eBottomMiddle.Width/2);
                        Canvas.SetTop(eBottomMiddle, ((Point) controlPoints[i]).Y - eBottomMiddle.Height/2);
                        break;
                    default:
                        throw new ApplicationException("Error: incorrect # of control points in EllipseG");
                }
            }
        }

        private void UpdateRectangleGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 5 && controlPoints.Count != 4)
            {
                throw new ApplicationException("Error:  incorrect # of control points for RectangleGeometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        var eTopLeft =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_TopLeft") as
                                Ellipse;
                        Canvas.SetLeft(eTopLeft, ((Point) controlPoints[i]).X - eTopLeft.Width/2);
                        Canvas.SetTop(eTopLeft, ((Point) controlPoints[i]).Y - eTopLeft.Height/2);
                        break;
                    case 1:
                        var eTopRight =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_TopRight") as
                                Ellipse;
                        Canvas.SetLeft(eTopRight, ((Point) controlPoints[i]).X - eTopRight.Width/2);
                        Canvas.SetTop(eTopRight, ((Point) controlPoints[i]).Y - eTopRight.Height/2);
                        break;
                    case 2:
                        var eBottomLeft =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_BottomLeft") as
                                Ellipse;
                        Canvas.SetLeft(eBottomLeft, ((Point) controlPoints[i]).X - eBottomLeft.Width/2);
                        Canvas.SetTop(eBottomLeft, ((Point) controlPoints[i]).Y - eBottomLeft.Height/2);
                        break;
                    case 3:
                        var eBottomRight =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_BottomRight") as
                                Ellipse;
                        Canvas.SetLeft(eBottomRight, ((Point) controlPoints[i]).X - eBottomRight.Width/2);
                        Canvas.SetTop(eBottomRight, ((Point) controlPoints[i]).Y - eBottomRight.Height/2);
                        break;
                    case 4:
                        var eCorner =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_Corner") as Ellipse;
                        Canvas.SetLeft(eCorner, ((Point) controlPoints[i]).X - eCorner.Width/2);
                        Canvas.SetTop(eCorner, ((Point) controlPoints[i]).Y - eCorner.Height/2);
                        break;
                    default:
                        throw new ApplicationException("Error: incorrect # of control points in RectangleG");
                }
            }
        }

        private void UpdateArcGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 2)
            {
                throw new ApplicationException("Error:  incorrect # of control points for Arc Geometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        var eStartPoint =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_StartPoint") as
                                Ellipse;
                        Canvas.SetLeft(eStartPoint, ((Point) controlPoints[i]).X - eStartPoint.Width/2);
                        Canvas.SetTop(eStartPoint, ((Point) controlPoints[i]).Y - eStartPoint.Height/2);
                        break;
                    case 1:
                        var ePoint1 =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_Point") as Ellipse;
                        Canvas.SetLeft(ePoint1, ((Point) controlPoints[i]).X - ePoint1.Width/2);
                        Canvas.SetTop(ePoint1, ((Point) controlPoints[i]).Y - ePoint1.Height/2);
                        break;
                    default:
                        throw new ApplicationException("Error: Incorrect # of control points in ArcG");
                }
            }
        }

        private void UpdateBezierGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 4)
            {
                throw new ApplicationException("Error:  incorrect # of control points for Bezier Geometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        var eStartPoint =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_StartPoint") as
                                Ellipse;
                        Canvas.SetLeft(eStartPoint, ((Point) controlPoints[i]).X - eStartPoint.Width/2);
                        Canvas.SetTop(eStartPoint, ((Point) controlPoints[i]).Y - eStartPoint.Height/2);
                        break;
                    case 1:
                        var ePoint1 =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_Point1") as Ellipse;
                        Canvas.SetLeft(ePoint1, ((Point) controlPoints[i]).X - ePoint1.Width/2);
                        Canvas.SetTop(ePoint1, ((Point) controlPoints[i]).Y - ePoint1.Height/2);
                        break;
                    case 2:
                        var ePoint2 =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_Point2") as Ellipse;
                        Canvas.SetLeft(ePoint2, ((Point) controlPoints[i]).X - ePoint2.Width/2);
                        Canvas.SetTop(ePoint2, ((Point) controlPoints[i]).Y - ePoint2.Height/2);
                        break;
                    case 3:
                        var ePoint3 =
                            LogicalTreeHelper.FindLogicalNode(DesignerPane, _currentElement.Name + "_Point3") as Ellipse;
                        Canvas.SetLeft(ePoint3, ((Point) controlPoints[i]).X - ePoint3.Width/2);
                        Canvas.SetTop(ePoint3, ((Point) controlPoints[i]).Y - ePoint3.Height/2);
                        break;
                    default:
                        throw new ApplicationException("Error: incorrect # of control points in BezierG");
                }
            }
        }

        private void UpdateGeometries(Point movingEndLocation, string id)
        {
            var geometryType = GetGeometryTypeInId(id);

            //Switch the controlpoint pane to the right panel
            GeometryPaneChange(geometryType, false);

            switch (geometryType)
            {
                case "Line":
                    UpdateLineGeometry(movingEndLocation, id);
                    break;
                case "Ellipse":
                    UpdateEllipseGeometry(movingEndLocation, id);
                    break;
                case "Rectangle":
                    UpdateRectangleGeometry(movingEndLocation, id);
                    break;
                case "Bezier":
                    UpdateBezierGeometry(movingEndLocation, id);
                    break;
                case "Arc":
                    UpdateArcGeometry(movingEndLocation, id);
                    break;
                default:
                    throw new ApplicationException("Error: incorrect GeometryType in UpdateGeometries()");
            }
        }

        private object SearchUpdatedElement(string p) => DrawingPane.Children.Cast<object>().FirstOrDefault(o => o is Path && ((Path)o).Name == p);

        private void UpdateArcGeometry(Point movingEndLocation, string id)
        {
            var s = id.Split('_');
            var controlPointType = GetContronPointTypeInId(id);
            var p = SearchUpdatedElement(s[0]) as Path;
            if (p == null)
            {
                throw new ApplicationException("Error: incorrect geometry ID");
            }
            _currentElement = p;
            var pg = p.Data as PathGeometry;
            var pf = pg.Figures[0];

            switch (controlPointType)
            {
                case "StartPoint":
                    pf.StartPoint = movingEndLocation;
                    ArcStartPoint.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    break;
                case "Point":
                    ((ArcSegment) pf.Segments[0]).Point = movingEndLocation;
                    ArcPoint.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    break;
                default:
                    throw new ApplicationException("Error: incorrect control point type");
            }

            p.Data = pg;
            var xamlstring = XamlWriter.Save(DrawingPane);
            ((TextBox) XAMLPane.Children[0]).Text = xamlstring;
        }

        private void UpdateLineGeometry(Point movingEndLocation, string id)
        {
            var s = id.Split('_');
            var controlPointType = GetContronPointTypeInId(id);
            var p = SearchUpdatedElement(s[0]) as Path;
            if (p == null)
            {
                throw new ApplicationException("Error: incorrect geometry ID");
            }
            _currentElement = p;
            var lg = p.Data as LineGeometry;

            switch (controlPointType)
            {
                case "StartPoint":
                    LineStartPoint.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    lg.StartPoint = movingEndLocation;

                    break;
                case "EndPoint":
                    LineEndPoint.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    lg.EndPoint = movingEndLocation;

                    break;
                default:
                    throw new ApplicationException("Error: Incorrect controlpoint type, '" + controlPointType +
                                                   "' in UpdateLineGeometry()");
            }
            var xamlstring = XamlWriter.Save(DrawingPane);
            ((TextBox) XAMLPane.Children[0]).Text = xamlstring;
        }

        private void UpdateEllipseGeometry(Point movingEndLocation, string id)
        {
            var s = id.Split('_');
            var controlPointType = GetContronPointTypeInId(id);
            var p = SearchUpdatedElement(s[0]) as Path;
            if (p == null)
            {
                throw new ApplicationException("Error: incorrect geometry ID");
            }
            _currentElement = p;
            var eg = p.Data.Clone() as EllipseGeometry;
            var diffX = movingEndLocation.X - eg.Center.X;
            var diffY = movingEndLocation.Y - eg.Center.Y;

            double radians, angle;
            radians = Math.Atan2(diffY, diffX);
            angle = radians*(180/Math.PI);

            switch (controlPointType)
            {
                case "Center":
                    eg.Center = movingEndLocation;

                    //Update the center in the RotateTransform when the ellipsegeometry's center is moved
                    if (eg.Transform is RotateTransform)
                    {
                        var rtWithNewCenter = eg.Transform as RotateTransform;
                        rtWithNewCenter.CenterX = eg.Center.X;
                        rtWithNewCenter.CenterY = eg.Center.Y;
                    }
                    foreach (var o in DesignerPane.Children)
                    {
                        if (o is Ellipse && ((Ellipse) o).Name.Contains(s[0]) && ((Ellipse) o).Name != s[0])
                        {
                            Canvas.SetLeft(((Ellipse) o), Canvas.GetLeft(((Ellipse) o)) + diffX);
                            Canvas.SetTop(((Ellipse) o), Canvas.GetTop(((Ellipse) o)) + diffY);
                        }
                    }
                    p.Data = eg;

                    EllipseCenterPoint.Text = eg.Center.X + " " + eg.Center.Y;
                    break;

                case "TopLeft":
                    var v0 = new Vector(-eg.RadiusX, 0);
                    var v1 = new Vector(diffX, diffY);

                    var rtTopLeft = new RotateTransform(angle + 180, eg.Center.X, eg.Center.Y);
                    eg.Transform = rtTopLeft;
                    eg.RadiusX = v1.Length;
                    EllipseRadiusX.Text = v1.Length.ToString(CultureInfo.InvariantCulture);
                    p.Data = eg;

                    //Update the TopRight control point for this EllipseGeometry
                    var eTopRight = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopRight");
                    Canvas.SetLeft(eTopRight, (eg.Center.X - diffX) - eTopRight.Width/2);
                    Canvas.SetTop(eTopRight, (eg.Center.Y - diffY) - eTopRight.Height/2);

                    var eTopMiddle = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopMiddle");
                    Canvas.SetLeft(eTopMiddle, (eg.Center.X - diffY*eg.RadiusY/v1.Length) - eTopMiddle.Width/2);
                    Canvas.SetTop(eTopMiddle, eg.Center.Y + diffX*eg.RadiusY/v1.Length - eTopMiddle.Height/2);

                    var eBottomMiddle =
                        (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_BottomMiddle");
                    Canvas.SetLeft(eBottomMiddle, (eg.Center.X + diffY*eg.RadiusY/v1.Length) - eBottomMiddle.Width/2);
                    Canvas.SetTop(eBottomMiddle, (eg.Center.Y - diffX*eg.RadiusY/v1.Length) - eBottomMiddle.Height/2);

                    break;
                case "TopMiddle":
                    var v1TopMiddle = new Vector(diffX, diffY);
                    var rtTopMiddle = new RotateTransform(angle + 90, eg.Center.X, eg.Center.Y);
                    eg.Transform = rtTopMiddle;
                    eg.RadiusY = v1TopMiddle.Length;
                    EllipseRadiusY.Text = v1TopMiddle.Length.ToString(CultureInfo.InvariantCulture);
                    p.Data = eg;

                    var eTopLeft2 = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopLeft");
                    Canvas.SetLeft(eTopLeft2, (eg.Center.X + diffY*eg.RadiusX/v1TopMiddle.Length) - eTopLeft2.Width/2);
                    Canvas.SetTop(eTopLeft2, (eg.Center.Y - diffX*eg.RadiusX/v1TopMiddle.Length) - eTopLeft2.Height/2);

                    var eTopRight2 = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopRight");
                    Canvas.SetLeft(eTopRight2, (eg.Center.X - diffY*eg.RadiusX/v1TopMiddle.Length) - eTopRight2.Width/2);
                    Canvas.SetTop(eTopRight2, (eg.Center.Y + diffX*eg.RadiusX/v1TopMiddle.Length) - eTopRight2.Height/2);

                    var eBottomMiddle2 =
                        (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_BottomMiddle");
                    Canvas.SetLeft(eBottomMiddle2, (eg.Center.X - diffX) - eBottomMiddle2.Width/2);
                    Canvas.SetTop(eBottomMiddle2, (eg.Center.Y - diffY) - eBottomMiddle2.Height/2);
                    break;

                case "TopRight":
                    var v1TopRight = new Vector(diffX, diffY);
                    var rtTopRight = new RotateTransform(angle, eg.Center.X, eg.Center.Y);
                    eg.Transform = rtTopRight;
                    eg.RadiusX = v1TopRight.Length;
                    EllipseRadiusX.Text = v1TopRight.Length.ToString(CultureInfo.InvariantCulture);
                    p.Data = eg;

                    var eTopLeft3 = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopLeft");
                    Canvas.SetLeft(eTopLeft3, (eg.Center.X - diffX) - eTopLeft3.Width/2);
                    Canvas.SetTop(eTopLeft3, (eg.Center.Y - diffY) - eTopLeft3.Height/2);

                    var eTopMiddle3 = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopMiddle");
                    Canvas.SetLeft(eTopMiddle3, (eg.Center.X + diffY*eg.RadiusY/v1TopRight.Length) - eTopMiddle3.Width/2);
                    Canvas.SetTop(eTopMiddle3, (eg.Center.Y - diffX*eg.RadiusY/v1TopRight.Length) - eTopMiddle3.Height/2);

                    var eBottomMiddle3 =
                        (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_BottomMiddle");
                    Canvas.SetLeft(eBottomMiddle3,
                        (eg.Center.X - diffY*eg.RadiusY/v1TopRight.Length) - eBottomMiddle3.Width/2);
                    Canvas.SetTop(eBottomMiddle3,
                        (eg.Center.Y + diffX*eg.RadiusY/v1TopRight.Length) - eBottomMiddle3.Height/2);
                    break;

                case "BottomMiddle":
                    var v1BottomMiddle = new Vector(diffX, diffY);
                    var rtBottomMiddle = new RotateTransform(angle - 90, eg.Center.X, eg.Center.Y);
                    eg.Transform = rtBottomMiddle;
                    eg.RadiusY = v1BottomMiddle.Length;
                    EllipseRadiusY.Text = v1BottomMiddle.Length.ToString(CultureInfo.InvariantCulture);
                    p.Data = eg;

                    var eTopLeft4 = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopLeft");
                    Canvas.SetLeft(eTopLeft4, (eg.Center.X - diffY*eg.RadiusX/v1BottomMiddle.Length) - eTopLeft4.Width/2);
                    Canvas.SetTop(eTopLeft4, (eg.Center.Y + diffX*eg.RadiusX/v1BottomMiddle.Length) - eTopLeft4.Height/2);

                    var eTopRight4 = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopRight");
                    Canvas.SetLeft(eTopRight4,
                        (eg.Center.X + diffY*eg.RadiusX/v1BottomMiddle.Length) - eTopRight4.Width/2);
                    Canvas.SetTop(eTopRight4,
                        (eg.Center.Y - diffX*eg.RadiusX/v1BottomMiddle.Length) - eTopRight4.Height/2);

                    var eTopMiddle4 = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopMiddle");
                    Canvas.SetLeft(eTopMiddle4, (eg.Center.X - diffX) - eTopMiddle4.Width/2);
                    Canvas.SetTop(eTopMiddle4, (eg.Center.Y - diffY) - eTopMiddle4.Height/2);
                    break;

                default:
                    throw new ApplicationException("Error: incorrect EllipseGeometry controlpoint type");
            }
            var xamlstring = XamlWriter.Save(DrawingPane);
            ((TextBox) XAMLPane.Children[0]).Text = xamlstring;
        }

        private void UpdateRectangleGeometry(Point movingEndLocation, string id)
        {
            double width, height;
            var s = id.Split('_');
            var controlPointType = GetContronPointTypeInId(id);
            var p = SearchUpdatedElement(s[0]) as Path;
            if (p == null)
            {
                throw new ApplicationException("Error:  incorrect geometry ID");
            }
            _currentElement = p;
            var rg = p.Data as RectangleGeometry;

            //Get all of the related control points in DesignerPane
            var rTopLeft = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopLeft");
            var rTopRight = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_TopRight");
            var rBottomLeft = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_BottomLeft");
            var rBottomRight = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_BottomRight");
            var rCorner = (Ellipse) LogicalTreeHelper.FindLogicalNode(DesignerPane, s[0] + "_Corner");


            switch (controlPointType)
            {
                case "TopLeft":
                    width = rg.Rect.Width + (rg.Rect.X - movingEndLocation.X);
                    height = rg.Rect.Height + (rg.Rect.Y - movingEndLocation.Y);
                    RectangleWidth.Text = width.ToString(CultureInfo.InvariantCulture);
                    RectangleHeight.Text = height.ToString(CultureInfo.InvariantCulture);

                    //Update the RectangleGeometry.
                    rg.Rect = new Rect(movingEndLocation.X, movingEndLocation.Y, width, height);

                    //Update the control points
                    Canvas.SetLeft(rTopRight, (movingEndLocation.X + width) - rTopRight.Width/2);
                    Canvas.SetTop(rTopRight, (movingEndLocation.Y) - rTopRight.Height/2);
                    Canvas.SetLeft(rBottomLeft, movingEndLocation.X - rBottomLeft.Width/2);

                    if (rCorner != null)
                    {
                        Canvas.SetLeft(rCorner, movingEndLocation.X + rg.RadiusX - rCorner.Width/2);
                        Canvas.SetTop(rCorner, movingEndLocation.Y + rg.RadiusY - rCorner.Height/2);
                    }

                    RectangleTopLeftPoint.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    break;
                case "TopRight":
                    width = movingEndLocation.X - rg.Rect.X;
                    height = (rg.Rect.Y + rg.Rect.Height) - movingEndLocation.Y;
                    RectangleWidth.Text = width.ToString(CultureInfo.InvariantCulture);
                    RectangleHeight.Text = height.ToString(CultureInfo.InvariantCulture);

                    //Update the control points
                    Canvas.SetTop(rTopLeft, movingEndLocation.Y - rTopLeft.Height/2);
                    Canvas.SetLeft(rBottomRight, movingEndLocation.X - rBottomRight.Width/2);

                    if (rCorner != null)
                    {
                        Canvas.SetTop(rCorner,
                            Canvas.GetTop(rCorner) + (movingEndLocation.Y - rg.Rect.Y) - rCorner.Height/2);
                    }

                    //Update the RectangleGeometry
                    rg.Rect = new Rect(Canvas.GetLeft(rTopLeft) + rTopLeft.Width/2,
                        Canvas.GetTop(rTopLeft) + rTopLeft.Height/2,
                        width, height);

                    //Update the TopLeft control field
                    RectangleTopLeftPoint.Text = movingEndLocation.X + " " + movingEndLocation.Y;

                    break;
                case "BottomLeft":

                    width = rg.Rect.Width + (rg.Rect.X - movingEndLocation.X);
                    height = movingEndLocation.Y - rg.Rect.Y;
                    RectangleWidth.Text = width.ToString(CultureInfo.InvariantCulture);
                    RectangleHeight.Text = height.ToString(CultureInfo.InvariantCulture);

                    //Update the control points
                    Canvas.SetLeft(rTopLeft, movingEndLocation.X - rTopLeft.Width/2);
                    Canvas.SetLeft(rBottomRight, movingEndLocation.X + width - rBottomRight.Width/2);
                    Canvas.SetTop(rBottomRight, movingEndLocation.Y - rBottomRight.Height/2);

                    if (rCorner != null)
                    {
                        Canvas.SetLeft(rCorner, movingEndLocation.X + rg.RadiusX - rCorner.Width/2);
                    }

                    RectangleTopLeftPoint.Text = Canvas.GetLeft(rTopLeft) + rTopLeft.Width/2 + " " +
                                                 Canvas.GetTop(rTopLeft) +
                                                 rTopLeft.Height/2;

                    //Update the RectangleGeometry
                    rg.Rect = new Rect(Canvas.GetLeft(rTopLeft) + rTopLeft.Width/2,
                        Canvas.GetTop(rTopLeft) + rTopLeft.Height/2,
                        width, height);

                    break;

                case "BottomRight":
                    width = movingEndLocation.X - rg.Rect.X;
                    height = movingEndLocation.Y - rg.Rect.Y;
                    RectangleWidth.Text = width.ToString(CultureInfo.InvariantCulture);
                    RectangleHeight.Text = height.ToString(CultureInfo.InvariantCulture);

                    //Update the control points
                    Canvas.SetLeft(rTopRight, movingEndLocation.X - rTopRight.Width/2);
                    Canvas.SetTop(rBottomLeft, movingEndLocation.Y - rBottomLeft.Height/2);

                    //Update the RectangleGeometry
                    rg.Rect = new Rect(Canvas.GetLeft(rTopLeft) + rTopLeft.Width/2,
                        Canvas.GetTop(rTopLeft) + rTopLeft.Height/2,
                        width, height);

                    p.Data = rg;
                    break;
                case "Corner":
                    var radiusx = movingEndLocation.X - rg.Rect.X;
                    var radiusy = movingEndLocation.Y - rg.Rect.Y;

                    if (radiusx <= 0)
                    {
                        Canvas.SetLeft(rCorner, rg.Rect.X + 0.1 - rCorner.Width);
                        radiusx = 0.1;
                    }
                    if (radiusy <= 0)
                    {
                        Canvas.SetTop(rCorner, rg.Rect.Y + 0.1 - rCorner.Height/2);
                        radiusy = 0.1;
                    }

                    RectangleWidth.Text = radiusx.ToString(CultureInfo.InvariantCulture);
                    RectangleHeight.Text = radiusy.ToString(CultureInfo.InvariantCulture);

                    rg.RadiusX = radiusx;
                    rg.RadiusY = radiusy;

                    p.Data = rg;
                    break;
                default:
                    throw new ApplicationException("Error: Incorrect control point type");
            }
            var xamlstring = XamlWriter.Save(DrawingPane);
            ((TextBox) XAMLPane.Children[0]).Text = xamlstring;
        }

        private void UpdateBezierGeometry(Point movingEndLocation, string id)
        {
            var s = id.Split('_');
            var controlPointType = GetContronPointTypeInId(id);
            var p = SearchUpdatedElement(s[0]) as Path;
            if (p == null)
            {
                throw new ApplicationException("Error:  incorrect geometry ID");
            }
            _currentElement = p;
            var pg = p.Data.Clone() as PathGeometry;
            var pf = pg.Figures[0];
            switch (controlPointType)
            {
                case "StartPoint":
                    pf.StartPoint = movingEndLocation;
                    BezierStartPoint.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    break;
                case "Point1":
                    BezierPoint1.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    ((BezierSegment) pf.Segments[0]).Point1 = movingEndLocation;
                    break;
                case "Point2":
                    BezierPoint2.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    ((BezierSegment) pf.Segments[0]).Point2 = movingEndLocation;
                    break;
                case "Point3":
                    BezierPoint3.Text = movingEndLocation.X + " " + movingEndLocation.Y;
                    ((BezierSegment) pf.Segments[0]).Point3 = movingEndLocation;
                    break;
                default:
                    throw new ApplicationException("Error:  Incorrect control point type");
            }

            p.Data = pg;
            var xamlstring = XamlWriter.Save(DrawingPane);
            ((TextBox) XAMLPane.Children[0]).Text = xamlstring;
        }

        private string GetContronPointTypeInId(string id)
        {
            var s = id.Split('_');
            return s[1];
        }

        private string GetGeometryTypeInId(string id)
        {
            var s = id.Split('_');
            if (s[0].Contains("Line"))
            {
                return "Line";
            }
            if (s[0].Contains("Ellipse"))
            {
                return "Ellipse";
            }
            if (s[0].Contains("Rectangle"))
            {
                return "Rectangle";
            }
            if (s[0].Contains("Arc"))
            {
                return "Arc";
            }
            return "Bezier";
        }

        private string GetControlPointName(string id) => null;

        private void AddControlPoints(ArrayList controlPoints, string geometryType)
        {
            switch (geometryType)
            {
                case "Line":
                    AddLineGeometryControlPoints(controlPoints);
                    break;
                case "Ellipse":
                    AddEllipseGeometryControlPoints(controlPoints);
                    break;
                case "Rectangle":
                    AddRectangleGeometryControlPoints(controlPoints);
                    break;
                case "Arc":
                    AddArcGeometryControlPoints(controlPoints);
                    break;
                case "Bezier":
                    AddBezierGeometryControlPoints(controlPoints);
                    break;
                default:
                    throw new ApplicationException("Error:  incorrect Geometry type");
            }
        }


        private static readonly double ControlPointMarkerWidth = 20;
        private static readonly double ControlPointMarkerHeight = 20;

        private void AddLineGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 2)
                throw new ApplicationException("Error:  incorrect # of control points for LineGeometry");

            for (var i = 0; i < controlPoints.Count; i++)
            {
                var e = new Ellipse
                {
                    Visibility = Visibility.Hidden,
                    Stroke = Brushes.Black,
                    StrokeThickness = 1,
                    Fill = Brushes.White,
                    Opacity = 0.5,
                    Width = 3,
                    Height = 3
                };

                if (i == 0)
                {
                    e.Name = "Line" + _lineCount + "_StartPoint";
                }
                else
                {
                    e.Name = "Line" + _lineCount + "_EndPoint";
                }

                e.Width = ControlPointMarkerWidth;
                e.Height = ControlPointMarkerHeight;
                Canvas.SetLeft(e, ((Point) controlPoints[i]).X - e.Width/2);
                Canvas.SetTop(e, ((Point) controlPoints[i]).Y - e.Height/2);


                e.MouseLeftButtonDown += Ellipse_MouseLeftButtonDown;
                e.MouseLeftButtonUp += Ellipse_MouseLeftButtonUp;
                e.MouseMove += Ellipse_MouseMove;

                //Add the control point to the Designer Pane
                //DesignerPane.Children.Add(e);
                DesignerPane.Children.Insert(DesignerPane.Children.Count - 1, e);
            }
        }

        private void AddEllipseGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 5)
            {
                throw new ApplicationException("Error:  incorrect # of control points for EllipseGeometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                var e = new Ellipse
                {
                    Visibility = Visibility.Hidden,
                    Stroke = Brushes.Black,
                    StrokeThickness = 1,
                    Fill = Brushes.White,
                    Opacity = 0.5,
                    Width = 3,
                    Height = 3
                };

                switch (i)
                {
                    case 0:
                        e.Name = "Ellipse" + _elliipseCount + "_Center";
                        break;
                    case 1:
                        e.Name = "Ellipse" + _elliipseCount + "_TopLeft";
                        break;
                    case 2:
                        e.Name = "Ellipse" + _elliipseCount + "_TopMiddle";
                        break;
                    case 3:
                        e.Name = "Ellipse" + _elliipseCount + "_TopRight";
                        break;
                    case 4:
                        e.Name = "Ellipse" + _elliipseCount + "_BottomMiddle";
                        break;
                    default:
                        throw new ApplicationException("Error: Incorrect control point ");
                }

                e.Width = ControlPointMarkerWidth;
                e.Height = ControlPointMarkerHeight;
                Canvas.SetLeft(e, ((Point) controlPoints[i]).X - e.Width/2);
                Canvas.SetTop(e, ((Point) controlPoints[i]).Y - e.Height/2);

                e.MouseLeftButtonDown += Ellipse_MouseLeftButtonDown;
                e.MouseLeftButtonUp += Ellipse_MouseLeftButtonUp;
                e.MouseMove += Ellipse_MouseMove;

                //Add the control point to the Designer Pane
                DesignerPane.Children.Insert(DesignerPane.Children.Count - 1, e);
            }
        }

        private void AddRectangleGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 5 && controlPoints.Count != 4)
            {
                throw new ApplicationException("Error:  incorrect # of control points for RectangleGeometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                var e = new Ellipse
                {
                    Visibility = Visibility.Hidden,
                    Stroke = Brushes.Black,
                    StrokeThickness = 1,
                    Fill = Brushes.White,
                    Opacity = 0.5,
                    Width = 3,
                    Height = 3
                };

                switch (i)
                {
                    case 0:
                        e.Name = "Rectangle" + _rectangleCount + "_TopLeft";
                        break;
                    case 1:
                        e.Name = "Rectangle" + _rectangleCount + "_TopRight";
                        break;
                    case 2:
                        e.Name = "Rectangle" + _rectangleCount + "_BottomLeft";
                        break;
                    case 3:
                        e.Name = "Rectangle" + _rectangleCount + "_BottomRight";
                        break;
                    case 4:
                        e.Name = "Rectangle" + _rectangleCount + "_Corner";
                        break;
                    default:
                        throw new ApplicationException("Error: Incorrect control point ");
                }


                e.Width = ControlPointMarkerWidth;
                e.Height = ControlPointMarkerHeight;
                Canvas.SetLeft(e, ((Point) controlPoints[i]).X - e.Width/2);
                Canvas.SetTop(e, ((Point) controlPoints[i]).Y - e.Height/2);
                e.MouseLeftButtonDown += Ellipse_MouseLeftButtonDown;
                e.MouseLeftButtonUp += Ellipse_MouseLeftButtonUp;
                e.MouseMove += Ellipse_MouseMove;

                //Add the control point to the Designer Pane
                DesignerPane.Children.Insert(DesignerPane.Children.Count - 1, e);
            }
        }

        private void AddArcGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 2)
            {
                throw new ApplicationException("Error:  incorrect # of control points for Arc Geometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                var e = new Ellipse
                {
                    Visibility = Visibility.Hidden,
                    Stroke = Brushes.Black,
                    StrokeThickness = 1,
                    Fill = Brushes.White,
                    Opacity = 0.5,
                    Width = 3,
                    Height = 3
                };

                switch (i)
                {
                    case 0:
                        e.Name = "Arc" + _arcCount + "_StartPoint";
                        break;
                    case 1:
                        e.Name = "Arc" + _arcCount + "_Point";
                        break;
                    default:
                        throw new ApplicationException("Error: Incorrect control point ");
                }

                e.Width = ControlPointMarkerWidth;
                e.Height = ControlPointMarkerHeight;
                Canvas.SetLeft(e, ((Point) controlPoints[i]).X - e.Width/2);
                Canvas.SetTop(e, ((Point) controlPoints[i]).Y - e.Height/2);

                e.MouseLeftButtonDown += Ellipse_MouseLeftButtonDown;
                e.MouseLeftButtonUp += Ellipse_MouseLeftButtonUp;
                e.MouseMove += Ellipse_MouseMove;

                //Add the control point to the Designer Pane
                //DesignerPane.Children.Insert(DesignerPane.Children.Count - 2, e);
                DesignerPane.Children.Insert(DesignerPane.Children.Count - 1, e);
            }
        }

        private void AddBezierGeometryControlPoints(ArrayList controlPoints)
        {
            if (controlPoints.Count != 4)
            {
                throw new ApplicationException("Error:  incorrect # of control points for Bezier Geometry");
            }
            for (var i = 0; i < controlPoints.Count; i++)
            {
                var e = new Ellipse
                {
                    Visibility = Visibility.Hidden,
                    Stroke = Brushes.Black,
                    StrokeThickness = 1,
                    Fill = Brushes.White,
                    Opacity = 0.5,
                    Width = 3,
                    Height = 3
                };

                switch (i)
                {
                    case 0:
                        e.Name = "Bezier" + _bezierCount + "_StartPoint";
                        break;
                    case 1:
                        e.Name = "Bezier" + _bezierCount + "_Point1";
                        break;
                    case 2:
                        e.Name = "Bezier" + _bezierCount + "_Point2";
                        break;
                    case 3:
                        e.Name = "Bezier" + _bezierCount + "_Point3";
                        break;
                    default:
                        throw new ApplicationException("Error: Incorrect control point ");
                }

                e.Width = ControlPointMarkerWidth;
                e.Height = ControlPointMarkerHeight;
                Canvas.SetLeft(e, ((Point) controlPoints[i]).X - e.Width/2);
                Canvas.SetTop(e, ((Point) controlPoints[i]).Y - e.Height/2);
                e.MouseLeftButtonDown += Ellipse_MouseLeftButtonDown;
                e.MouseLeftButtonUp += Ellipse_MouseLeftButtonUp;
                e.MouseMove += Ellipse_MouseMove;

                //Add the control point to the Designer Pane
                DesignerPane.Children.Insert(DesignerPane.Children.Count - 1, e);
            }
        }

        /// <summary>
        ///     The function takes the design pane element,e.g. LinePane, RectanglePane,
        ///     and extract the value from the different control point fields from the pane and construct
        ///     a Path with the correct Geometry
        /// </summary>
        /// <param name="pane"></param>
        /// <returns></returns>
        private GeometryBase GeometryFactory(FrameworkElement pane)
        {
            switch (pane.Name.Remove(pane.Name.LastIndexOf("Pane", StringComparison.Ordinal)))
            {
                case "Line":
                    return new LineG(pane);
                case "Ellipse":
                    return new EllipseG(pane);
                case "Rectangle":
                    return new RectanlgeG(pane);
                case "Arc":
                    return new ArcG(pane);
                case "Bezier":
                    return new BezierG(pane);
                default:
                    throw new ApplicationException("Error:  Unknow Geometry name?");
            }
        }

        #endregion

        #region Data members

        private bool _initialSelection = true;
        private int _lineCount = 1;
        private int _elliipseCount = 1;
        private int _rectangleCount = 1;
        private int _arcCount = 1;
        private int _bezierCount = 1;
        private bool _isShow;
        private Path _currentElement;
        private bool _isInsert = true;

        #endregion
    }
}

<|start_filename|>Documents/Annotations/AnnotationsStyling/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.IO;
using System.Windows;
using System.Windows.Annotations;
using System.Windows.Annotations.Storage;
using System.Windows.Controls;

namespace AnnotationsStyling
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // ------------------------- OnStyleSelected --------------------------
        /// <summary>
        ///     Replaces the default StickyNote style when a new
        ///     style is selected from the drop down combo box.
        /// </summary>
        protected void OnStyleSelected(object sender, SelectionChangedEventArgs e)
        {
            // Extract the selected style.
            var source = (ComboBox) e.Source;
            var selectedStyle = (StyleMetaData) source.SelectedItem;
            var newStyle = new Style(typeof (StickyNoteControl)) {BasedOn = selectedStyle.Value};

            // Replace the default StickyNote style with the one that was just selected.
            var defaultKey = typeof (StickyNoteControl);
            if (Viewer.Resources.Contains(defaultKey))
                Viewer.Resources.Remove(defaultKey);
            Viewer.Resources.Add(defaultKey, newStyle);

            // Re-load annotations so that they pickup new style.
            var service = AnnotationService.GetService(Viewer);
            service.Disable();
            service.Enable(service.Store);
        }

        #region Boilerplate Annotations Code

        // ----------------------------- OnLoaded -----------------------------
        /// <summary>
        ///     Turns Annotations on.
        /// </summary>
        protected void OnLoaded(object sender, RoutedEventArgs e)
        {
            // Make sure that an AnnotationService isn�t already enabled.
            var service = AnnotationService.GetService(Viewer);
            if (service == null)
            {
                // (a) Create a Stream for the annotations to be stored in.
                _annotationStream =
                    new FileStream("annotations.xml", FileMode.OpenOrCreate);
                // (b) Create an AnnotationService on our
                // FlowDocumentPageViewer.
                service = new AnnotationService(Viewer);
                // (c) Create an AnnotationStore and give it the stream we
                // created. (Autoflush == false)
                AnnotationStore store = new XmlStreamStore(_annotationStream);
                // (d) "Turn on annotations". Annotations will be persisted in
                // the stream created at (a).
                service.Enable(store);
            }
        } // end:OnLoaded


        // ---------------------------- OnUnLoaded ----------------------------
        /// <summary>
        ///     Turns Annotations off.
        /// </summary>
        protected void OnUnloaded(object sender, RoutedEventArgs e)
        {
            // (a) Check that an AnnotationService
            // actually existed and was Enabled.
            var service = AnnotationService.GetService(Viewer);
            if (service != null && service.IsEnabled)
            {
                // (b) Flush changes to annotations to our stream.
                service.Store.Flush();
                // (c) Turn off annotations.
                service.Disable();
                // (d) Close our stream.
                _annotationStream.Close();
            }
        }

        // The stream that we will store annotations in.
        private Stream _annotationStream;

        #endregion Boilerplate Annotations Code
    } // end:partial class Window1


    // =============== class ResourceEntryToComboItemConverter ================
    // end:class ResourceEntryToComboItemConverter


    // ========================= class StyleMetaData ==========================
}

<|start_filename|>Documents/Fixed Documents/DocumentMerge/RollupFixedDocument.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Windows.Documents;
using System.Windows.Markup;

namespace DocumentMerge
{
    /// <summary>
    ///     Maintains data needed to generate a DocumentReference to be added to a RollUpDocument
    /// </summary>
    public class RollUpFixedDocument
    {
        public RollUpFixedDocument()
        {
            Pages = new List<RollUpFixedPage>();
        }

        public RollUpFixedDocument(FixedDocument fixedDocument)
            : this()
        {
            FixedDocument = fixedDocument;
        }

        public RollUpFixedDocument(Uri source, Uri baseUri)
            : this()
        {
            Source = source;
            BaseUri = baseUri;
        }

        public FixedDocument FixedDocument { get; set; }
        public List<RollUpFixedPage> Pages { get; set; }
        public Uri BaseUri { get; set; }
        public Uri Source { get; set; }

        internal void CreatePagesFromSource()
        {
            var documentReference = new DocumentReference {Source = Source};
            ((IUriContext) documentReference).BaseUri = BaseUri;
            var fixedDocument = documentReference.GetDocument(true);
            PrivateCreatePagesFromFixedDocument(fixedDocument);
        }

        internal void CreatePagesFromFixedDocument()
        {
            PrivateCreatePagesFromFixedDocument(FixedDocument);
        }

        private void PrivateCreatePagesFromFixedDocument(FixedDocument fixedDocument)
        {
            foreach (var pageContent in fixedDocument.Pages)
            {
                Pages.Add(((IUriContext) pageContent).BaseUri != null
                    ? new RollUpFixedPage(pageContent.Source, ((IUriContext) pageContent).BaseUri)
                    : new RollUpFixedPage(pageContent.Child));
            }
            Source = null;
            BaseUri = null;
        }
    }
}

<|start_filename|>Documents/Annotations/AnnotatedDocumentViewer/AnnotationDataConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Markup;

// Type
// CultureInfo
// MemoryStream
// IValueConverter
// Section, TextRange

// XamlReader

namespace AnnotatedDocumentViewer
{
    public class AnnotationDataConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Convert 64 bit binary data into an 8 bit byte array and load
            // it into a memory buffer
            var data = System.Convert.FromBase64String(value as string);
            using (var buffer = new MemoryStream(data))
            {
                // Convert memory buffer to object and return text
                var section = (Section) XamlReader.Load(buffer);
                var range = new TextRange(section.ContentStart, section.ContentEnd);
                return range.Text;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => null;
    }
}

<|start_filename|>Data Binding/PropertyChangeNotification/Bid.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace PropertyChangeNotification
{
    public class Bid : INotifyPropertyChanged
    {
        private string _biditemname;
        private decimal _biditemprice;

        public Bid(string newBidItemName, decimal newBidItemPrice)
        {
            _biditemname = newBidItemName;
            _biditemprice = newBidItemPrice;
        }

        public string BidItemName
        {
            get { return _biditemname; }
            set
            {
                if (_biditemname.Equals(value) == false)
                {
                    _biditemname = value;
                    // Call OnPropertyChanged whenever the property is updated
                    OnPropertyChanged("BidItemName");
                }
            }
        }

        public decimal BidItemPrice
        {
            get { return _biditemprice; }
            set
            {
                if (_biditemprice.Equals(value) == false)
                {
                    _biditemprice = value;
                    // Call OnPropertyChanged whenever the property is updated
                    OnPropertyChanged("BidItemPrice");
                }
            }
        }

        // Declare event
        public event PropertyChangedEventHandler PropertyChanged;
        // OnPropertyChanged to update property value in binding
        private void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }
}

<|start_filename|>Windows/DialogBox/FontPropertyLists.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Media;

namespace DialogBox
{
    public class FontPropertyLists
    {
        private static Collection<FontFamily> _fontFaces;
        private static Collection<FontStyle> _fontStyles;
        private static Collection<FontWeight> _fontWeights;
        private static Collection<double> _fontSizes;

        /// <summary>
        ///     Return a collection of avaliable font styles
        /// </summary>
        public static ICollection<FontFamily> FontFaces
        {
            get
            {
                if (_fontFaces == null) _fontFaces = new Collection<FontFamily>();
                foreach (var fontFamily in Fonts.SystemFontFamilies)
                {
                    _fontFaces.Add(fontFamily);
                }
                return _fontFaces;
            }
        }

        /// <summary>
        ///     Return a collection of avaliable font styles
        /// </summary>
        public static ICollection FontStyles => _fontStyles ?? (_fontStyles = new Collection<FontStyle>
        {
            System.Windows.FontStyles.Normal,
            System.Windows.FontStyles.Oblique,
            System.Windows.FontStyles.Italic
        });

        /// <summary>
        ///     Return a collection of avaliable FontWeight
        /// </summary>
        public static ICollection FontWeights => _fontWeights ?? (_fontWeights = new Collection<FontWeight>
        {
            System.Windows.FontWeights.Thin,
            System.Windows.FontWeights.Light,
            System.Windows.FontWeights.Regular,
            System.Windows.FontWeights.Normal,
            System.Windows.FontWeights.Medium,
            System.Windows.FontWeights.Heavy,
            System.Windows.FontWeights.SemiBold,
            System.Windows.FontWeights.DemiBold,
            System.Windows.FontWeights.Bold,
            System.Windows.FontWeights.Black,
            System.Windows.FontWeights.ExtraLight,
            System.Windows.FontWeights.ExtraBold,
            System.Windows.FontWeights.ExtraBlack,
            System.Windows.FontWeights.UltraLight,
            System.Windows.FontWeights.UltraBold,
            System.Windows.FontWeights.UltraBlack
        });

        /// <summary>
        ///     Return a collection of font sizes.
        /// </summary>
        public static Collection<double> FontSizes
        {
            get
            {
                if (_fontSizes == null)
                {
                    _fontSizes = new Collection<double>();
                    for (double i = 8; i <= 40; i++) _fontSizes.Add(i);
                }
                return _fontSizes;
            }
        }

        public static bool CanParseFontStyle(string fontStyleName)
        {
            try
            {
                var converter = new FontStyleConverter();
                converter.ConvertFromString(fontStyleName);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static FontStyle ParseFontStyle(string fontStyleName)
        {
            var converter = new FontStyleConverter();
            return (FontStyle) converter.ConvertFromString(fontStyleName);
        }

        public static bool CanParseFontWeight(string fontWeightName)
        {
            try
            {
                var converter = new FontWeightConverter();
                converter.ConvertFromString(fontWeightName);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static FontWeight ParseFontWeight(string fontWeightName)
        {
            var converter = new FontWeightConverter();
            return (FontWeight) converter.ConvertFromString(fontWeightName);
        }
    }
}

<|start_filename|>Animation/AnimationExamples/TimingBehaviors/InteractiveAnimationsExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;

namespace AnimationExamples
{
    public partial class InteractiveAnimationsExample : Page
    {
        private AnimationTransitionType _selectedTransition;

        // Computes the target point when the user clicks the Canvas
        // and starts the appropriate animation.
        private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs args)
        {
            var targetPoint = args.GetPosition(ContainerCanvas);
            targetPoint.X = targetPoint.X - (MyAnimatedObject.ActualWidth/2);
            targetPoint.Y = targetPoint.Y - (MyAnimatedObject.ActualHeight/2);


            switch (_selectedTransition)
            {
                case AnimationTransitionType.Linear:
                    AnimateToDestinationUsingLinearAnimation(targetPoint);
                    break;

                case AnimationTransitionType.Bounce:
                    AnimateToDestinationUsingBounceAnimation(targetPoint);
                    break;

                case AnimationTransitionType.Elastic:
                    AnimateToDestinationUsingElasticAnimation(targetPoint);
                    break;
            }
        }

        // Animates to the target point using a standard
        // DoubleAnimation.
        private void AnimateToDestinationUsingLinearAnimation(Point targetPoint)
        {
            var xAnimation = new DoubleAnimation
            {
                To = targetPoint.X,
                Duration = new Duration(TimeSpan.FromSeconds(5))
            };
            var yAnimation = new DoubleAnimation
            {
                To = targetPoint.Y,
                Duration = new Duration(TimeSpan.FromSeconds(5))
            };
            MyAnimatedObject.BeginAnimation(Canvas.LeftProperty, xAnimation);
            MyAnimatedObject.BeginAnimation(Canvas.TopProperty, yAnimation);
        }

        // Animates to the target point using a custom
        // BouncAnimation.
        private void AnimateToDestinationUsingBounceAnimation(Point targetPoint)
        {
            var bounceXAnimation =
                new BounceDoubleAnimation
                {
                    From = Canvas.GetLeft(MyAnimatedObject),
                    To = targetPoint.X,
                    Duration = TimeSpan.FromSeconds(5),
                    EdgeBehavior = BounceDoubleAnimation.EdgeBehaviorEnum.EaseIn
                };
            MyAnimatedObject.BeginAnimation(Canvas.LeftProperty, bounceXAnimation);

            var bounceYAnimation =
                new BounceDoubleAnimation
                {
                    From = Canvas.GetTop(MyAnimatedObject),
                    To = targetPoint.Y,
                    Duration = TimeSpan.FromSeconds(5),
                    EdgeBehavior = BounceDoubleAnimation.EdgeBehaviorEnum.EaseIn
                };
            MyAnimatedObject.BeginAnimation(Canvas.TopProperty, bounceYAnimation);
        }

        // Animates to the target point using a custom
        // ElasticAnimation.        
        private void AnimateToDestinationUsingElasticAnimation(Point targetPoint)
        {
            var elasticXAnimation =
                new ElasticDoubleAnimation
                {
                    From = Canvas.GetLeft(MyAnimatedObject),
                    To = targetPoint.X,
                    Duration = TimeSpan.FromSeconds(5),
                    EdgeBehavior = ElasticDoubleAnimation.EdgeBehaviorEnum.EaseIn
                };
            MyAnimatedObject.BeginAnimation(Canvas.LeftProperty, elasticXAnimation);

            var elasticYAnimation =
                new ElasticDoubleAnimation
                {
                    From = Canvas.GetTop(MyAnimatedObject),
                    To = targetPoint.Y,
                    Duration = TimeSpan.FromSeconds(5),
                    EdgeBehavior = ElasticDoubleAnimation.EdgeBehaviorEnum.EaseIn
                };
            MyAnimatedObject.BeginAnimation(Canvas.TopProperty, elasticYAnimation);
        }

        // Sets the default animation transition mode.
        private void PageLoaded(object sender, RoutedEventArgs args)
        {
            LinearTransitionRadioButton.IsChecked = true;
        }

        // Updates the cached animation transition.
        private void SelectedTransitionChanged(object sender, RoutedEventArgs args)
        {
            var value = (string) ((RadioButton) args.Source).Content;
            _selectedTransition = (AnimationTransitionType) Enum.Parse(typeof (AnimationTransitionType), value);
        }
    }
}

<|start_filename|>Windows/DialogBox/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;

namespace DialogBox
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _needsToBeSaved;

        public MainWindow()
        {
            InitializeComponent();
        }

        // Closing
        private void mainWindow_Closing(object sender, CancelEventArgs e)
        {
            // If the document needs to be saved
            if (_needsToBeSaved)
            {
                // Configure the message box
                var messageBoxText =
                    "This document needs to be saved. Click Yes to save and exit, No to exit without saving, or Cancel to not exit.";
                var caption = "Word Processor";
                var button = MessageBoxButton.YesNoCancel;
                var icon = MessageBoxImage.Warning;

                // Display message box
                var messageBoxResult = MessageBox.Show(messageBoxText, caption, button, icon);

                // Process message box results
                switch (messageBoxResult)
                {
                    case MessageBoxResult.Yes: // Save document and exit
                        SaveDocument();
                        break;
                    case MessageBoxResult.No: // Exit without saving
                        break;
                    case MessageBoxResult.Cancel: // Don't exit
                        e.Cancel = true;
                        break;
                }
            }
        }

        private void fileOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenDocument();
        }

        private void fileSave_Click(object sender, RoutedEventArgs e)
        {
            SaveDocument();
        }

        private void filePrint_Click(object sender, RoutedEventArgs e)
        {
            PrintDocument();
        }

        private void fileExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void editFindMenuItem_Click(object sender, RoutedEventArgs e)
        {
            // Instantiate the dialog box
            var dlg = new FindDialogBox(documentTextBox) {Owner = this};

            // Configure the dialog box
            dlg.TextFound += dlg_TextFound;

            // Open the dialog box modally
            dlg.Show();
        }

        private void formatMarginsMenuItem_Click(object sender, RoutedEventArgs e)
        {
            // Instantiate the dialog box
            var dlg = new MarginsDialogBox
            {
                Owner = this,
                DocumentMargin = documentTextBox.Margin
            };

            // Configure the dialog box

            // Open the dialog box modally 
            dlg.ShowDialog();

            // Process data entered by user if dialog box is accepted
            if (dlg.DialogResult == true)
            {
                // Update fonts
                documentTextBox.Margin = dlg.DocumentMargin;
            }
        }

        private void formatFontMenuItem_Click(object sender, RoutedEventArgs e)
        {
            // Instantiate the dialog box
            var dlg = new FontDialogBox
            {
                Owner = this,
                FontFamily = documentTextBox.FontFamily,
                FontSize = documentTextBox.FontSize,
                FontWeight = documentTextBox.FontWeight,
                FontStyle = documentTextBox.FontStyle
            };

            // Configure the dialog box

            // Open the dialog box modally 
            dlg.ShowDialog();

            // Process data entered by user if dialog box is accepted
            if (dlg.DialogResult == true)
            {
                // Update fonts
                documentTextBox.FontFamily = dlg.FontFamily;
                documentTextBox.FontSize = dlg.FontSize;
                documentTextBox.FontWeight = dlg.FontWeight;
                documentTextBox.FontStyle = dlg.FontStyle;
            }
        }

        // Detect when document has been altered
        private void documentTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            _needsToBeSaved = true;
        }

        private void OpenDocument()
        {
            // Instantiate the dialog box
            var dlg = new OpenFileDialog
            {
                FileName = "Document",
                DefaultExt = ".wpf",
                Filter = "Word Processor Files (.wpf)|*.wpf"
            };

            // Configure open file dialog box
            // Default file name
            // Default file extension
            // Filter files by extension

            // Open the dialog box modally
            var result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                var filename = dlg.FileName;
            }
        }

        private void SaveDocument()
        {
            // Configure save file dialog
            var dlg = new SaveFileDialog
            {
                FileName = "Document",
                DefaultExt = ".wpf",
                Filter = "Word Processor Files (.wpf)|*.wpf"
            };
            // Default file name
            // Default file extension
            // Filter files by extension

            // Show save file dialog
            var result = dlg.ShowDialog();

            // Process save file dialog results
            if (result == true)
            {
                // Save document
                var filename = dlg.FileName;
            }
        }

        private void PrintDocument()
        {
            // Configure printer dialog
            var dlg = new PrintDialog
            {
                PageRangeSelection = PageRangeSelection.AllPages,
                UserPageRangeEnabled = true
            };

            // Show save file dialog
            var result = dlg.ShowDialog();

            // Process save file dialog results
            if (result == true)
            {
                // Print document
            }
        }

        private void dlg_TextFound(object sender, EventArgs e)
        {
            // Get the find dialog box that raised the event
            var dlg = (FindDialogBox) sender;

            // Get find results and select found text
            documentTextBox.Select(dlg.Index, dlg.Length);
            documentTextBox.Focus();
        }
    }
}

<|start_filename|>Properties/CustomClassesWithDP/ShirtColors.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace CustomClassesWithDP
{
    public enum ShirtColors
    {
        None,
        White,
        Red,
        Green,
        Yellow
    }
}

<|start_filename|>Accessibility/WindowMove/WindowMove.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace WindowMove
{
    /// <summary>
    ///     WindowMove application.
    /// </summary>
    public class WindowMove : Application
    {
        private readonly string _targetApplication = "Notepad.exe";
        private StringBuilder _feedbackText = new StringBuilder();
        private DockPanel _informationPanel;
        private Button _moveTarget;
        private Point _targetLocation;
        private AutomationElement _targetWindow;
        private TransformPattern _transformPattern;
        private WindowPattern _windowPattern;
        private TextBox _xCoordinate;
        private TextBox _yCoordinate;

        /// <summary>
        ///     The Startup handler.
        /// </summary>
        /// <param name="e">The event arguments</param>
        protected override void OnStartup(StartupEventArgs e)
        {
            // Start the WindowMove client.
            CreateWindow();

            try
            {
                // Obtain an AutomationElement from the target window handle.
                _targetWindow = StartTargetApp(_targetApplication);

                // Does the automation element exist?
                if (_targetWindow == null)
                {
                    Feedback("No target.");
                    return;
                }
                Feedback("Found target.");

                // find current location of our window
                _targetLocation = _targetWindow.Current.BoundingRectangle.Location;

                // Obtain required control patterns from our automation element
                _windowPattern = GetControlPattern(_targetWindow,
                    WindowPattern.Pattern) as WindowPattern;

                if (_windowPattern == null) return;

                // Make sure our window is usable.
                // WaitForInputIdle will return before the specified time 
                // if the window is ready.
                if (false == _windowPattern.WaitForInputIdle(10000))
                {
                    Feedback("Object not responding in a timely manner.");
                    return;
                }
                Feedback("Window ready for user interaction");

                // Register for required events
                RegisterForEvents(
                    _targetWindow, WindowPattern.Pattern, TreeScope.Element);

                // Obtain required control patterns from our automation element
                _transformPattern =
                    GetControlPattern(_targetWindow, TransformPattern.Pattern)
                        as TransformPattern;

                if (_transformPattern == null) return;

                // Is the TransformPattern object moveable?
                if (_transformPattern.Current.CanMove)
                {
                    // Enable our WindowMove fields
                    _xCoordinate.IsEnabled = true;
                    _yCoordinate.IsEnabled = true;
                    _moveTarget.IsEnabled = true;

                    // Move element
                    _transformPattern.Move(0, 0);
                }
                else
                {
                    Feedback("Wndow is not moveable.");
                }
            }
            catch (ElementNotAvailableException)
            {
                Feedback("Client window no longer available.");
            }
            catch (InvalidOperationException)
            {
                Feedback("Client window cannot be moved.");
            }
            catch (Exception exc)
            {
                Feedback(exc.ToString());
            }
        }

        /// <summary>
        ///     Start the WindowMove client.
        /// </summary>
        private void CreateWindow()
        {
            var window = new Window();
            var sp = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            var txtX = new TextBlock
            {
                Text = "X-coordinate: ",
                VerticalAlignment = VerticalAlignment.Center
            };

            _xCoordinate = new TextBox
            {
                Text = "0",
                IsEnabled = false,
                MaxLines = 1,
                MaxLength = 4,
                Margin = new Thickness(10, 0, 10, 0)
            };

            var txtY = new TextBlock
            {
                Text = "Y-coordinate: ",
                VerticalAlignment = VerticalAlignment.Center
            };

            _yCoordinate = new TextBox
            {
                Text = "0",
                IsEnabled = false,
                MaxLines = 1,
                MaxLength = 4,
                Margin = new Thickness(10, 0, 10, 0)
            };

            _moveTarget = new Button
            {
                IsEnabled = false,
                Width = 100,
                Content = "Move Window"
            };
            _moveTarget.Click += btnMove_Click;

            sp.Children.Add(txtX);
            sp.Children.Add(_xCoordinate);
            sp.Children.Add(txtY);
            sp.Children.Add(_yCoordinate);
            sp.Children.Add(_moveTarget);

            _informationPanel = new DockPanel {LastChildFill = false};
            DockPanel.SetDock(sp, Dock.Top);
            _informationPanel.Children.Add(sp);

            window.Content = _informationPanel;
            window.Show();
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Provides feedback in the client.
        /// </summary>
        /// <param name="message">The string to display.</param>
        /// <remarks>
        ///     Since the events may happen on a different thread than the
        ///     client we need to use a Dispatcher delegate to handle them.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void Feedback(string message)
        {
            // Check if we need to call BeginInvoke.
            if (Dispatcher.CheckAccess() == false)
            {
                // Pass the same function to BeginInvoke,
                // but the call would come on the correct
                // thread and InvokeRequired will be false.
                Dispatcher.BeginInvoke(
                    DispatcherPriority.Send,
                    new FeedbackDelegate(Feedback),
                    message);
                return;
            }
            var textElement = new TextBlock {Text = message};
            DockPanel.SetDock(textElement, Dock.Top);
            _informationPanel.Children.Add(textElement);
        }

        /// <summary>
        ///     Handles the 'Move' button invoked event.
        ///     By default, the Move method does not allow an object
        ///     to be moved completely off-screen.
        /// </summary>
        /// <param name="src">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void btnMove_Click(object src, RoutedEventArgs e)
        {
            try
            {
                // If coordinate left blank, substitute 0
                if (_xCoordinate.Text == "") _xCoordinate.Text = "0";
                if (_yCoordinate.Text == "") _yCoordinate.Text = "0";

                // Reset background colours
                _xCoordinate.Background = Brushes.White;
                _yCoordinate.Background = Brushes.White;

                if (_windowPattern.Current.WindowVisualState ==
                    WindowVisualState.Minimized)
                    _windowPattern.SetWindowVisualState(WindowVisualState.Normal);

                var x = double.Parse(_xCoordinate.Text);
                var y = double.Parse(_yCoordinate.Text);

                // Should validate the requested screen location
                if ((x < 0) ||
                    (x >= (SystemParameters.WorkArea.Width -
                           _targetWindow.Current.BoundingRectangle.Width)))
                {
                    Feedback("X-coordinate would place the window all or partially off-screen.");
                    _xCoordinate.Background = Brushes.Yellow;
                }

                if ((y < 0) ||
                    (y >= (SystemParameters.WorkArea.Height -
                           _targetWindow.Current.BoundingRectangle.Height)))
                {
                    Feedback("Y-coordinate would place the window all or partially off-screen.");
                    _yCoordinate.Background = Brushes.Yellow;
                }

                // transformPattern was obtained from the target window.
                _transformPattern.Move(x, y);
            }
            catch (ElementNotAvailableException)
            {
                Feedback("Client window no longer available.");
            }
            catch (InvalidOperationException)
            {
                Feedback("Client window cannot be moved.");
            }
        }

        /// <summary>
        ///     Update client controls based on target location changes.
        /// </summary>
        /// <param name="src">The object that raised the event.</param>
        private void UpdateClientControls(object src)
        {
            // If window is minimized, no need to report new screen coordinates
            if (_windowPattern.Current.WindowVisualState == WindowVisualState.Minimized)
                return;

            var ptCurrent =
                ((AutomationElement) src).Current.BoundingRectangle.Location;
            if (_targetLocation != ptCurrent)
            {
                Feedback("Window moved from " + _targetLocation +
                         " to " + ptCurrent);
                _targetLocation = ptCurrent;
            }
            if (_targetLocation.X != double.Parse(_xCoordinate.Text))
            {
                Feedback("Alert: Final X-coordinate not equal to requested X-coordinate.");
                _xCoordinate.Text = _targetLocation.X.ToString(CultureInfo.InvariantCulture);
            }
            if (_targetLocation.Y != double.Parse(_yCoordinate.Text))
            {
                Feedback("Alert: Final Y-coordinate not equal to requested Y-coordinate.");
                _yCoordinate.Text = _targetLocation.Y.ToString(CultureInfo.InvariantCulture);
            }
        }

        /// <summary>
        ///     Window move event handler.
        /// </summary>
        /// <param name="src">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void OnWindowMove(object src, AutomationPropertyChangedEventArgs e)
        {
            // Pass the same function to BeginInvoke.
            Dispatcher.BeginInvoke(
                DispatcherPriority.Send,
                new ClientControlsDelegate(UpdateClientControls), src);
        }

        /// <summary>
        ///     Starts the target application.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <returns>The target automation element.</returns>
        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        private AutomationElement StartTargetApp(string app)
        {
            try
            {
                // Start application.
                var p = Process.Start(app);
                if (p.WaitForInputIdle(20000))
                    Feedback("Window ready for user interaction");
                else return null;

                // Give application a second to startup.
                Thread.Sleep(2000);

                // Return the automation element
                return AutomationElement.FromHandle(p.MainWindowHandle);
            }
            catch (ArgumentException e)
            {
                Feedback(e.ToString());
                return null;
            }
            catch (Win32Exception e)
            {
                Feedback(e.ToString());
                return null;
            }
        }

        /// <summary>
        ///     Gets a specified control pattern.
        /// </summary>
        /// <param name="ae">
        ///     The automation element we want to obtain the control pattern from.
        /// </param>
        /// <param name="ap">The control pattern of interest.</param>
        /// <returns>A ControlPattern object.</returns>
        private object GetControlPattern(
            AutomationElement ae, AutomationPattern ap)
        {
            object oPattern = null;

            if (false == ae.TryGetCurrentPattern(ap, out oPattern))
            {
                Feedback("Object does not support the " +
                         ap.ProgrammaticName + " Pattern");
                return null;
            }

            Feedback("Object supports the " +
                     ap.ProgrammaticName + " Pattern.");

            return oPattern;
        }

        /// <summary>
        ///     Register for events of interest.
        /// </summary>
        /// <param name="ae">The automation element of interest.</param>
        /// <param name="ap">The control pattern of interest.</param>
        /// <param name="ts">The tree scope of interest.</param>
        private void RegisterForEvents(AutomationElement ae,
            AutomationPattern ap, TreeScope ts)
        {
            if (ap.Id == WindowPattern.Pattern.Id)
            {
                // The WindowPattern Exposes an element's ability 
                // to change its on-screen position or size.

                // The following code shows an example of listening for the 
                // BoundingRectangle property changed event on the window.
                Feedback("Start listening for WindowMove events for the control.");

                // Define an AutomationPropertyChangedEventHandler delegate to 
                // listen for window moved events.
                var moveHandler =
                    new AutomationPropertyChangedEventHandler(OnWindowMove);

                Automation.AddAutomationPropertyChangedEventHandler(
                    ae, ts, moveHandler,
                    AutomationElement.BoundingRectangleProperty);
            }
        }

        /// <summary>
        ///     Window shut down event handler.
        /// </summary>
        /// <param name="e">The exit event arguments.</param>
        protected override void OnExit(ExitEventArgs e)
        {
            Automation.RemoveAllEventHandlers();
            base.OnExit(e);
        }

        // Delegates for updating the client UI based on target application events.
        private delegate void FeedbackDelegate(string message);

        private delegate void ClientControlsDelegate(object src);

        /// <summary>
        ///     Launch the sample application.
        /// </summary>
        internal sealed class TestMain
        {
            [STAThread]
            private static void Main()
            {
                // Create an instance of the sample class
                var app = new WindowMove();
                app.Run();
            }
        }
    }
}

<|start_filename|>Graphics/BitmapMetadata/App.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace BitmapMetadata
{
    public class App : Application
    {
        private Window _mainWindow;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            CreateAndShowMainWindow();
        }

        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {Title = "Image Metadata"};

            Stream pngStream = new FileStream("smiley.png", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            var pngDecoder = new PngBitmapDecoder(pngStream, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);
            var pngFrame = pngDecoder.Frames[0];
            var pngInplace = pngFrame.CreateInPlaceBitmapMetadataWriter();
            if (pngInplace.TrySave())
            {
                pngInplace.SetQuery("/Text/Description", "Have a nice day.");
            }
            pngStream.Close();

            // Draw the Image
            var myImage = new Image
            {
                Source = new BitmapImage(new Uri("smiley.png", UriKind.Relative)),
                Stretch = Stretch.None,
                Margin = new Thickness(20)
            };


            // Add the metadata of the bitmap image to the text block.
            var myTextBlock = new TextBlock
            {
                Text =
                    "The Description metadata of this image is: " + pngInplace.GetQuery("/Text/Description")
            };

            // Define a StackPanel to host Controls
            var myStackPanel = new StackPanel
            {
                Orientation = Orientation.Vertical,
                Height = 200,
                VerticalAlignment = VerticalAlignment.Top,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            _mainWindow.Content = myStackPanel;
            _mainWindow.Show();
        }
    }

    // Define a static entry class
}

<|start_filename|>Data Binding/BindValidation/MyDataSource.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace BindValidation
{
    public class MyDataSource
    {
        public MyDataSource()
        {
            Age = 0;
            Age2 = 0;
        }

        public int Age { get; set; }
        public int Age2 { get; set; }
        public int Age3 { get; set; }
    }
}

<|start_filename|>Input and Commands/CustomRoutedCommand/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace CustomRoutedCommand
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static RoutedCommand ColorCmd = new RoutedCommand();

        public MainWindow()
        {
            InitializeComponent();
        }

        // ExecutedRoutedEventHandler for the custom color command.
        private void ColorCmdExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var target = e.Source as Panel;
            if (target != null)
            {
                target.Background = target.Background == Brushes.AliceBlue ? Brushes.LemonChiffon : Brushes.AliceBlue;
            }
        }

        // CanExecuteRoutedEventHandler for the custom color command.
        private void ColorCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (e.Source is Panel)
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }
    }
}

<|start_filename|>Data Binding/Colors/LuminanceToBrushConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace Colors
{
    // One-way conversion between Luminance and Brush - used to draw text in
    // a color tile using a color that contrasts with the background

    public class LuminanceToBrushConverter : IValueConverter
    {
        object IValueConverter.Convert(object o, Type type, object parameter, CultureInfo culture)
        {
            var luminance = (double) o;
            return (luminance < 0.5) ? Brushes.White : Brushes.Black;
        }

        object IValueConverter.ConvertBack(object o, Type type, object parameter, CultureInfo culture) => null;
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/EmailDialog.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace StickyNotesDemo
{
    /// <summary>
    ///     Interaction logic for EmailDialog.xaml
    /// </summary>
    public class EmailDialog : Window
    {
        private TextBox _body;
        private TextBox _from;
        private PasswordBox _password;
        private TextBox _subj;
        private TextBox _to;

        public EmailDialog(string message)
        {
            WindowStyle = WindowStyle.ToolWindow;
            Height = Width = 600;
            Title = "Email";
            Background = Window2.ChangeBackgroundColor(Colors.BlanchedAlmond);


            if (File.Exists("MailServerInfo"))
            {
                CreateMailUi(message);
                ShowDialog();
            }
            else
            {
                var msd = new MailSettingsDialog();
                msd.Show();
            }
        }

        private void CreateMailUi(string message)
        {
            var sp = new StackPanel {Background = Brushes.Transparent};

            var g = new Grid {Background = Brushes.Transparent};
            var rdef1 = new RowDefinition();
            var rdef2 = new RowDefinition();
            var rdef3 = new RowDefinition();
            var rdef4 = new RowDefinition();
            var rdef5 = new RowDefinition();
            g.RowDefinitions.Add(rdef1);
            g.RowDefinitions.Add(rdef2);
            g.RowDefinitions.Add(rdef3);
            g.RowDefinitions.Add(rdef4);
            g.RowDefinitions.Add(rdef5);

            var cd1 = new ColumnDefinition();
            var gdl = new GridLength(80);
            cd1.Width = gdl;
            var cd2 = new ColumnDefinition();
            g.ColumnDefinitions.Add(cd1);
            g.ColumnDefinitions.Add(cd2);

            var l00 = new Label
            {
                Background = Brushes.Transparent,
                Content = "Login:"
            };
            var login = new TextBox();
            var email = GetEmail();
            var index = email.IndexOf('@');
            if (index < 0)
            {
                login.Text = "Pls correct incorrect email in Mail settings";
            }
            else
            {
                var loginText = email.Substring(0, index);
                login.Text = loginText;
            }

            Grid.SetRow(l00, 0);
            Grid.SetColumn(l00, 0);
            Grid.SetRow(login, 0);
            Grid.SetColumn(login, 1);

            var l0 = new Label
            {
                Background = Brushes.Transparent,
                Content = "Password:"
            };
            _password = new PasswordBox {PasswordChar = '*'};


            Grid.SetRow(l0, 1);
            Grid.SetColumn(l0, 0);
            Grid.SetRow(_password, 1);
            Grid.SetColumn(_password, 1);

            var l1 = new Label
            {
                Background = Brushes.Transparent,
                Content = "To:"
            };
            _to = new TextBox();

            Grid.SetRow(l1, 2);
            Grid.SetColumn(l1, 0);
            Grid.SetRow(_to, 2);
            Grid.SetColumn(_to, 1);

            var l2 = new Label
            {
                Background = Brushes.Transparent,
                Content = "From:"
            };
            _from = new TextBox {Text = email};

            Grid.SetRow(l2, 3);
            Grid.SetColumn(l2, 0);
            Grid.SetRow(_from, 3);
            Grid.SetColumn(_from, 1);

            var l5 = new Label
            {
                Background = Brushes.Transparent,
                Content = "Subj:"
            };
            _subj = new TextBox();

            Grid.SetRow(l5, 4);
            Grid.SetColumn(l5, 0);
            Grid.SetRow(_subj, 4);
            Grid.SetColumn(_subj, 1);

            g.Children.Add(l00);
            g.Children.Add(login);
            g.Children.Add(l0);
            g.Children.Add(_password);
            g.Children.Add(l1);
            g.Children.Add(_to);
            g.Children.Add(l2);
            g.Children.Add(_from);
            g.Children.Add(l5);
            g.Children.Add(_subj);

            _body = new TextBox
            {
                Text = message,
                AcceptsReturn = true,
                TextWrapping = TextWrapping.Wrap,
                Height = 250,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto
            };

            var ok = new Button
            {
                Content = "Ok",
                HorizontalAlignment = HorizontalAlignment.Right
            };
            ok.Click += ok_Click;

            sp.Children.Add(g);
            sp.Children.Add(_body);
            sp.Children.Add(ok);

            Height = 500;
            Content = sp;
        }

        private void ok_Click(object sender, RoutedEventArgs e)
        {
            var fs = new FileStream("MailServerInfo", FileMode.Open);
            var reader = new StreamReader(fs);
            var server = reader.ReadLine();
            var account = reader.ReadLine();
            var index = account.IndexOf('@');
            index = (index < 0) ? 0 : index;
            account = account.Substring(0, index);
            var portString = reader.ReadLine();
            var port = (portString != string.Empty) ? int.Parse(portString) : 25;

            var sslCheck = reader.ReadLine().Contains("true") ? true : false;

            var toEmail = _to.Text;
            var fromEmail = _from.Text;
            var password = <PASSWORD>;
            var subject = _subj.Text;
            var bodyMessage = _body.Text;

            reader.Close();
            fs.Close();

            var email = new Email(server, account, port, sslCheck, toEmail, fromEmail, password, bodyMessage, this,
                subject);
        }

        private string GetEmail()
        {
            var fs = new FileStream("MailServerInfo", FileMode.Open);
            var reader = new StreamReader(fs);
            reader.ReadLine();
            var str = reader.ReadLine();
            reader.Close();
            fs.Close();
            return str;
        }
    }
}

<|start_filename|>Visual Layer/VisualsHitTesting/MyWindow.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using System.Windows.Media;

namespace SDKSample
{
    internal class MyWindow
    {
        // Constant values from the "winuser.h" header file.
        internal const int WsChild = 0x40000000,
            WsVisible = 0x10000000;

        // Constant values from the "winuser.h" header file.
        internal const int WmLbuttonup = 0x0202,
            WmRbuttonup = 0x0205;

        public static int Width = Form.ActiveForm.ClientSize.Width;
        public static int Height = Form.ActiveForm.ClientSize.Height;
        public static HwndSource MyHwndSource;
        public static bool TopmostLayer = true;
        public static bool ChangeColor;

        public static void FillWithCircles(IntPtr parentHwnd)
        {
            // Fill the client area of the form with randomly placed circles.
            for (var i = 0; i < 200; i++)
            {
                CreateShape(parentHwnd);
            }
        }

        public static void CreateShape(IntPtr parentHwnd)
        {
            // Create an instance of the shape.
            var myShape = new MyShape();

            // Determine whether the host container window has been created.
            if (MyHwndSource == null)
            {
                // Create the host container window for the visual objects.
                CreateHostHwnd(parentHwnd);

                // Associate the shape with the host container window.
                MyHwndSource.RootVisual = myShape;
            }
            else
            {
                // Assign the shape as a child of the root visual.
                ((ContainerVisual) MyHwndSource.RootVisual).Children.Add(myShape);
            }
        }

        internal static void CreateHostHwnd(IntPtr parentHwnd)
        {
            // Set up the parameters for the host hwnd.
            var parameters = new HwndSourceParameters("Visual Hit Test", Width, Height)
            {
                WindowStyle = WsVisible | WsChild
            };
            parameters.SetPosition(0, 24);
            parameters.ParentWindow = parentHwnd;
            parameters.HwndSourceHook = ApplicationMessageFilter;

            // Create the host hwnd for the visuals.
            MyHwndSource = new HwndSource(parameters);

            // Set the hwnd background color to the form's background color.
            MyHwndSource.CompositionTarget.BackgroundColor = Brushes.OldLace.Color;
        }

        internal static IntPtr ApplicationMessageFilter(
            IntPtr hwnd, int message, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Handle messages passed to the visual.
            switch (message)
            {
                // Handle the left and right mouse button up messages.
                case WmLbuttonup:
                case WmRbuttonup:
                    var pt = new Point
                    {
                        X = (uint) lParam & 0x0000ffff,
                        Y = (uint) lParam >> 16
                    };
                    // LOWORD = x
                    // HIWORD = y
                    MyShape.OnHitTest(pt, message);
                    break;
            }

            return IntPtr.Zero;
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/FunctionMesh.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace GraphingCalculatorDemo.Parser
{
    public class FunctionMesh
    {
        private double _du;
        private double _dv;
        // - - - - - - - - - - - - - - - - - - - - - - - - - -

        private IExpression _fx;
        private IExpression _fxDu;
        private IExpression _fxDv;
        private IExpression _fy;
        private IExpression _fyDu;
        private IExpression _fyDv;
        private IExpression _fz;
        private IExpression _fzDu;
        private IExpression _fzDv;
        private ArrayList _indices;
        private int _lengthX;
        private int _lengthY;
        private Vector3D[,] _normals;
        private Point3D[,] _positions;
        private Point[,] _textureCoords;
        protected double UMax;
        // - - - - - - - - - - - - - - - - - - - - - - - - - -

        protected double UMin;
        protected double VMax;
        protected double VMin;

        protected FunctionMesh()
        {
            // We open this class up for extension only by those who promise to call Init
            //  at some time during their constructors.  If they do not, CreateMesh will fail.
        }

        public FunctionMesh(
            string fx,
            string fy,
            string fz,
            double uMin,
            double uMax,
            double vMin,
            double vMax
            )
        {
            Init(
                FunctionParser.Parse(fx),
                FunctionParser.Parse(fy),
                FunctionParser.Parse(fz),
                uMin,
                uMax,
                vMin,
                vMax
                );
        }

        protected Point3D this[int x, int y] => _positions[x, y];

        protected void Init(
            IExpression fx,
            IExpression fy,
            IExpression fz,
            double uMin,
            double uMax,
            double vMin,
            double vMax
            )
        {
            _fx = fx.Simplify();
            _fy = fy.Simplify();
            _fz = fz.Simplify();

            _fxDu = _fx.Differentiate("u").Simplify();
            _fxDv = _fx.Differentiate("v").Simplify();
            _fyDu = _fy.Differentiate("u").Simplify();
            _fyDv = _fy.Differentiate("v").Simplify();
            _fzDu = _fz.Differentiate("u").Simplify();
            _fzDv = _fz.Differentiate("v").Simplify();

            UMin = uMin;
            UMax = uMax;
            VMin = vMin;
            VMax = vMax;
        }

        /// <summary>
        ///     Creates a mesh with a horizontal and vertical resolution indicated
        ///     by the input parameters.  It will generate
        ///     (precisionU-1)*(precisionV-1) quads.
        /// </summary>
        public MeshGeometry3D CreateMesh(int precisionU, int precisionV)
        {
            _lengthX = precisionU;
            _lengthY = precisionV;
            _du = (UMax - UMin)/(precisionU - 1);
            _dv = (VMax - VMin)/(precisionV - 1);

            _positions = new Point3D[_lengthX, _lengthY];
            _normals = new Vector3D[_lengthX, _lengthY];
            _textureCoords = new Point[_lengthX, _lengthY];
            _indices = new ArrayList();

            var v = VMin;
            for (var y = 0; y < _lengthY; y++)
            {
                var u = UMin;
                if (y == _lengthY - 1)
                {
                    v = VMax;
                }
                for (var x = 0; x < _lengthX; x++)
                {
                    if (x == _lengthX - 1)
                    {
                        u = UMax;
                    }
                    VariableExpression.Define("u", u);
                    VariableExpression.Define("v", v);
                    _positions[x, y] = Evaluate();
                    _normals[x, y] = GetNormal(u, v);
                    u += _du;
                }
                v += _dv;
            }
            VariableExpression.Undefine("u");
            VariableExpression.Undefine("v");

            SetTextureCoordinates();
            SetIndices();

            var mesh = new MeshGeometry3D();
            for (var y = 0; y < _lengthY; y++)
            {
                for (var x = 0; x < _lengthX; x++)
                {
                    mesh.Positions.Add(_positions[x, y]);
                    mesh.Normals.Add(_normals[x, y]);
                    mesh.TextureCoordinates.Add(_textureCoords[x, y]);
                }
            }
            mesh.TriangleIndices = new Int32Collection();
            foreach (int index in _indices)
                mesh.TriangleIndices.Add(index);

            return mesh;
        }

        /// <summary>
        ///     Evaluates the mesh position at the indicated parameters.
        /// </summary>
        private Point3D Evaluate()
        {
            var p = new Point3D
            {
                X = _fx.Evaluate(),
                Y = _fy.Evaluate(),
                Z = _fz.Evaluate()
            };


            return p;
        }

        /// <summary>
        ///     Returns the normal of the mesh at the indicated parameters.
        /// </summary>
        private Vector3D GetNormal(double u, double v)
        {
            var a = ToVector3D(_fxDu, _fyDu, _fzDu);
            var b = ToVector3D(_fxDv, _fyDv, _fzDv);

            var normal = Vector3D.CrossProduct(a, b);
            normal.Normalize();

            if (double.IsNaN(normal.X) || double.IsNaN(normal.Y) || double.IsNaN(normal.Z))
            {
                // This is sort-of what <NAME> said to do in his paper, I think...
                // It seems to work okay.

                // We take a second derivative of the equation, this time using the other variable,
                //  then we re-evaluate it.  The direction of the normal is dependent on where we
                //  are in the mesh grid
                if (a.Length < b.Length)
                {
                    a = TryToVector3DAgain(_fxDu, _fyDu, _fzDu, "v");
                    normal = v < (VMax + VMin)/2 ? Vector3D.CrossProduct(a, b) : Vector3D.CrossProduct(b, a);
                }
                else
                {
                    b = TryToVector3DAgain(_fxDv, _fyDv, _fzDv, "u");
                    normal = u < (UMax + UMin)/2 ? Vector3D.CrossProduct(a, b) : Vector3D.CrossProduct(b, a);
                }

                normal.Normalize();
                if (double.IsNaN(normal.X) || double.IsNaN(normal.Y) || double.IsNaN(normal.Z))
                {
                    Debug.Assert(false, "Persistent degenerate normal.  Bailing out!");
                    normal = new Vector3D(0, 1, 0);
                }
            }
            return normal;
        }

        private Vector3D ToVector3D(
            IExpression fx,
            IExpression fy,
            IExpression fz
            ) => new Vector3D(fx.Evaluate(), fy.Evaluate(), fz.Evaluate());

        private Vector3D TryToVector3DAgain(
            IExpression fx,
            IExpression fy,
            IExpression fz,
            string otherVar
            )
        {
            var fxDn = fx.Differentiate(otherVar).Simplify();
            var fyDn = fy.Differentiate(otherVar).Simplify();
            var fzDn = fz.Differentiate(otherVar).Simplify();

            return ToVector3D(fxDn, fyDn, fzDn);
        }

        private void SetTextureCoordinates()
        {
            var scaleU = 1.0/(_lengthX - 1);
            var scaleV = 1.0/(_lengthY - 1);
            var v = 0.0;

            for (var y = 0; y < _lengthY; y++)
            {
                var u = 0.0;
                if (y == _lengthY - 1)
                {
                    v = 1.0;
                }
                for (var x = 0; x < _lengthX; x++)
                {
                    if (x == _lengthX - 1)
                    {
                        u = 1.0;
                    }
                    // WPF textures things upside down
                    _textureCoords[x, y] = new Point(u, 1.0 - v);
                    u += scaleU;
                }
                v += scaleV;
            }
        }

        private void SetIndices()
        {
            // Connect the dots (vertices)...

            for (var y = 0; y < _lengthY - 1; y++)
            {
                var rowX = y*_lengthX;
                var nextRowX = rowX + _lengthX;
                for (var x = 0; x < _lengthX - 1; x++)
                {
                    _indices.Add(rowX + x);
                    _indices.Add(rowX + x + 1);
                    _indices.Add(nextRowX + x);
                    _indices.Add(nextRowX + x + 1);
                    _indices.Add(nextRowX + x);
                    _indices.Add(rowX + x + 1);
                }
            }
            Debug.Assert(_indices.Count == (_lengthX - 1)*(_lengthY - 1)*6, "indices = " + _indices.Count);
        }
    }
}

<|start_filename|>Sample Applications/PhotoStoreDemo/Shirt.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Media.Imaging;

namespace PhotoStoreDemo
{
    public class Shirt : PrintBase
    {
        public Shirt(BitmapSource photo) : base(photo, "T-Shirt", 14.99)
        {
        }
    }
}

<|start_filename|>Sample Applications/ExpenseIt/ExpenseItDemo/ExpenseReport.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;

// EventHandler
// ObservableCollection

// INotifyPropertyChanged, PropertyChangedEventArgs

namespace ExpenseItDemo
{
    public class ExpenseReport : INotifyPropertyChanged
    {
        private string _alias;
        private string _costCenter;
        private string _employeeNumber;
        private int _totalExpenses;

        public ExpenseReport()
        {
            LineItems = new LineItemCollection();
            LineItems.LineItemCostChanged += OnLineItemCostChanged;
        }

        public string Alias
        {
            get { return _alias; }
            set
            {
                _alias = value;
                OnPropertyChanged("Alias");
            }
        }

        public string CostCenter
        {
            get { return _costCenter; }
            set
            {
                _costCenter = value;
                OnPropertyChanged("CostCenter");
            }
        }

        public string EmployeeNumber
        {
            get { return _employeeNumber; }
            set
            {
                _employeeNumber = value;
                OnPropertyChanged("EmployeeNumber");
            }
        }

        public int TotalExpenses
        {
            // calculated property, no setter
            get
            {
                RecalculateTotalExpense();
                return _totalExpenses;
            }
        }

        public LineItemCollection LineItems { get; }
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnLineItemCostChanged(object sender, EventArgs e)
        {
            OnPropertyChanged("TotalExpenses");
        }

        private void RecalculateTotalExpense()
        {
            _totalExpenses = 0;
            foreach (var item in LineItems)
                _totalExpenses += item.Cost;
        }

        private void OnPropertyChanged(string propName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }
}

<|start_filename|>Migration and Interoperability/WindowsFormsHostingWpfControl/FormsApp/Form1.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Media;
using WPFControls;

namespace FormsApp
{
    partial class Form1 : Form
    {
        private ElementHost _ctrlHost;
        private SolidColorBrush _initBackBrush;
        private FontFamily _initFontFamily;
        private double _initFontSize;
        private FontStyle _initFontStyle;
        private FontWeight _initFontWeight;
        private SolidColorBrush _initForeBrush;
        private MyControl _wpfAddressCtrl;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _ctrlHost = new ElementHost {Dock = DockStyle.Fill};
            panel1.Controls.Add(_ctrlHost);
            _wpfAddressCtrl = new MyControl();
            _wpfAddressCtrl.InitializeComponent();
            _ctrlHost.Child = _wpfAddressCtrl;

            _wpfAddressCtrl.OnButtonClick +=
                avAddressCtrl_OnButtonClick;
            _wpfAddressCtrl.Loaded += avAddressCtrl_Loaded;
        }

        private void avAddressCtrl_Loaded(object sender, EventArgs e)
        {
            _initBackBrush = _wpfAddressCtrl.MyControlBackground;
            _initForeBrush = _wpfAddressCtrl.MyControlForeground;
            _initFontFamily = _wpfAddressCtrl.MyControlFontFamily;
            _initFontSize = _wpfAddressCtrl.MyControlFontSize;
            _initFontWeight = _wpfAddressCtrl.MyControlFontWeight;
            _initFontStyle = _wpfAddressCtrl.MyControlFontStyle;
        }

        private void avAddressCtrl_OnButtonClick(
            object sender,
            MyControlEventArgs args)
        {
            if (args.IsOk)
            {
                lblAddress.Text = @"Street Address: " + args.MyStreetAddress;
                lblCity.Text = @"City: " + args.MyCity;
                lblName.Text = "Name: " + args.MyName;
                lblState.Text = "State: " + args.MyState;
                lblZip.Text = "Zip: " + args.MyZip;
            }
            else
            {
                lblAddress.Text = "Street Address: ";
                lblCity.Text = "City: ";
                lblName.Text = "Name: ";
                lblState.Text = "State: ";
                lblZip.Text = "Zip: ";
            }
        }

        private void radioBackgroundOriginal_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlBackground = _initBackBrush;
        }

        private void radioBackgroundLightGreen_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlBackground = new SolidColorBrush(Colors.LightGreen);
        }

        private void radioBackgroundLightSalmon_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlBackground = new SolidColorBrush(Colors.LightSalmon);
        }

        private void radioForegroundOriginal_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlForeground = _initForeBrush;
        }

        private void radioForegroundRed_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlForeground = new SolidColorBrush(Colors.Red);
        }

        private void radioForegroundYellow_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlForeground = new SolidColorBrush(Colors.Yellow);
        }

        private void radioFamilyOriginal_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontFamily = _initFontFamily;
        }

        private void radioFamilyTimes_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontFamily = new FontFamily("Times New Roman");
        }

        private void radioFamilyWingDings_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontFamily = new FontFamily("WingDings");
        }

        private void radioSizeOriginal_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontSize = _initFontSize;
        }

        private void radioSizeTen_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontSize = 10;
        }

        private void radioSizeTwelve_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontSize = 12;
        }

        private void radioStyleOriginal_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontStyle = _initFontStyle;
        }

        private void radioStyleItalic_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontStyle = FontStyles.Italic;
        }

        private void radioWeightOriginal_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontWeight = _initFontWeight;
        }

        private void radioWeightBold_CheckedChanged(object sender, EventArgs e)
        {
            _wpfAddressCtrl.MyControlFontWeight = FontWeights.Bold;
        }
    }
}

// </snippet1>

<|start_filename|>Data Binding/DataTemplatingIntro/Tasks.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;

namespace DataTemplatingIntro
{
    public class Tasks : ObservableCollection<Task>
    {
        public Tasks()
        {
            Add(new Task("Groceries", "Pick up Groceries and Detergent", 2, TaskType.Home));
            Add(new Task("Laundry", "Do my Laundry", 2, TaskType.Home));
            Add(new Task("Email", "Email clients", 1, TaskType.Work));
            Add(new Task("Clean", "Clean my office", 3, TaskType.Work));
            Add(new Task("Dinner", "Get ready for family reunion", 1, TaskType.Home));
            Add(new Task("Proposals", "Review new budget proposals", 2, TaskType.Work));
        }
    }
}

<|start_filename|>Data Binding/CompositeCollections/GreekGods.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;

namespace CompositeCollections
{
    public class GreekGods : ObservableCollection<GreekGod>
    {
        public GreekGods()
        {
            Add(new GreekGod("Aphrodite"));
            Add(new GreekGod("Apollo"));
            Add(new GreekGod("Ares"));
            Add(new GreekGod("Artemis"));
            Add(new GreekGod("Athena"));
            Add(new GreekGod("Demeter"));
            Add(new GreekGod("Dionysus"));
            Add(new GreekGod("Hephaestus"));
            Add(new GreekGod("Hera"));
            Add(new GreekGod("Hermes"));
            Add(new GreekGod("Poseidon"));
            Add(new GreekGod("Zeus"));
        }
    }
}

<|start_filename|>Animation/Per-FrameAnimation/FrameIndependentFollow/FrameIndependentFollowExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace PerFrameAnimation
{
    /// <summary>
    ///     Interaction logic for FrameIndependentFollowExample.xaml
    /// </summary>
    public partial class FrameIndependentFollowExample : Page
    {
        private Point _lastMousePosition = new Point(0, 0);
        //timing variables
        private TimeSpan _lastRender;
        private Vector _rectangleVelocity = new Vector(0, 0);

        public FrameIndependentFollowExample()
        {
            InitializeComponent();
            _lastRender = TimeSpan.FromTicks(DateTime.Now.Ticks);
            CompositionTarget.Rendering += UpdateRectangle;
            PreviewMouseMove += UpdateLastMousePosition;
        }

        private void UpdateRectangle(object sender, EventArgs e)
        {
            var renderArgs = (RenderingEventArgs) e;
            var deltaTime = (renderArgs.RenderingTime - _lastRender).TotalSeconds;
            _lastRender = renderArgs.RenderingTime;


            var location = new Point(Canvas.GetLeft(followRectangle), Canvas.GetTop(followRectangle));

            //find vector toward mouse location
            var toMouse = _lastMousePosition - location;

            //add a force toward the mouse to the rectangles velocity
            var followForce = 1.00;
            _rectangleVelocity += toMouse*followForce;

            //dampen the velocity to add stability
            var drag = 0.9;
            _rectangleVelocity *= drag;

            //update the new location from the velocity
            location += _rectangleVelocity*deltaTime;

            //set new position
            Canvas.SetLeft(followRectangle, location.X);
            Canvas.SetTop(followRectangle, location.Y);
        }

        private void UpdateLastMousePosition(object sender, MouseEventArgs e)
        {
            _lastMousePosition = e.GetPosition(containerCanvas);
        }
    }
}

<|start_filename|>Documents/Flow Content/ParagraphAndHyphenation/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace ParagraphAndHyphenation
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ToggleHyphenation(object sender, RoutedEventArgs args)
        {
            flowDoc.IsHyphenationEnabled = ((CheckBox) sender).IsChecked.Value;
        }

        private void ToggleOptimalParagraph(object sender, RoutedEventArgs args)
        {
            flowDoc.IsOptimalParagraphEnabled = ((CheckBox) sender).IsChecked.Value;
        }

        private void ToggleColumnFlex(object sender, RoutedEventArgs args)
        {
            flowDoc.IsColumnWidthFlexible = ((CheckBox) sender).IsChecked.Value;
        }

        private void ChangeColumnWidth(object sender, RoutedEventArgs args)
        {
            if (myGrid.Children.Contains(flowReader))
            {
                if (columnWidthSlider.Value == 0)
                {
                    flowDoc.ColumnWidth = 100;
                }
                else if (columnWidthSlider.Value == 1)
                {
                    flowDoc.ColumnWidth = 200;
                }
                else if (columnWidthSlider.Value == 2)
                {
                    flowDoc.ColumnWidth = 300;
                }
                else if (columnWidthSlider.Value == 3)
                {
                    flowDoc.ColumnWidth = 400;
                }
                else if (columnWidthSlider.Value == 4)
                {
                    flowDoc.ColumnWidth = 500;
                }
            }
        }

        private void ChangeColumnGap(object sender, RoutedEventArgs args)
        {
            if (myGrid.Children.Contains(flowReader))
            {
                if (columnGapSlider.Value == 0)
                {
                    flowDoc.ColumnGap = 5;
                }
                else if (columnGapSlider.Value == 1)
                {
                    flowDoc.ColumnGap = 10;
                }
                else if (columnGapSlider.Value == 2)
                {
                    flowDoc.ColumnGap = 15;
                }
                else if (columnGapSlider.Value == 3)
                {
                    flowDoc.ColumnGap = 20;
                }
                else if (columnGapSlider.Value == 4)
                {
                    flowDoc.ColumnGap = 25;
                }
            }
        }
    }
}

<|start_filename|>Migration and Interoperability/WPFHostingWin32Control/App.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.InteropServices;
using System.Windows;

namespace WPFHostingWin32Control
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [DllImport("comctl32.dll", EntryPoint = "InitCommonControls", CharSet = CharSet.Auto)]
        public static extern void InitCommonControls();

        private void ApplicationStartup(object sender, StartupEventArgs args)
        {
        }
    }
}

<|start_filename|>Input and Commands/TouchKeyboard/TouchKBRegister/App.xaml.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;

namespace TouchKBRegister
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            new MenuChild().Show();
            new MenuSibling().Show();
            new LotsOfStacking().Show();
            new SxSDecorators().Show();
        }
    }
}


<|start_filename|>Data Binding/DataTrigger/Place.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DataTrigger
{
    public class Place
    {
        public Place(string name, string state)
        {
            Name = name;
            State = state;
        }

        public string Name { get; set; }
        public string State { get; set; }
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/PropNames.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace StickyNotesDemo
{
    /// <summary>
    ///     Interaction logic for Dialog.xaml
    /// </summary>
    internal enum PropNames
    {
        BackgroundColor = 0,
        ForegroundColor,
        Alarm
    }
}

<|start_filename|>Elements/UsingElements/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace UsingElements
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Button _btn, _btn1, _btn2, _btn3;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void AddButton(object sender, MouseButtonEventArgs e)
        {
            sp1.Children.Clear();
            _btn = new Button {Content = "New Button"};
            sp1.Children.Add(_btn);
        }

        private void RemoveButton(object sender, MouseButtonEventArgs e)
        {
            if ((sp1.Children.IndexOf(_btn) >= 0) || (sp1.Children.IndexOf(_btn1) >= 0) ||
                (sp1.Children.IndexOf(_btn2) >= 0) || (sp1.Children.IndexOf(_btn3) >= 0))
            {
                sp1.Children.RemoveAt(0);
            }
        }

        private void InsertButton(object sender, MouseButtonEventArgs e)
        {
            sp1.Children.Clear();
            _btn = new Button {Content = "Click to insert button"};
            sp1.Children.Add(_btn);
            _btn.Click += (InsertControls);
            _btn1 = new Button {Content = "Click to insert button"};
            sp1.Children.Add(_btn1);
            _btn1.Click += (InsertControls);
        }

        private void InsertControls(object sender, RoutedEventArgs e)
        {
            _btn2 = new Button {Content = "Inserted Button"};
            sp1.Children.Insert(1, _btn2);
        }

        private void ShowIndex(object sender, MouseButtonEventArgs e)
        {
            sp1.Children.Clear();
            _btn = new Button {Content = "Click for index"};
            _btn.Click += (PrintIndex);
            sp1.Children.Add(_btn);

            _btn1 = new Button {Content = "Click for index"};
            sp1.Children.Add(_btn1);
            _btn1.Click += (PrintIndex1);

            _btn2 = new Button {Content = "Click for index"};
            sp1.Children.Add(_btn2);
            _btn2.Click += (PrintIndex2);

            _btn3 = new Button {Content = "Click for index"};
            sp1.Children.Add(_btn3);
            _btn3.Click += (PrintIndex3);
        }

        private void PrintIndex(object sender, RoutedEventArgs e)
        {
            _btn.Content = ((sp1.Children.IndexOf(_btn)).ToString());
        }

        private void PrintIndex1(object sender, RoutedEventArgs e)
        {
            _btn1.Content = ((sp1.Children.IndexOf(_btn1)).ToString());
        }

        private void PrintIndex2(object sender, RoutedEventArgs e)
        {
            _btn2.Content = ((sp1.Children.IndexOf(_btn2)).ToString());
        }

        private void PrintIndex3(object sender, RoutedEventArgs e)
        {
            _btn3.Content = ((sp1.Children.IndexOf(_btn3)).ToString());
        }

        private void ClearButtons(object sender, MouseButtonEventArgs e)
        {
            sp1.Children.Clear();
            _btn = new Button {Content = "Click to clear"};
            sp1.Children.Add(_btn);
            _btn.Click += (ClearControls);
            _btn1 = new Button {Content = "Click to clear"};
            sp1.Children.Add(_btn1);
            _btn1.Click += (ClearControls);
            _btn2 = new Button {Content = "Click to clear"};
            sp1.Children.Add(_btn2);
            _btn2.Click += (ClearControls);
            _btn3 = new Button {Content = "Click to clear"};
            sp1.Children.Add(_btn3);
            _btn3.Click += (ClearControls);
        }

        private void ClearControls(object sender, RoutedEventArgs e)
        {
            sp1.Children.Clear();
        }

        private void ContainsElement(object sender, RoutedEventArgs e)
        {
            var txt1 = new TextBlock();
            sp1.Children.Add(txt1);
            txt1.Text = "This StackPanel contains UIElement btn1: " + sp1.Children.Contains(_btn1);
        }

        private void GetItem(object sender, RoutedEventArgs e)
        {
            var txt2 = new TextBlock();
            sp1.Children.Add(txt2);
            txt2.Text = "UIElement at Index position [0] is " + sp1.Children[0];
        }

        private void GetCount(object sender, RoutedEventArgs e)
        {
            var txt3 = new TextBlock();
            sp1.Children.Add(txt3);
            txt3.Text = "UIElement Count is equal to " + sp1.Children.Count;
        }
    }
}

<|start_filename|>Graphics/Brushes/EnumPossibleValuesToStringArrayConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;
using System.Globalization;
using System.Windows.Data;

namespace Brushes
{
    [ValueConversion(typeof (object), typeof (string[]))]
    public class EnumPossibleValuesToStringArrayConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new ArrayList(Enum.GetNames(value.GetType()));

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => null;
    }
}

<|start_filename|>Sample Applications/FontDialog/FontFamilyListItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace FontDialog
{
    internal class FontFamilyListItem : TextBlock, IComparable
    {
        private readonly string _displayName;

        public FontFamilyListItem(FontFamily fontFamily)
        {
            _displayName = GetDisplayName(fontFamily);

            FontFamily = fontFamily;
            Text = _displayName;
            ToolTip = _displayName;

            // In the case of symbol font, apply the default message font to the text so it can be read.
            if (IsSymbolFont(fontFamily))
            {
                var range = new TextRange(ContentStart, ContentEnd);
                range.ApplyPropertyValue(FontFamilyProperty, SystemFonts.MessageFontFamily);
            }
        }

        int IComparable.CompareTo(object obj) => string.Compare(_displayName, obj.ToString(), true, CultureInfo.CurrentCulture);

        public override string ToString() => _displayName;

        internal static bool IsSymbolFont(FontFamily fontFamily)
        {
            foreach (var typeface in fontFamily.GetTypefaces())
            {
                GlyphTypeface face;
                if (typeface.TryGetGlyphTypeface(out face))
                {
                    return face.Symbol;
                }
            }
            return false;
        }

        internal static string GetDisplayName(FontFamily family) => NameDictionaryHelper.GetDisplayName(family.FamilyNames);
    }
}

<|start_filename|>Getting Started/Concepts/samps/propertychangenotification_samp.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace PropertyChangeNotification //needs to match the .xaml page
{
    public partial class Page1 : Page
    {
        private ToolTip _ttp;
        // This function checks the language filter settings to see which code to filter and also grays out tabs with no content
        public void CheckLang(object sender, EventArgs e)
        {
            if (xcsharpCheck.Content == null) // grays out xaml + c# tab
            {
                xamlcsharp.Background = Brushes.Gainsboro;
                xamlcsharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlcsharp, true);
                _ttp.Content = "This sample is not available in XAML + C#.";
                xamlcsharp.ToolTip = (_ttp);
                xamlcsharp.IsEnabled = false;
            }
            else if (xcsharpCheck.Content != null)
            {
                xamlcsharp.IsEnabled = true;
            }

            if (xvbCheck.Content == null) // grays out xaml + vb tab
            {
                xamlvb.Background = Brushes.Gainsboro;
                xamlvb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlvb, true);
                _ttp.Content = "This sample is not available in XAML + Visual Basic.NET";
                xamlvb.ToolTip = (_ttp);
                xamlvb.IsEnabled = false;
            }
            else if (xvbCheck.Content != null)
            {
                xamlvb.IsEnabled = true;
            }

            if (xaml.Content == null) // grays out xaml
            {
                xaml.IsEnabled = false;
                xaml.Background = Brushes.Gainsboro;
                xaml.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xaml, true);
                _ttp.Content = "This sample is not available in XAML.";
                xaml.ToolTip = (_ttp);
            }
            else if (xaml.Content != null)
            {
                xaml.IsEnabled = true;
            }

            if (csharp.Content == null) // grays out c#
            {
                csharp.IsEnabled = false;
                csharp.Background = Brushes.Gainsboro;
                csharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(csharp, true);
                _ttp.Content = "This sample is not available in C#.";
                csharp.ToolTip = (_ttp);
            }
            else if (csharp.Content != null)
            {
                csharp.IsEnabled = true;
            }

            if (vb.Content == null) // grays out vb
            {
                vb.IsEnabled = false;
                vb.Background = Brushes.Gainsboro;
                vb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(vb, true);
                _ttp.Content = "This sample is not available in Visual Basic.NET.";
                vb.ToolTip = (_ttp);
            }
            else if (vb.Content != null)
            {
                vb.IsEnabled = true;
            }

            if (managedcpp.Content == null) // grays out cpp
            {
                managedcpp.IsEnabled = false;
                managedcpp.Background = Brushes.Gainsboro;
                managedcpp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(managedcpp, true);
                _ttp.Content = "This sample is not available in Managed C++.";
                managedcpp.ToolTip = (_ttp);
            }
            else if (managedcpp.Content != null)
            {
                managedcpp.IsEnabled = true;
            }
            if (Welcome.Page1.MyDouble == 1) // XAML only
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 2) // CSharp
            {
                csharp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 3) // Visual Basic
            {
                vb.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 4) // Managed CPP
            {
                managedcpp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 5) // No Filter
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Visible;
                vb.Visibility = Visibility.Visible;
                managedcpp.Visibility = Visibility.Visible;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Visible;
            }
            else if (Welcome.Page1.MyDouble == 6) // XAML + CSharp
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 7) // XAML + VB
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Visible;
            }
        }
    }

    public class Bid : INotifyPropertyChanged
    {
        private string _biditemname = "Unset";
        private decimal _biditemprice;

        public Bid(string newBidItemName, decimal newBidItemPrice)
        {
            _biditemname = newBidItemName;
            _biditemprice = newBidItemPrice;
        }

        public string BidItemName
        {
            get { return _biditemname; }
            set
            {
                if (_biditemname.Equals(value) == false)
                {
                    _biditemname = value;
                    // Call OnPropertyChanged whenever the property is updated
                    OnPropertyChanged("BidItemName");
                }
            }
        }

        public decimal BidItemPrice
        {
            get { return _biditemprice; }
            set
            {
                if (_biditemprice.Equals(value) == false)
                {
                    _biditemprice = value;
                    // Call OnPropertyChanged whenever the property is updated
                    OnPropertyChanged("BidItemPrice");
                }
            }
        }

        // Declare event
        public event PropertyChangedEventHandler PropertyChanged;
        // OnPropertyChanged event handler to update property value in binding
        private void OnPropertyChanged(string propName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }

    public class BidCollection : ObservableCollection<Bid>
    {
        private readonly Bid _item1 = new Bid("Perseus Vase", (decimal) 24.95);
        private readonly Bid _item2 = new Bid("Hercules Statue", (decimal) 16.05);
        private readonly Bid _item3 = new Bid("Odysseus Painting", (decimal) 100.0);

        public BidCollection()
        {
            Add(_item1);
            Add(_item2);
            Add(_item3);
            CreateTimer();
        }

        private void Timer1_Elapsed(object sender, ElapsedEventArgs e)
        {
            _item1.BidItemPrice += (decimal) 1.25;
            _item2.BidItemPrice += (decimal) 2.45;
            _item3.BidItemPrice += (decimal) 10.55;
        }

        private void CreateTimer()
        {
            var timer1 = new Timer
            {
                Enabled = true,
                Interval = 2000
            };
            timer1.Elapsed += Timer1_Elapsed;
        }
    }
}

<|start_filename|>Animation/Per-FrameAnimation/ParticleEffects/Particle.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media;

namespace PerFrameAnimation
{
    internal class Particle
    {
        public DateTime DeathTime;
        public double Diameter;
        public Color EndColor;
        public DateTime LifeTime;
        public Point Location;
        public Color StartColor;
        public Vector Velocity;
    }
}

<|start_filename|>Properties/CustomClassesWithDP/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;

namespace CustomClassesWithDP
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Shirt _myShirt;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnInit(object sender, EventArgs e)
        {
            _myShirt = new Shirt();
            PopulateListbox(ShirtChoice, Enum.GetValues(typeof (ShirtTypes)));
            PopulateListbox(ShirtColorChoice, Enum.GetValues(typeof (ShirtColors)));
            PopulateListbox(ButtonChoice, Enum.GetValues(typeof (ButtonColors)));
            _myShirt.ButtonColorChanged += UiButtonColorChanged;
        }

        private void PopulateListbox(FrameworkElement fe, Array values)
        {
            var lb = fe as ListBox;
            for (var j = 1; j < values.Length; j++)
            {
                var lbi = new ListBoxItem {Content = (Enum) values.GetValue(j)};
                lb.Items.Add(lbi);
            }
        }

        private void ChooseShirt(object sender, SelectionChangedEventArgs e)
        {
            var lbi = ((e.Source as ListBox).SelectedItem as ListBoxItem);
            _myShirt.ShirtType = (ShirtTypes) lbi.Content;
        }

        private void ChooseShirtColor(object sender, SelectionChangedEventArgs e)
        {
            var lbi = ((e.Source as ListBox).SelectedItem as ListBoxItem);
            _myShirt.ShirtColor = (ShirtColors) lbi.Content;
        }

        private void ChooseButtonColor(object sender, SelectionChangedEventArgs e)
        {
            var lbi = ((e.Source as ListBox).SelectedItem as ListBoxItem);
            _myShirt.ButtonColor = (ButtonColors) lbi.Content;
        }

        private void UiButtonColorChanged(object sender, RoutedEventArgs e)
        {
            var s = (Shirt) e.Source;
            var b = s.ButtonColor;
            if (b == ButtonColors.None)
            {
                ButtonChoice.Visibility = Visibility.Hidden;
                ButtonChoiceLabel.Visibility = Visibility.Hidden;
            }
            else
            {
                ButtonChoice.Visibility = Visibility.Visible;
                ButtonChoiceLabel.Visibility = Visibility.Visible;
            }
        }
    }
}

<|start_filename|>Migration and Interoperability/PropertyMappingWithWfh/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Media;
using Application = System.Windows.Forms.Application;
using FlowDirection = System.Windows.FlowDirection;

namespace PropertyMappingWithWfh
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // The WindowLoaded method handles the Loaded event.
        // It enables Windows Forms visual styles, creates 
        // a Windows Forms checkbox control, and assigns the
        // control as the child of the WindowsFormsHost element. 
        // This method also modifies property mappings on the 
        // WindowsFormsHost element.
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            Application.EnableVisualStyles();

            // Create a Windows Forms checkbox control and assign 
            // it as the WindowsFormsHost element's child.
            var cb = new CheckBox
            {
                Text = "Windows Forms checkbox",
                Dock = DockStyle.Fill,
                TextAlign = ContentAlignment.MiddleCenter
            };
            cb.CheckedChanged += cb_CheckedChanged;
            wfHost.Child = cb;

            // Replace the default mapping for the FlowDirection property.
            ReplaceFlowDirectionMapping();

            // Remove the mapping for the Cursor property.
            RemoveCursorMapping();

            // Add the mapping for the Clip property.
            AddClipMapping();

            // Add another mapping for the Background property.
            ExtendBackgroundMapping();

            // Cause the OnFlowDirectionChange delegate to be called.
            wfHost.FlowDirection = FlowDirection.LeftToRight;

            // Cause the OnClipChange delegate to be called.
            wfHost.Clip = new RectangleGeometry();

            // Cause the OnBackgroundChange delegate to be called.
            wfHost.Background = new ImageBrush();
        }

        // The ReplaceFlowDirectionMapping method replaces the  
        // default mapping for the FlowDirection property.
        private void ReplaceFlowDirectionMapping()
        {
            wfHost.PropertyMap.Remove("FlowDirection");

            wfHost.PropertyMap.Add(
                "FlowDirection",
                OnFlowDirectionChange);
        }

        // The OnFlowDirectionChange method translates a 
        // Windows Presentation Foundation FlowDirection value 
        // to a Windows Forms RightToLeft value and assigns
        // the result to the hosted control's RightToLeft property.
        private void OnFlowDirectionChange(object h, string propertyName, object value)
        {
            var host = h as WindowsFormsHost;
            var fd = (FlowDirection) value;
            var cb = host.Child as CheckBox;

            cb.RightToLeft = (fd == FlowDirection.RightToLeft)
                ? RightToLeft.Yes
                : RightToLeft.No;
        }

        // The cb_CheckedChanged method handles the hosted control's
        // CheckedChanged event. If the Checked property is true,
        // the flow direction is set to RightToLeft, otherwise it is
        // set to LeftToRight.
        private void cb_CheckedChanged(object sender, EventArgs e)
        {
            var cb = sender as CheckBox;

            wfHost.FlowDirection = (cb.CheckState == CheckState.Checked)
                ? FlowDirection.RightToLeft
                : FlowDirection.LeftToRight;
        }

        // The RemoveCursorMapping method deletes the default
        // mapping for the Cursor property.
        private void RemoveCursorMapping()
        {
            wfHost.PropertyMap.Remove("Cursor");
        }

        // The AddClipMapping method adds a custom 
        // mapping for the Clip property.
        private void AddClipMapping()
        {
            wfHost.PropertyMap.Add(
                "Clip",
                OnClipChange);
        }

        // The OnClipChange method assigns an elliptical clipping 
        // region to the hosted control's Region property.
        private void OnClipChange(object h, string propertyName, object value)
        {
            var host = h as WindowsFormsHost;
            var cb = host.Child as CheckBox;

            if (cb != null)
            {
                cb.Region = CreateClipRegion();
            }
        }

        // The Window1_SizeChanged method handles the window's 
        // SizeChanged event. It calls the OnClipChange method explicitly 
        // to assign a new clipping region to the hosted control.
        private void Window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            OnClipChange(wfHost, "Clip", null);
        }

        // The CreateClipRegion method creates a Region from an
        // elliptical GraphicsPath.
        private Region CreateClipRegion()
        {
            var path = new GraphicsPath();

            path.StartFigure();

            path.AddEllipse(new Rectangle(
                0,
                0,
                (int) wfHost.ActualWidth,
                (int) wfHost.ActualHeight));

            path.CloseFigure();

            return (new Region(path));
        }

        // The ExtendBackgroundMapping method adds a property
        // translator if a mapping already exists.
        private void ExtendBackgroundMapping()
        {
            if (wfHost.PropertyMap["Background"] != null)
            {
                wfHost.PropertyMap["Background"] += OnBackgroundChange;
            }
        }

        // The OnBackgroundChange method assigns a specific image 
        // to the hosted control's BackgroundImage property.
        private void OnBackgroundChange(object h, string propertyName, object value)
        {
            var host = h as WindowsFormsHost;
            var cb = host.Child as CheckBox;
            var b = value as ImageBrush;

            if (b != null)
            {
                cb.BackgroundImage = new Bitmap(@"C:\WINDOWS\Santa Fe Stucco.bmp");
            }
        }
    }
}

<|start_filename|>Sample Applications/VideoViewerDemo/MyVideo.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace VideoViewerDemo
{
    public class MyVideo
    {
        private string _name;
        private Uri _source;

        public MyVideo(string path)
        {
            Source = path;
            _source = new Uri(path);
        }

        public MyVideo(string path, string name)
        {
            _name = name;
            Source = path;
            _source = new Uri(path);
        }

        public string VideoTitle
        {
            get { return _name; }
            set
            {
                if (_name != value)
                {
                    _name = value;
                }
            }
        }

        public string Source { get; }
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/Splash.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace StickyNotesDemo
{
    // This only works with Windows 2000/XP
    internal class Splash : Form
    {
        public Splash(Bitmap bitmap)
        {
            // Window settings
            TopMost = true;
            ShowInTaskbar = false;
            Size = bitmap.Size;
            StartPosition = FormStartPosition.CenterScreen;
            Show();
            // Must be called before setting bitmap
            SelectBitmap(bitmap);
            BackColor = Color.Red;
            Click += Splash_Click;
            MouseClick += Splash_MouseClick;
        }

        protected override CreateParams CreateParams
        {
            get
            {
                // Add the layered extended style (WS_EX_LAYERED) to this window
                var createParams = base.CreateParams;
                createParams.ExStyle |= NativeMethods.WsExLayered;
                return createParams;
            }
        }

        private void Splash_MouseClick(object sender, MouseEventArgs e)
        {
            Close();
        }

        private void Splash_Click(object sender, EventArgs e)
        {
        }

        // Sets the current bitmap
        public void SelectBitmap(Bitmap bitmap)
        {
            // Does this bitmap contain an alpha channel?
            if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new ApplicationException("The bitmap must be 32bpp with alpha-channel.");
            }

            // Get device contexts
            var screenDc = NativeMethods.GetDC(IntPtr.Zero);
            var memDc = NativeMethods.CreateCompatibleDC(screenDc);
            var hBitmap = IntPtr.Zero;
            var hOldBitmap = IntPtr.Zero;

            try
            {
                // Get handle to the new bitmap and select it into the current device context
                hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
                hOldBitmap = NativeMethods.SelectObject(memDc, hBitmap);

                // Set parameters for layered window update
                var newSize = new NativeMethods.Size(bitmap.Width, bitmap.Height);
                // Size window to match bitmap
                var sourceLocation = new NativeMethods.Point(0, 0);
                var newLocation = new NativeMethods.Point(Left, Top); // Same as this window
                var blend = new NativeMethods.Blendfunction
                {
                    BlendOp = NativeMethods.AcSrcOver,
                    BlendFlags = 0,
                    SourceConstantAlpha = 255,
                    AlphaFormat = NativeMethods.AcSrcAlpha
                };
                // Only works with a 32bpp bitmap
                // Always 0
                // Set to 255 for per-pixel alpha values
                // Only works when the bitmap contains an alpha channel

                // Update the window
                NativeMethods.UpdateLayeredWindow(Handle, screenDc, ref newLocation, ref newSize,
                    memDc, ref sourceLocation, 0, ref blend, NativeMethods.UlwAlpha);
            }
            finally
            {
                // Release device context
                NativeMethods.ReleaseDC(IntPtr.Zero, screenDc);
                if (hBitmap != IntPtr.Zero)
                {
                    NativeMethods.SelectObject(memDc, hOldBitmap);
                    NativeMethods.DeleteObject(hBitmap); // Remove bitmap resources
                }
                NativeMethods.DeleteDC(memDc);
            }
        }

        // Let Windows drag this window for us (thinks its hitting the title bar of the window)
        protected override void WndProc(ref Message message)
        {
            if (message.Msg == NativeMethods.WmNchittest)
            {
                // Tell Windows that the user is on the title bar (caption)
                message.Result = (IntPtr) NativeMethods.Htcaption;
            }
            else
            {
                base.WndProc(ref message);
            }
        }
    }

    // Class to assist with Win32 API calls
}

<|start_filename|>Events/CustomRoutedEvents/MyButtonSimple.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace CustomRoutedEvents
{
    public class MyButtonSimple : Button
    {
        // Create a custom routed event by first registering a RoutedEventID
        // This event uses the bubbling routing strategy
        public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
            "Tap", RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof (MyButtonSimple));

        // Provide CLR accessors for the event
        public event RoutedEventHandler Tap
        {
            add { AddHandler(TapEvent, value); }
            remove { RemoveHandler(TapEvent, value); }
        }

        // This method raises the Tap event
        private void RaiseTapEvent()
        {
            var newEventArgs = new RoutedEventArgs(TapEvent);
            RaiseEvent(newEventArgs);
        }

        // For demonstration purposes we raise the event when the MyButtonSimple is clicked
        protected override void OnClick()
        {
            RaiseTapEvent();
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/BamlBinaryReader.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.IO;
using System.Text;

namespace BamlTools
{
    public class BamlBinaryReader : BinaryReader
    {
        public BamlBinaryReader(Stream stream)
            : base(stream)
        {
        }

        public BamlBinaryReader(Stream stream, Encoding code)
            : base(stream, code)
        {
        }

        public new int Read7BitEncodedInt()
        {
            return base.Read7BitEncodedInt();
        }

        //public BamlRecordType PeekBamlRecordId()
        //{
        //    long pos = BaseStream.Position;
        //    BamlRecordType recordType = (BamlRecordType )ReadByte();
        //    BaseStream.Position = pos;

        //    return recordType;
        //}
    }
}


<|start_filename|>Sample Applications/FontDialog/TypographicFeatureListItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;

namespace FontDialog
{
    internal class TypographicFeatureListItem : TextBlock, IComparable
    {
        private readonly string _displayName;

        public TypographicFeatureListItem(string displayName, DependencyProperty chooserProperty)
        {
            _displayName = displayName;
            ChooserProperty = chooserProperty;
            Text = displayName;
        }

        public DependencyProperty ChooserProperty { get; }

        int IComparable.CompareTo(object obj) => string.Compare(_displayName, obj.ToString(), true, CultureInfo.CurrentCulture);

        public override string ToString() => _displayName;
    }
}

<|start_filename|>Data Binding/CompositeCollections/GreekGod.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace CompositeCollections
{
    public class GreekGod
    {
        public GreekGod(string name)
        {
            Name = name;
        }

        public string Name { get; set; }
    }
}

<|start_filename|>Data Binding/UpdateSource/UserProfile.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace UpdateSource
{
    public class UserProfile : INotifyPropertyChanged
    {
        private string _bidPrice = "";
        private string _itemName = "";

        public string ItemName
        {
            get { return _itemName; }
            set
            {
                _itemName = value;
                OnPropertyChanged("ItemName");
            }
        }

        public string BidPrice
        {
            get { return _bidPrice; }
            set
            {
                _bidPrice = value;
                OnPropertyChanged("BidPrice");
            }
        }

        //Declare event
        public event PropertyChangedEventHandler PropertyChanged;
        //OnPropertyChanged event handler to update property value in binding
        private void OnPropertyChanged(string info)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/aitcodecregistrymanager.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Declaration and Definition of TestCodecsRegistryManager
//----------------------------------------------------------------------------------------
#pragma once


class TestCodecsRegistryManager : public RegistryValueManager
{
public:
     virtual HRESULT PopulateValues()
    {
        SetCodecDLLPath();

        RegisterAITDecoder();
        RegisterAITEncoder();        
        RegisterYCbCrFormatConverter();
        RegisterCMYKFormatConverter();
        return S_OK;
    }

private:

   //Register function for every extensible element
    void RegisterAITDecoder()
    {
        BYTE bytes[8] = { 0 };
        // AIT Decoder
        Val("CLSID\\{7ED96837-96F0-4812-B211-F13C24117ED3}\\Instance\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "CLSID", "{DEC50239-14BB-4F70-AD2A-B7126219A6DC}");
        Val("CLSID\\{7ED96837-96F0-4812-B211-F13C24117ED3}\\Instance\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "FriendlyName", "Test AIT Decoder");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Version", "1.0.0.0");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Date", "2004-09-01");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SpecVersion", "1.0.0.0");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "ColorManagementVersion", "1.0.0.0");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "MimeTypes", "x-image/ait");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "FileExtensions", ".ait");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportsAnimation", 1);
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportChromakey", 1);
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportLossless", 1);
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportMultiframe", 1);
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "ContainerFormat", "{CCC50239-14BB-4F70-AD2A-B7126219A6DC}");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Author", "WPF Imaging Test");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Description", "WPF Imaging Test Decoder");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "FriendlyName", "Test AIT Decoder");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc901}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc902}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc903}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc904}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc905}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc906}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc907}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc908}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc909}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90a}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90b}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90c}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90d}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90e}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90f}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc910}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc911}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc912}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc913}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc914}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc915}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc916}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc917}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc918}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc919}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc91a}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc91b}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc91c}",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\InprocServer32",
            "", moduleFilename);
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Patterns",
            "", "");
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Patterns\\0",
            "Position", (DWORD)0);
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Patterns\\0",
            "Length", 4);
        bytes[0] = 'A'; bytes[1] = 'I'; bytes[2] = 'T'; bytes[3] = '\0';
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Patterns\\0",
            "Pattern", bytes, 4);
        bytes[0] = bytes[1] = bytes[2] = bytes[3] = 0xFF;
        Val("CLSID\\{DEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Patterns\\0",
            "Mask", bytes, 4);
    };

    void RegisterAITEncoder()
    {
         // AIT Encoder
        Val("CLSID\\{AC757296-3522-4e11-9862-C17BE5A1767E}\\Instance\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "CLSID", "{EEC50239-14BB-4F70-AD2A-B7126219A6DC}");
        Val("CLSID\\{AC757296-3522-4e11-9862-C17BE5A1767E}\\Instance\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "FriendlyName", "Test AIT Encoder");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Version", "1.0.0.0");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Date", "2004-09-01");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SpecVersion", "1.0.0.0");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "ColorManagementVersion", "1.0.0.0");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "MimeTypes", "x-image/ait");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportsAnimation", 1);
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportChromakey", 1);
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportLossless", 1);
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "SupportMultiframe", 1);
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "ContainerFormat", "{CCC50239-14BB-4F70-AD2A-B7126219A6DC}");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Author", "WPF Imaging Test");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "Description", "WPF Imaging Test Encoder");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}",
            "FriendlyName", "Test AIT Encoder");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc901}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc902}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc903}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc904}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc905}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc906}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc907}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc908}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc909}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90a}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90b}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90c}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90d}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90e}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc90f}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc910}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc911}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc912}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc913}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc914}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc915}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc916}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc917}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc918}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc919}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc91a}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc91b}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\Formats\\{6fddc324-4e03-4bfe-b185-3d77768dc91c}",
            "", "");
        Val("CLSID\\{EEC50239-14BB-4F70-AD2A-B7126219A6DC}\\InprocServer32",
            "", moduleFilename);
    };

    void RegisterYCbCrFormatConverter()
    {
        Val("CLSID\\{7835EAE8-BF14-49D1-93CE-533A407B2248}\\Instance\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}",
            "CLSID", "{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}");                      
        Val("CLSID\\{7835EAE8-BF14-49D1-93CE-533A407B2248}\\Instance\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}",
            "FriendlyName", "Test YcbCr Pixel Format Converter");
        Val("CLSID\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}",
            "Date", "2005-05-26");
        Val("CLSID\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}",
            "SpecVersion", "1.0.0.0");
        Val("CLSID\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}",
            "Version", "1.0.0.0");
        Val("CLSID\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}\\InprocServer32",
            "", moduleFilename);
        Val("CLSID\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}\\InprocServer32",
            "ThreadingModel", "Both");
        Val("CLSID\\{49CC393E-CE46-11D9-8BDE-F66BAD1E3F3A}\\PixelFormats\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}",
            "", "");      
         
        Val("CLSID\\{2b46e70f-cda7-473e-89f6-dc9630a2390b}\\Instance\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}",
            "CLSID", "{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}");
        Val("CLSID\\{2b46e70f-cda7-473e-89f6-dc9630a2390b}\\Instance\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}",
            "FriendlyName", "Test YCbCr Pixel Format");

        Val("CLSID\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}",
            "Author", "WPF Imaging Test");
        Val("CLSID\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}",
            "FriendlyName", "Test YCbCr Pixel Format");

        Val("CLSID\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}",
            "ChannelCount", (DWORD)3);
        Val("CLSID\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}",
            "BitLength", (DWORD)24);

        BYTE mask0[] = {0xFF,0,0};
        BYTE mask1[] = {0,0xFF,0};
        BYTE mask2[] = {0,0,0xFF};
        Val("CLSID\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}\\ChannelMasks",
            "0", mask0, 3);
        Val("CLSID\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}\\ChannelMasks",
            "1", mask1, 3);
        Val("CLSID\\{9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}\\ChannelMasks",
            "2", mask2, 3);
    };

    void RegisterCMYKFormatConverter()
    {
                                                                       
        Val("CLSID\\{7835EAE8-BF14-49D1-93CE-533A407B2248}\\Instance\\{B312A459-2A44-4833-AA45-0F50BC669A28}",
            "CLSID", "{B312A459-2A44-4833-AA45-0F50BC669A28}");                      
        Val("CLSID\\{7835EAE8-BF14-49D1-93CE-533A407B2248}\\Instance\\{B312A459-2A44-4833-AA45-0F50BC669A28}",
            "FriendlyName", "Test CMYK Pixel Format Converter");
        Val("CLSID\\{B312A459-2A44-4833-AA45-0F50BC669A28}",
            "Date", "2005-05-26");
        Val("CLSID\\{B312A459-2A44-4833-AA45-0F50BC669A28}",
            "SpecVersion", "1.0.0.0");
        Val("CLSID\\{B312A459-2A44-4833-AA45-0F50BC669A28}",
            "Version", "1.0.0.0");
        Val("CLSID\\{B312A459-2A44-4833-AA45-0F50BC669A28}\\InprocServer32",
            "", moduleFilename);
        Val("CLSID\\{B312A459-2A44-4833-AA45-0F50BC669A28}\\InprocServer32",
            "ThreadingModel", "Both");
        Val("CLSID\\{B312A459-2A44-4833-AA45-0F50BC669A28}\\PixelFormats\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}",
            "", "");      

        Val("CLSID\\{2b46e70f-cda7-473e-89f6-dc9630a2390b}\\Instance\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}",
            "CLSID", "{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}");
        Val("CLSID\\{2b46e70f-cda7-473e-89f6-dc9630a2390b}\\Instance\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}",
            "FriendlyName", "Test CMYK Pixel Format");

        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}",
            "Author", "WPF Imaging Test");
        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}",
            "FriendlyName", "Test CMYK Pixel Format");

        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}",
            "ChannelCount", (DWORD)4);
        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}",
            "BitLength", (DWORD)32);

        BYTE mask0[] = {0xFF,0,0,0};
        BYTE mask1[] = {0,0xFF,0,0};
        BYTE mask2[] = {0,0,0xFF,0};
        BYTE mask3[] = {0,0,0,0xFF};
        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}\\ChannelMasks",
            "0", mask0, 4);
        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}\\ChannelMasks",
            "1", mask1, 4);
        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}\\ChannelMasks",
            "2", mask2, 4);
        Val("CLSID\\{710194EC-F8B2-4b7a-94AD-945A7DCDEADB}\\ChannelMasks",
            "3", mask3, 4);
    };

    void SetCodecDLLPath()
    {
        HMODULE curModule = GetModuleHandle("AITCodecs.dll");
        
        if (curModule != NULL)
        {
            GetModuleFileNameA(curModule, moduleFilename, MAX_PATH);
        }
    }
 //Codec Dll full path
 char moduleFilename[MAX_PATH];
};


<|start_filename|>Animation/AnimationTiming/AccelDecelExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace AnimationTiming
{
    public partial class AccelDecelExample : Page
    {
        private void StateInvalidated(object sender, EventArgs args)
        {
            if (sender != null)
            {
                elapsedTime.Clock = (Clock) sender;
            }
        }
    }
}

<|start_filename|>Windows/Wizard/WizardPage1.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Navigation;

namespace Wizard
{
    public partial class WizardPage1 : PageFunction<WizardResult>
    {
        public WizardPage1(WizardData wizardData)
        {
            InitializeComponent();

            // Bind wizard state to UI
            DataContext = wizardData;
        }

        private void nextButton_Click(object sender, RoutedEventArgs e)
        {
            // Go to next wizard page
            var wizardPage2 = new WizardPage2((WizardData) DataContext);
            wizardPage2.Return += wizardPage_Return;
            NavigationService?.Navigate(wizardPage2);
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            // Cancel the wizard and don't return any data
            OnReturn(new ReturnEventArgs<WizardResult>(WizardResult.Canceled));
        }

        public void wizardPage_Return(object sender, ReturnEventArgs<WizardResult> e)
        {
            // If returning, wizard was completed (finished or canceled),
            // so continue returning to calling page
            OnReturn(e);
        }
    }
}

<|start_filename|>Windows/SaveWindowState/Properties/Settings.Designer.cs<|end_filename|>
﻿//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SaveWindowState.Properties {
    
    
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
        
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
        
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
        
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute(@"
                    <WindowPlacement xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                        <length>0</length>
                        <flags>0</flags>
                        <showCmd>0</showCmd>
                        <minPosition>
                            <X>0</X>
                            <Y>0</Y>
                        </minPosition>
                        <maxPosition>
                            <X>0</X>
                            <Y>0</Y>
                        </maxPosition>
                        <normalPosition>
                            <Left>0</Left>
                            <Top>0</Top>
                            <Right>0</Right>
                            <Bottom>0</Bottom>
                        </normalPosition>
                    </WindowPlacement>
                ")]
        public global::SaveWindowState.WindowPlacement WindowPlacement {
            get {
                return ((global::SaveWindowState.WindowPlacement)(this["WindowPlacement"]));
            }
            set {
                this["WindowPlacement"] = value;
            }
        }
    }
}


<|start_filename|>Properties/CustomClassesWithDP/ShirtTypes.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace CustomClassesWithDP
{
    public enum ShirtTypes
    {
        None,
        Tee,
        Bowling,
        Dress,
        Rugby
    }
}

<|start_filename|>Windows/SaveWindowState/Windowplacement.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;

namespace SaveWindowState
{
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public struct WindowPlacement
    {
        public int length;
        public int flags;
        public int showCmd;
        public Point minPosition;
        public Point maxPosition;
        public Rect normalPosition;
    }
}

<|start_filename|>Documents/Annotations/AnnotationsStyling/ResourceEntryToComboItemConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace AnnotationsStyling
{
    [ValueConversion(typeof (Collection<StyleMetaData>),
        typeof (Collection<ResourceDictionary>))]
    public class ResourceEntryToComboItemConverter : IValueConverter
    {
        // ----------------------------- Convert ------------------------------
        /// <summary>
        ///     Parses a collection of ResourceDictionaries and
        ///     extracts all StickyNote styles.
        /// </summary>
        /// <returns>
        ///     A list of Styles and their associated
        ///     keys (for identification).
        /// </returns>
        public object Convert(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            var unfiltered =
                value as Collection<ResourceDictionary>;

            var filtered =
                new Collection<StyleMetaData>();

            foreach (var dict in unfiltered)
            {
                foreach (string key in dict.Keys)
                {
                    var aStyle = dict[key] as Style;
                    if (aStyle != null && aStyle.TargetType.Equals(typeof (StickyNoteControl)))
                        filtered.Add(new StyleMetaData(key, aStyle));
                }
            }

            return filtered;
        } // end:Convert
        // --------------------------- ConvertBack ----------------------------
        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture) => null;
    }
}

<|start_filename|>Getting Started/Concepts/Default.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;

namespace Guide
{
    public partial class Page1 : Page
    {
        private Application _app;
        public bool RealTimeUpdate = true;

        public void MenuExit(object sender, RoutedEventArgs args)
        {
            _app = Application.Current;
            _app.Shutdown();
        }

        public void SetXaml(object sender, EventArgs e)
        {
            myCombo.SelectedValue = cbItem5;
        }

        //Begin XAMLPAD integration

        protected void HandleTextChanged(object sender, TextChangedEventArgs me)
        {
            if (RealTimeUpdate) ParseCurrentBuffer();
        }

        private void ParseCurrentBuffer()
        {
            try
            {
                var ms = new MemoryStream();
                var sw = new StreamWriter(ms);
                var str = TextBox1.Text;
                sw.Write(str);
                sw.Flush();
                ms.Flush();
                ms.Position = 0;
                try
                {
                    var content = XamlReader.Load(ms);
                    if (content != null)
                    {
                        cc.Children.Clear();
                        cc.Children.Add((UIElement) content);
                    }
                    TextBox1.Foreground = Brushes.Black;
                    ErrorText.Text = "";
                }

                catch (XamlParseException xpe)
                {
                    TextBox1.Foreground = Brushes.Red;
                    ErrorText.Text = xpe.Message;
                }
            }
            catch (Exception)
            {
            }
        }

        // End integration of XAMLPAD

        public void SelectLang(object sender, RoutedEventArgs e)
        {
            if (cbItem1.IsSelected)
            {
                Welcome.Page1.MyDouble = 1;
                frame2.Refresh();
            }
            else if (cbItem2.IsSelected)
            {
                Welcome.Page1.MyDouble = 2;
                frame2.Refresh();
            }
            else if (cbItem3.IsSelected)
            {
                Welcome.Page1.MyDouble = 3;
                frame2.Refresh();
            }
            else if (cbItem4.IsSelected)
            {
                Welcome.Page1.MyDouble = 4;
                frame2.Refresh();
            }
            else if (cbItem5.IsSelected)
            {
                Welcome.Page1.MyDouble = 5;
                frame2.Refresh();
            }
            else if (cbItem6.IsSelected)
            {
                Welcome.Page1.MyDouble = 6;
                frame2.Refresh();
            }
            else if (cbItem7.IsSelected)
            {
                Welcome.Page1.MyDouble = 7;
                frame2.Refresh();
            }
        }
    }
}

<|start_filename|>Data Binding/MasterDetail/Division.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace MasterDetail
{
    public class Division
    {
        public Division(string name)
        {
            Name = name;
            Teams = new TeamList();
        }

        public string Name { get; }
        public TeamList Teams { get; }

        public override string ToString() => Name;
    }
}

<|start_filename|>Sample Applications/CustomComboBox/MainWindowViewModel.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;

namespace CustomComboBox
{
    class MainWindowViewModel : INotifyPropertyChanged
    {
        public MainWindowViewModel()
        {
            Movies2 = new List<string>
            {
                "Movie1",
                "Movie2",
                "Movie3",
                "Movie4",
                "Movie5",
                "Movie6"
            };
            Movies = new List<Movie>
            {
                new Movie{Id=1, Title="The Dark Knight" },
                new Movie{Id=2, Title="The Big Lebowski" },
                new Movie{Id=3, Title="The Shawshank Redemption" },
                new Movie{Id=4, Title="Schindler's List" },
                new Movie{Id=5, Title="Pulp Fiction" },
                new Movie{Id=6, Title="Fight Club" }
            };

            OnWatchNow = new WatchNowCommand(ShowMovie);
        }

        private void ShowMovie(object parameter)
        {
            if (parameter != null)
            {

                if (parameter is string s)
                    SelectedMovie = s;
                else if (parameter is Movie m)
                    SelectedMovie = m.Title;
            }
        }

        public List<Movie> Movies { get; set; }
        public List<string> Movies2 { get; set; }
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        public ICommand OnWatchNow { get; set; }
        string selectedMovie;
        public string SelectedMovie
        {
            get { return selectedMovie; }
            set
            {
                selectedMovie = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedMovie)));
            }
        }
    }

    public class WatchNowCommand : ICommand
    {
        Action<object> _execute;
        public WatchNowCommand(Action<object> execute)
        {
            _execute = execute;
        }
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter) => true;

        public void Execute(object parameter) =>
            _execute(parameter);

    }
}


<|start_filename|>Documents/Fixed Documents/DocumentMerge/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;

namespace DocumentMerge
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly Dictionary<string, XpsDocument> _documentCache;
        private readonly RollUpDocument _documentRollUp;

        public MainWindow()
        {
            InitializeComponent();
            // Add the Open Command
            AddCommandBindings(ApplicationCommands.Open, OpenCommandHandler);
            // Add the Save Command
            //AddCommandBindings(ApplicationCommands.Save, SaveCommandHandler);
            AddCommandBindings(ApplicationCommands.Save, SaveCommandHandler);
            // Add the Exit/Close Command
            AddCommandBindings(ApplicationCommands.Close, CloseCommandHandler);

            _documentRollUp = new RollUpDocument();
            _documentCache = new Dictionary<string, XpsDocument>();
        }

        // ------------------------ OpenCommandHandler ------------------------
        /// <summary>
        ///     Opens an existing XPS document and displays it
        ///     in a DocumentViewer control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenCommandHandler(object sender, RoutedEventArgs e)
        {
            //Display a file open dialog to select an existing document
            var dlg = new OpenFileDialog
            {
                Filter = "XPS Document (*.xps)|*.xps",
                InitialDirectory = GetContentFolder(),
                CheckFileExists = true,
                Multiselect = true
            };
            if (dlg.ShowDialog() == true)
            {
                foreach (var file in dlg.FileNames)
                {
                    AddDocumentsToSource(file);
                }
            }
            menuFileSave.IsEnabled = true;
        }

        // ------------------------- GetContentFolder -------------------------
        /// <summary>
        ///     Locates and returns the path to the "Content\" folder
        ///     containing the fixed document for the sample.
        /// </summary>
        /// <returns>
        ///     The path to the fixed document "Content\" folder.
        /// </returns>
        private string GetContentFolder()
        {
            // Get the path to the current directory and its length.
            var contentDir = Directory.GetCurrentDirectory();
            var dirLength = contentDir.Length;

            // If we're in "...\bin\debug", move up to the root.
            if (contentDir.ToLower().EndsWith(@"\bin\debug"))
                contentDir = contentDir.Remove(dirLength - 10, 10);

            // If we're in "...\bin\release", move up to the root.
            else if (contentDir.ToLower().EndsWith(@"\bin\release"))
                contentDir = contentDir.Remove(dirLength - 12, 12);

            // If there's a "Content" subfolder, that's what we want.
            if (Directory.Exists(contentDir + @"\Content"))
                contentDir = contentDir + @"\Content";

            // Return the "Content\" folder (or the "current"
            // directory if we're executing somewhere else).
            return contentDir;
        } // end:GetContentFolder()

        private void AddDocumentsToSource(string fileName)
        {
            if (!_documentCache.ContainsKey(fileName))
            {
                var xpsDocument = new XpsDocument(fileName, FileAccess.Read);
                _documentCache[fileName] = xpsDocument;
                var docSeq = xpsDocument.GetFixedDocumentSequence();
                foreach (var docRef in docSeq.References)
                {
                    var item = new DocumentItem(fileName, docRef);
                    source.Items.Add(item);
                }
            }
        }

        /// <summary>
        ///     Closes current Xps Document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveCommandHandler(object sender, RoutedEventArgs e)
        {
            if (dest.Items.Count < 1)
            {
                MessageBox.Show("Please add document to list before saving",
                    "No document to be combined", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Xps Documents (*.xps)|*.xps",
                FilterIndex = 1
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                var destFile = saveFileDialog.FileName;
                if (File.Exists(destFile))
                {
                    File.Delete(destFile);
                }
                _documentRollUp.Uri = new Uri(destFile);
                _documentRollUp.Save();
            }
        }

        /// <summary>
        ///     Closes current XPS document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// !!!private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
        private void CloseCommandHandler(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void SourceSelected(object sender, SelectionChangedEventArgs args)
        {
            sourcePage.Items.Clear();
            foreach (var item in args.AddedItems)
            {
                if (item is DocumentItem)
                {
                    var docSrc = item as DocumentItem;
                    foreach (var pageContent in docSrc.FixedDocument.Pages)
                    {
                        sourcePage.Items.Add(new PageItem(pageContent));
                    }
                }
            }
        }

        private void DestSelected(object sender, SelectionChangedEventArgs args)
        {
            destPage.Items.Clear();
            var selectedIndex = dest.SelectedIndex;
            if (selectedIndex != -1)
            {
                var pageCount = _documentRollUp.GetPageCount(selectedIndex);
                for (var i = 0; i < pageCount; i++)
                {
                    var pageContent = _documentRollUp.GetPage(selectedIndex, i);
                    destPage.Items.Add(new PageItem(pageContent));
                }
            }
        }

        private void Window_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data != null && e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effects = DragDropEffects.All;
            }
            else
            {
                e.Effects = DragDropEffects.None;
            }
        }

        private void Window_OnDrop(object sender, DragEventArgs e)
        {
            if (e.Data != null && e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var files = (string[]) e.Data.GetData(DataFormats.FileDrop);
                foreach (var file in files)
                {
                    AddDocumentsToSource(file);
                }
            }
        }

        /// <summary>
        ///     Helper function to find commands to handlers and register them
        /// </summary>
        /// <param name="command"></param>
        /// <param name="handler"></param>
        private void AddCommandBindings(ICommand command, ExecutedRoutedEventHandler handler)
        {
            var cmdBindings = new CommandBinding(command);
            cmdBindings.Executed += handler;
            CommandBindings.Add(cmdBindings);
        }

        protected void DestDocList_OnDrop(object sender, DragEventArgs e)
        {
            if (e.Data != null && e.Data.GetDataPresent(typeof (List<DocumentItem>)))
            {
                var items = (List<DocumentItem>) e.Data.GetData(typeof (List<DocumentItem>));
                dest.BeginInit();
                dest.SelectedItems.Clear();
                DocumentItem firstItem = null;
                foreach (var item in items)
                {
                    var newItem = new DocumentItem(item);
                    dest.Items.Add(newItem);
                    // only select fist item
                    if (firstItem == null)
                    {
                        firstItem = newItem;
                    }
                    _documentRollUp.AddDocument(item.DocumentReference.Source,
                        (item.DocumentReference as IUriContext).BaseUri);
                }
                dest.SelectedItem = firstItem;
                dest.EndInit();
            }
            e.Handled = true;
        }

        protected void DestPageList_OnDrop(object sender, DragEventArgs e)
        {
            if (e.Data != null && e.Data.GetDataPresent(typeof (List<PageItem>)))
            {
                var items = (List<PageItem>) e.Data.GetData(typeof (List<PageItem>));
                if (items.Count > 0)
                {
                    var selectedDoc = dest.SelectedIndex;
                    if (selectedDoc == -1)
                    {
                        selectedDoc = _documentRollUp.AddDocument();
                        var docItem = new DocumentItem(items[0].FixedPage);
                        dest.Items.Add(docItem);
                        dest.SelectedItem = docItem;
                    }
                    foreach (var item in items)
                    {
                        destPage.Items.Add(new PageItem(item));
                        _documentRollUp.AddPage(selectedDoc, item.PageContent.Source,
                            (item.PageContent as IUriContext).BaseUri);
                    }
                }
            }
            e.Handled = true;
        }

        protected void DestItem_Drop(object sender, DragEventArgs e)
        {
            if (e.Data != null && e.Data.GetDataPresent(typeof (List<DocumentItem>)))
            {
                var items = (List<DocumentItem>) e.Data.GetData(typeof (List<DocumentItem>));
                var currItem = (ListBoxItem) sender;
                var currItemIndex = dest.Items.IndexOf(currItem.Content);
                var insertionIndex = currItemIndex;

                var currentDropPosition = e.GetPosition(dest);
                var itemPosition = currItem.TranslatePoint(new Point(0, 0), dest);
                if (currentDropPosition.X < (itemPosition.X + (currItem.ActualWidth/2)))
                {
                }
                else
                {
                    insertionIndex++;
                }
                foreach (var item in items)
                {
                    dest.Items.Insert(insertionIndex, new DocumentItem(item));
                    _documentRollUp.InsertDocument(insertionIndex, item.DocumentReference.Source,
                        (item.DocumentReference as IUriContext).BaseUri);
                }
            }
            e.Handled = true;
        }

        protected void DestPageItem_Drop(object sender, DragEventArgs e)
        {
            if (e.Data != null && e.Data.GetDataPresent(typeof (List<PageItem>)))
            {
                var items = (List<PageItem>) e.Data.GetData(typeof (List<PageItem>));
                var currItem = (ListBoxItem) sender;
                var currItemIndex = destPage.Items.IndexOf(currItem.Content);
                var insertionIndex = currItemIndex;

                var currentDropPosition = e.GetPosition(dest);
                var itemPosition = currItem.TranslatePoint(new Point(0, 0), destPage);
                if (currentDropPosition.X < (itemPosition.X + (currItem.ActualWidth/2)))
                {
                }
                else
                {
                    insertionIndex++;
                }
                foreach (var item in items)
                {
                    destPage.Items.Insert(insertionIndex, new PageItem(item));
                    _documentRollUp.InsertPage(dest.SelectedIndex, insertionIndex, item.PageContent.Source,
                        (item.PageContent as IUriContext).BaseUri);
                }
            }
            e.Handled = true;
        }

        private void DestList_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                var index = -1;

                while ((index = dest.SelectedIndex) != -1)
                {
                    dest.Items.RemoveAt(index);
                    _documentRollUp.RemoveDocument(index);
                }
            }
        }

        private void DestPageList_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                var index = -1;

                while ((index = destPage.SelectedIndex) != -1)
                {
                    destPage.Items.RemoveAt(index);
                    _documentRollUp.RemovePage(dest.SelectedIndex, index);
                }
                // if we deleted all the pages, we will remove the parent document too
                if (destPage.Items.Count == 0)
                {
                    while ((index = dest.SelectedIndex) != -1)
                    {
                        dest.Items.RemoveAt(index);
                        _documentRollUp.RemoveDocument(index);
                    }
                }
            }
        }

        private void rect_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 1 && !Keyboard.IsKeyDown(Key.RightCtrl) && !Keyboard.IsKeyDown(Key.LeftCtrl))
            {
                var items = new List<DocumentItem>();
                var clearAndSelect = false;

                var clikedItem = sender as ListBoxItem;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    items.AddRange(source.SelectedItems.Cast<DocumentItem>());
                }
                else
                {
                    clearAndSelect = true;
                    items.Add(clikedItem.Content as DocumentItem);
                }

                DragDrop.DoDragDrop(source, items, DragDropEffects.All);
                if (clearAndSelect)
                {
                    source.SelectedItems.Clear();
                }
                clikedItem.IsSelected = true;
                e.Handled = true;
            }
        }

        private void page_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 1 && !Keyboard.IsKeyDown(Key.RightCtrl) && !Keyboard.IsKeyDown(Key.LeftCtrl))
            {
                var items = new List<PageItem>();
                var clearAndSelect = false;

                var clikedItem = sender as ListBoxItem;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    items.AddRange(sourcePage.SelectedItems.Cast<PageItem>());
                }
                else
                {
                    clearAndSelect = true;
                    items.Add(clikedItem.Content as PageItem);
                }

                DragDrop.DoDragDrop(source, items, DragDropEffects.All);
                if (clearAndSelect)
                {
                    sourcePage.SelectedItems.Clear();
                }
                clikedItem.IsSelected = true;
                e.Handled = true;
            }
        }

        private void dest_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
        }
    }
}

<|start_filename|>Properties/RestoringDefaultValues/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace RestoringDefaultValues
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void RestoreDefaultProperties(object sender, RoutedEventArgs e)
        {
            var uic = Sandbox.Children;
            foreach (Shape uie in uic)
            {
                var locallySetProperties = uie.GetLocalValueEnumerator();
                while (locallySetProperties.MoveNext())
                {
                    var propertyToClear = locallySetProperties.Current.Property;
                    if (!propertyToClear.ReadOnly)
                    {
                        uie.ClearValue(propertyToClear);
                    }
                }
            }
        }

        private void MakeEverythingRed(object sender, RoutedEventArgs e)
        {
            var uic = Sandbox.Children;
            foreach (Shape uie in uic)
            {
                uie.Fill = new SolidColorBrush(Colors.Red);
            }
        }
    }
}

<|start_filename|>Animation/AnimationExamples/TimingBehaviors/AnimationTransitionType.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace AnimationExamples
{
    public enum AnimationTransitionType
    {
        Linear,
        Bounce,
        Elastic
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/UnaryExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     An expression which holds onto a single child expression.  All of its
    ///     functions call into the child functions.
    /// </summary>
    public abstract class UnaryExpression : IExpression
    {
        protected IExpression child;

        protected UnaryExpression(IExpression child)
        {
            this.child = child;
        }

        public IExpression Child => child;

        public double Evaluate() => Operate(child.Evaluate());

        string IExpression.ToString() => ToString();

        public abstract IExpression Differentiate(string byVar);
        public abstract IExpression Simplify();
        protected abstract double Operate(double d);
        public abstract override string ToString();
    }
}

<|start_filename|>Animation/Per-FrameAnimation/ParticleEffects/MagnitismCanvas.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace PerFrameAnimation
{
    public class MagnitismCanvas : Canvas
    {
        public MagnitismCanvas()
        {
            // suppress movement in the visual studio designer.
            if (Process.GetCurrentProcess().ProcessName != "devenv")
                CompositionTarget.Rendering += UpdateChildren;
            _timeTracker = new ParticleEffectsTimeTracker();
        }

        private void UpdateChildren(object sender, EventArgs e)
        {
            //update time delta
            _timeTracker.Update();

            foreach (UIElement child in LogicalTreeHelper.GetChildren(this))
            {
                var velocity = _childrenVelocities.ContainsKey(child) ? _childrenVelocities[child] : new Vector(0, 0);

                //compute velocity dampening
                velocity = velocity*Drag;

                var truePosition = GetTruePosition(child);
                var childRect = new Rect(truePosition, child.RenderSize);


                //accumulate forces
                var forces = new Vector(0, 0);

                //add wall repulsion
                forces.X += BorderForce/Math.Max(1, childRect.Left);
                forces.X -= BorderForce/Math.Max(1, RenderSize.Width - childRect.Right);
                forces.Y += BorderForce/Math.Max(1, childRect.Top);
                forces.Y -= BorderForce/Math.Max(1, RenderSize.Height - childRect.Bottom);

                //each other child pushes away based on the square distance
                foreach (UIElement otherchild in LogicalTreeHelper.GetChildren(this))
                {
                    //dont push against itself
                    if (otherchild == child)
                        continue;

                    var otherchildtruePosition = GetTruePosition(otherchild);
                    var otherchildRect = new Rect(otherchildtruePosition, otherchild.RenderSize);

                    //make sure rects aren't the same
                    if (otherchildRect == childRect)
                        continue;

                    //ignore children with a size of 0,0
                    if (otherchildRect.Width == 0 && otherchildRect.Height == 0 ||
                        childRect.Width == 0 && childRect.Height == 0)
                        continue;

                    //vector from current other child to current child
                    //are they overlapping?  if so, distance is 0
                    var toChild = AreRectsOverlapping(childRect, otherchildRect)
                        ? new Vector(0, 0)
                        : VectorBetweenRects(childRect, otherchildRect);

                    var length = toChild.Length;
                    if (length < 1)
                    {
                        length = 1;
                        var childCenter = GetCenter(childRect);
                        var otherchildCenter = GetCenter(otherchildRect);
                        //compute toChild from the center of both rects
                        toChild = childCenter - otherchildCenter;
                    }

                    var childpush = ChildForce/length;

                    toChild.Normalize();
                    forces += toChild*childpush;
                }

                //add forces to velocity and store it for next iteration
                velocity += forces;
                _childrenVelocities[child] = velocity;

                //move the object based on it's velocity
                SetTruePosition(child, truePosition + _timeTracker.DeltaSeconds*velocity);
            }
        }

        private bool AreRectsOverlapping(Rect r1, Rect r2)
        {
            if (r1.Bottom < r2.Top) return false;
            if (r1.Top > r2.Bottom) return false;

            if (r1.Right < r2.Left) return false;
            if (r1.Left > r2.Right) return false;

            return true;
        }

        private Point IntersectInsideRect(Rect r, Point raystart, Vector raydir)
        {
            var xtop = raystart.X + raydir.X*(r.Top - raystart.Y)/raydir.Y;
            var xbottom = raystart.X + raydir.X*(r.Bottom - raystart.Y)/raydir.Y;
            var yleft = raystart.Y + raydir.Y*(r.Left - raystart.X)/raydir.X;
            var yright = raystart.Y + raydir.Y*(r.Right - raystart.X)/raydir.X;
            var top = new Point(xtop, r.Top);
            var bottom = new Point(xbottom, r.Bottom);
            var left = new Point(r.Left, yleft);
            var right = new Point(r.Right, yright);
            var tv = raystart - top;
            var bv = raystart - bottom;
            var lv = raystart - left;
            var rv = raystart - right;
            //classify ray direction
            if (raydir.Y < 0)
            {
                if (raydir.X < 0) //top left
                {
                    if (tv.LengthSquared < lv.LengthSquared)
                        return top;
                    return left;
                }
                if (tv.LengthSquared < rv.LengthSquared)
                    return top;
                return right;
            }
            if (raydir.X < 0) //bottom left
            {
                if (bv.LengthSquared < lv.LengthSquared)
                    return bottom;
                return left;
            }
            if (bv.LengthSquared < rv.LengthSquared)
                return bottom;
            return right;
        }

        private Vector VectorBetweenRects(Rect r1, Rect r2)
        {
            //find the edge points and use these to measure the distance
            var r1Center = GetCenter(r1);
            var r2Center = GetCenter(r2);
            var between = (r1Center - r2Center);
            between.Normalize();
            var edge1 = IntersectInsideRect(r1, r1Center, -between);
            var edge2 = IntersectInsideRect(r2, r2Center, between);
            return edge1 - edge2;
        }

        private Point GetRenderTransformOffset(UIElement e)
        {
            //make sure they object's render transform is a translation
            var renderTranslation = e.RenderTransform as TranslateTransform;
            if (renderTranslation == null)
            {
                renderTranslation = new TranslateTransform(0, 0);
                e.RenderTransform = renderTranslation;
            }

            return new Point(renderTranslation.X, renderTranslation.Y);
        }

        private void SetRenderTransformOffset(UIElement e, Point offset)
        {
            //make sure they object's render transform is a translation
            var renderTranslation = e.RenderTransform as TranslateTransform;
            if (renderTranslation == null)
            {
                renderTranslation = new TranslateTransform(0, 0);
                e.RenderTransform = renderTranslation;
            }

            //set new offset
            renderTranslation.X = offset.X;
            renderTranslation.Y = offset.Y;
        }

        private Point GetTruePosition(UIElement e)
        {
            var renderTranslation = GetRenderTransformOffset(e);
            return new Point(GetLeft(e) + renderTranslation.X, GetTop(e) + renderTranslation.Y);
        }

        private void SetTruePosition(UIElement e, Point p)
        {
            var canvasOffset = new Vector(GetLeft(e), GetTop(e));
            var renderTranslation = p - canvasOffset;

            SetRenderTransformOffset(e, renderTranslation);
        }

        private Point GetCenter(Rect r) => new Point((r.Left + r.Right) / 2.0, (r.Top + r.Bottom) / 2.0);

        #region Private Members

        private readonly ParticleEffectsTimeTracker _timeTracker;
        private readonly Dictionary<UIElement, Vector> _childrenVelocities = new Dictionary<UIElement, Vector>();

        #endregion

        #region Properties

        public double BorderForce { get; set; } = 1000.0;

        public double ChildForce { get; set; } = 200.0;

        public double Drag { get; set; } = 0.9;

        #endregion
    }
}

<|start_filename|>PerMonitorDPI/ImageScaling/MainWindow.xaml.cs<|end_filename|>
﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ImageScaling
{
    /// <summary>
    /// This sample works with the Per Monitor DPI 11/2015 Preview of WPF.
    /// It shows how a developer can use a set of 100, 200, and 400 DPI images to cover the range 
    /// of DPIs that your users may have. It adjusts the images used as the App's window is moved 
    /// to monitors with different DPIs.
    /// This shows how this can work for a normal image element.
    /// One could also build an image aware WPF control (perhaps overriding Visual.OnDpiChanged)
    /// The final version of WPF that has Per Monitor DPI support may do some of this more automatically.
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // Ensure image of appropriate DPI is loaded for first load.
        private void PickRightScaledImage(object sender, EventArgs e)
        {
            Image image = (Image)sender;
            UpdateImageSourceForDpi(image);

            image.DpiChanged += Image_DpiChanged;
        }

        // Ensure image of appropriate DPI is loaded when DPI changes
        private void Image_DpiChanged(object sender, RoutedEventArgs e)
        {
            Image image = (Image)sender;
            UpdateImageSourceForDpi(image);
        }

        private void UpdateImageSourceForDpi(Image image)
        {
            string newImageUrl = ImageDpiHelper.GetDesiredImageUrlForDpi(image);
            ImageDpiHelper.UpdateImageSource(image, newImageUrl);
            textLabel.Text = newImageUrl + " for DPI of " + (VisualTreeHelper.GetDpi(image).PixelsPerDip * 100);
        }
    }
}

<|start_filename|>Animation/LocalAnimations/SampleViewer.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace LocalAnimations
{
    public class SampleViewer : Window
    {
        public SampleViewer()
        {
            var tControl = new TabControl();
            var tItem = new TabItem {Header = "Local Animation Example"};
            var contentFrame = new Frame {Content = new LocalAnimationExample()};
            tItem.Content = contentFrame;
            tControl.Items.Add(tItem);
            tItem = new TabItem {Header = "Interactive Animation Example"};
            contentFrame = new Frame {Content = new InteractiveAnimationExample()};
            tItem.Content = contentFrame;
            tControl.Items.Add(tItem);

            Content = tControl;
            Title = "Local Animations Example";
        }
    }
}

<|start_filename|>Graphics/Converter/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace Converter
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            ShowVars();
        }

        // This method performs the Point operations
        public void PerformOperation(object sender, RoutedEventArgs e)
        {
            var li = (sender as RadioButton);

            // Strings used to display the results
            string syntaxString, resultType, operationString;

            // The local variables point1, point2, vector2, etc are defined in each
            // case block for readability reasons. Each variable is contained within
            // the scope of each case statement.  
            switch (li.Name)
            {
                //begin switch

                case "rb1":
                {
                    // Converts a String to a Point using a PointConverter
                    // Returns a Point.

                    var pConverter = new PointConverter();
                    var string1 = "10,20";

                    var pointResult = (Point) pConverter.ConvertFromString(string1);
                    // pointResult is equal to (10, 20)

                    // Displaying Results
                    syntaxString = "pointResult = (Point)pConverter1.ConvertFromString(string1);";
                    resultType = "Point";
                    operationString = "Converting a String to a Point";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb2":
                {
                    // Converts a String to a Vector using a VectorConverter
                    // Returns a Vector.

                    var vConverter = new VectorConverter();
                    var string1 = "10,20";

                    var vectorResult = (Vector) vConverter.ConvertFromString(string1);
                    // vectorResult is equal to (10, 20)

                    // Displaying Results
                    syntaxString = "vectorResult = (Vector)vConverter.ConvertFromString(string1);";
                    resultType = "Vector";
                    operationString = "Converting a String into a Vector";
                    ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb3":
                {
                    // Converts a String to a Matrix using a MatrixConverter
                    // Returns a Matrix.

                    var mConverter = new MatrixConverter();
                    var string2 = "10,20,30,40,50,60";

                    var matrixResult = (Matrix) mConverter.ConvertFromString(string2);
                    // matrixResult is equal to (10, 20, 30, 40, 50, 60)

                    // Displaying Results
                    syntaxString = "matrixResult = (Vector)mConverter.ConvertFromString(string2);";
                    resultType = "Matrix";
                    operationString = "Converting a String into a Matrix";
                    ShowResults(matrixResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb4":
                {
                    // Converts a String to a Point3D using a Point3DConverter
                    // Returns a Point3D.

                    var p3DConverter = new Point3DConverter();
                    var string3 = "10,20,30";

                    var point3DResult = (Point3D) p3DConverter.ConvertFromString(string3);
                    // point3DResult is equal to (10, 20, 30)

                    // Displaying Results
                    syntaxString = "point3DResult = (Point3D)p3DConverter.ConvertFromString(string3);";
                    resultType = "Point3D";
                    operationString = "Converting a String into a Point3D";
                    ShowResults(point3DResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb5":
                {
                    // Converts a String to a Vector3D using a Vector3DConverter
                    // Returns a Vector3D.

                    var v3DConverter = new Vector3DConverter();
                    var string3 = "10,20,30";

                    var vector3DResult = (Vector3D) v3DConverter.ConvertFromString(string3);
                    // vector3DResult is equal to (10, 20, 30)

                    // Displaying Results
                    syntaxString = "vector3DResult = (Vector3D)v3DConverter.ConvertFromString(string3);";
                    resultType = "Vector3D";
                    operationString = "Converting a String into a Vector3D";
                    ShowResults(vector3DResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb6":
                {
                    // Converts a String to a Size3D using a Size3DConverter
                    // Returns a Size3D.

                    var s3DConverter = new Size3DConverter();
                    var string3 = "10,20,30";

                    var size3DResult = (Size3D) s3DConverter.ConvertFromString(string3);
                    // size3DResult is equal to (10, 20, 30)

                    // Displaying Results
                    syntaxString = "size3DResult = (Size3D)v3DConverter.ConvertFromString(string3);";
                    resultType = "Size3D";
                    operationString = "Converting a String into a Size3D";
                    ShowResults(size3DResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb7":
                {
                    // Converts a String to a Point4D using a Point4DConverter
                    // Returns a Point4D.

                    var p4DConverter = new Point4DConverter();
                    var string4 = "10,20,30,40";

                    var point4DResult = (Point4D) p4DConverter.ConvertFromString(string4);
                    // point4DResult is equal to (10, 20, 30)

                    // Displaying Results
                    syntaxString = "point4DResult = (Point4D)v3DConverter.ConvertFromString(string3);";
                    resultType = "Point4D";
                    operationString = "Converting a String into a Point4D";
                    ShowResults(point4DResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }
            } //end switch
        }

        // Displays the results of the operation
        private void ShowResults(string resultValue, string syntax, string resultType, string opString)
        {
            txtResultValue.Text = resultValue;
            txtSyntax.Text = syntax;
            txtResultType.Text = resultType;
            txtOperation.Text = opString;
        }

        // Displays the values of the variables
        public void ShowVars()
        {
            var s1 = "10, 20";
            var s2 = "10, 20, 30, 40, 50, 60";
            var s3 = "10, 20, 30";
            var s4 = "10, 20, 30, 40";

            // Displaying values in Text objects

            txtString1.Text = s1;
            txtString2.Text = s2;
            txtString3.Text = s3;
            txtString4.Text = s4;
        }
    }
}

<|start_filename|>Sample Applications/DataBindingDemo/ProductCategory.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DataBindingDemo
{
    public enum ProductCategory
    {
        Books,
        Computers,
        DvDs,
        Electronics,
        Home,
        Sports
    }
}

<|start_filename|>Sample Applications/ExpenseIt/ExpenseItDemo/ViewChartWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace ExpenseItDemo
{
    /// <summary>
    ///     Interaction logic for ViewChartWindow.xaml
    /// </summary>
    public partial class ViewChartWindow : Window
    {
        public ViewChartWindow()
        {
            InitializeComponent();
        }

        private void closeButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}

<|start_filename|>Migration and Interoperability/WPFUserControlHost/Form1.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Forms;

namespace WPFUserControlHost
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/Ellipsoid.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    public sealed class Ellipsoid : FunctionMesh
    {
        public Ellipsoid(double ax, double by, double cz)
        {
            Init(new MultExpression(new ConstantExpression(ax), FunctionParser.Parse("cos(u)sin(v)")),
                new MultExpression(new ConstantExpression(by), FunctionParser.Parse("-cos(v)")),
                new MultExpression(new ConstantExpression(cz), FunctionParser.Parse("sin(-u)sin(v)")),
                -Math.PI, Math.PI, 0.0, Math.PI);
        }
    }
}

<|start_filename|>Sample Applications/ExpenseIt/ExpenseItDemo/LineItemCollection.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace ExpenseItDemo
{
    public class LineItemCollection : ObservableCollection<LineItem>
    {
        public event EventHandler LineItemCostChanged;

        public new void Add(LineItem item)
        {
            if (item != null)
            {
                item.PropertyChanged += LineItemPropertyChanged;
            }
            base.Add(item);
        }

        private void LineItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Cost")
            {
                OnLineItemCostChanged(this, new EventArgs());
            }
        }

        private void OnLineItemCostChanged(object sender, EventArgs args)
        {
            LineItemCostChanged?.Invoke(sender, args);
        }
    }
}

<|start_filename|>Animation/Per-FrameAnimation/ParticleEffects/SonicEffect.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace PerFrameAnimation
{
    //uielement
    //visual operations

    public class SonicEffect : OverlayRenderDecorator
    {
        protected override void OnAttachChild(UIElement child)
        {
            child.PreviewMouseLeftButtonUp += OnMouseLeftButtonUp;
        }

        protected override void OnDetachChild(UIElement child)
        {
            CompositionTarget.Rendering -= OnFrameCallback;

            child.PreviewMouseLeftButtonUp -= OnMouseLeftButtonUp;
            _timeTracker = null;
        }

        private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_timeTracker != null)
            {
                _timeTracker.TimerFired -= OnTimerFired;
                _timeTracker = null;
            }

            CompositionTarget.Rendering += OnFrameCallback;
            _timeTracker = new ParticleEffectsTimeTracker {TimerInterval = _ringDelayInSeconds};
            _timeTracker.TimerFired += OnTimerFired;
            _lowerRing = _upperRing = 0;
            _clickPosition = e.GetPosition(this);
        }

        private void OnFrameCallback(object sender, EventArgs e)
        {
            if (_timeTracker != null)
            {
                _timeTracker.Update();
                InvalidateVisual();
            }
        }

        private void OnTimerFired(object sender, EventArgs e)
        {
            if (_upperRing < RingCount)
            {
                _upperRing++;
            }
            else
            {
                _lowerRing++;
                if (_lowerRing >= _upperRing)
                {
                    _timeTracker.TimerFired -= OnTimerFired;
                    _timeTracker = null;
                    CompositionTarget.Rendering -= OnFrameCallback;
                }
            }
        }

        protected override void OnOverlayRender(DrawingContext dc)
        {
            if (_timeTracker != null)
            {
                for (var i = _lowerRing; i < _upperRing; i++)
                {
                    var radius = RingRadius*(i + 1);
                    dc.DrawEllipse(Brushes.Transparent, new Pen(new SolidColorBrush(RingColor), RingThickness),
                        _clickPosition, radius, radius);
                }
            }
        }

        #region Private Members

        private ParticleEffectsTimeTracker _timeTracker;
        private double _ringDelayInSeconds = 0.1;
        private Point _clickPosition;
        private int _lowerRing, _upperRing;

        #endregion

        #region Properties

        public int RingCount { get; set; } = 5;

        public TimeSpan RingDelay
        {
            get { return TimeSpan.FromSeconds(_ringDelayInSeconds); }
            set { _ringDelayInSeconds = value.TotalSeconds; }
        }

        public double RingRadius { get; set; } = 7.0;

        public double RingThickness { get; set; } = 5.0;

        public Color RingColor { get; set; } = Color.FromArgb(128, 128, 128, 128);

        #endregion
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/GenerateImageResources.cs<|end_filename|>
using System;
using System.Drawing;
using System.IO;
using System.Resources;
using System.Windows.Controls;

namespace StickyNotesDemo.GenApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ResourceWriter myResource = new ResourceWriter("Images.resources");
            myResource.AddResource("flash", new Bitmap("flashScreen.png"));
            Image simpleImage = new Image();
            simpleImage.Margin = new Thickness(0);

            BitmapImage bi = new BitmapImage();
            //BitmapImage.UriSource must be in a BeginInit/EndInit block
            bi.BeginInit();





            bi.UriSource = new Uri(@"pack://siteoforigin:,,,/alarm3.png");
            bi.EndInit();
            //set image source
            simpleImage.Source = bi;
            //        simpleImage.Stretch = Stretch.None;
            simpleImage.HorizontalAlignment = HorizontalAlignment.Center;
            simpleImage.Visibility = Visibility.Hidden;
            simpleImage.Name = "AlarmIndicator";
            simpleImage.Width = 13;


            myResource.AddResource("alarm", new Image("alarm3.png"));
            myResource.Close(); 


        }
    }
}


<|start_filename|>Sample Applications/StickyNotesDemo/NativeMethods.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;

namespace StickyNotesDemo
{
    internal class NativeMethods
    {
        public enum Bool
        {
            False = 0,
            True = 1
        }

        // Required constants
        public const int WsExLayered = 0x80000;
        public const int Htcaption = 0x02;
        public const int WmNchittest = 0x84;
        public const int UlwAlpha = 0x02;
        public const byte AcSrcOver = 0x00;
        public const byte AcSrcAlpha = 0x01;

        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern Bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize,
            IntPtr hdcSrc, ref Point pprSrc, int crKey, ref Blendfunction pblend, int dwFlags);

        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDc);

        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern IntPtr GetDC(IntPtr hWnd);

        [DllImport("user32.dll", ExactSpelling = true)]
        public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDc);

        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern Bool DeleteDC(IntPtr hdc);

        [DllImport("gdi32.dll", ExactSpelling = true)]
        public static extern IntPtr SelectObject(IntPtr hDc, IntPtr hObject);

        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern Bool DeleteObject(IntPtr hObject);

        [StructLayout(LayoutKind.Sequential)]
        public struct Point
        {
            public int x;
            public int y;

            public Point(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct Size
        {
            public int cx;
            public int cy;

            public Size(int cx, int cy)
            {
                this.cx = cx;
                this.cy = cy;
            }
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        private struct Argb
        {
            private readonly byte Blue;
            private readonly byte Green;
            private readonly byte Red;
            private readonly byte Alpha;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct Blendfunction
        {
            public byte BlendOp;
            public byte BlendFlags;
            public byte SourceConstantAlpha;
            public byte AlphaFormat;
        }
    }
}

<|start_filename|>Sample Applications/SlidePuzzleDemo/MoveStatus.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace SlidePuzzleDemo
{
    internal enum MoveStatus
    {
        Up,
        Down,
        Left,
        Right,
        BadMove
    }
}

<|start_filename|>Getting Started/Concepts/samps/btncolor_samp.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ButtonColor //needs to match the .xaml page
{
    public partial class Page1 : Page
    {
        // Begin inserting any c# code-behind content here. These methods handle events in XAML files and can be ported from samples. Access modifiers may need to be updated.

        private static int _newcolor;
        private Button _btncsharp;
        private ToolTip _ttp;
        // This function checks the language filter settings to see which code to filter and also grays out tabs with no content
        public void CheckLang(object sender, EventArgs e)
        {
            if (xcsharpCheck.Content == null) // grays out xaml + c# tab
            {
                xamlcsharp.Background = Brushes.Gainsboro;
                xamlcsharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlcsharp, true);
                _ttp.Content = "This sample is not available in XAML + C#.";
                xamlcsharp.ToolTip = (_ttp);
                xamlcsharp.IsEnabled = false;
            }
            else if (xcsharpCheck.Content != null)
            {
                xamlcsharp.IsEnabled = true;
            }

            if (xvbCheck.Content == null) // grays out xaml + vb tab
            {
                xamlvb.Background = Brushes.Gainsboro;
                xamlvb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlvb, true);
                _ttp.Content = "This sample is not available in XAML + Visual Basic.NET";
                xamlvb.ToolTip = (_ttp);
                xamlvb.IsEnabled = false;
            }
            else if (xvbCheck.Content != null)
            {
                xamlvb.IsEnabled = true;
            }

            if (xaml.Content == null) // grays out xaml
            {
                xaml.IsEnabled = false;
                xaml.Background = Brushes.Gainsboro;
                xaml.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xaml, true);
                _ttp.Content = "This sample is not available in XAML.";
                xaml.ToolTip = (_ttp);
            }
            else if (xaml.Content != null)
            {
                xaml.IsEnabled = true;
            }

            if (csharp.Content == null) // grays out c#
            {
                csharp.IsEnabled = false;
                csharp.Background = Brushes.Gainsboro;
                csharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(csharp, true);
                _ttp.Content = "This sample is not available in C#.";
                csharp.ToolTip = (_ttp);
            }
            else if (csharp.Content != null)
            {
                csharp.IsEnabled = true;
            }

            if (vb.Content == null) // grays out vb
            {
                vb.IsEnabled = false;
                vb.Background = Brushes.Gainsboro;
                vb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(vb, true);
                _ttp.Content = "This sample is not available in Visual Basic.NET.";
                vb.ToolTip = (_ttp);
            }
            else if (vb.Content != null)
            {
                vb.IsEnabled = true;
            }

            if (managedcpp.Content == null) // grays out cpp
            {
                managedcpp.IsEnabled = false;
                managedcpp.Background = Brushes.Gainsboro;
                managedcpp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(managedcpp, true);
                _ttp.Content = "This sample is not available in Managed C++.";
                managedcpp.ToolTip = (_ttp);
            }
            else if (managedcpp.Content != null)
            {
                managedcpp.IsEnabled = true;
            }
            if (Welcome.Page1.MyDouble == 1) // XAML only
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 2) // CSharp
            {
                csharp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 3) // Visual Basic
            {
                vb.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 4) // Managed CPP
            {
                managedcpp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 5) // No Filter
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Visible;
                vb.Visibility = Visibility.Visible;
                managedcpp.Visibility = Visibility.Visible;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Visible;
            }
            else if (Welcome.Page1.MyDouble == 6) // XAML + CSharp
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 7) // XAML + VB
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Visible;
            }
        }

        private void OnClick1(object sender, RoutedEventArgs e)
        {
            btn1.Background = Brushes.LightBlue;
        }

        private void OnClick2(object sender, RoutedEventArgs e)
        {
            btn2.Background = Brushes.Pink;
        }

        private void OnClick3(object sender, RoutedEventArgs e)
        {
            btn1.Background = Brushes.Pink;
            btn2.Background = Brushes.LightBlue;
        }

        private void OnClick4(object sender, RoutedEventArgs e)
        {
            switch (_newcolor)
            {
                case 0:
                    btn4.Background = Brushes.Red;
                    btn4.Foreground = Brushes.Beige;
                    btn4.Content = "Font Size 10";
                    btn4.FontSize = 10;
                    break;

                case 1:
                    btn4.Background = Brushes.CadetBlue;
                    btn4.Foreground = Brushes.LemonChiffon;
                    btn4.Content = "Font Size 12";
                    btn4.FontSize = 12;
                    break;

                case 2:
                    btn4.Background = Brushes.Purple;
                    btn4.Foreground = Brushes.PeachPuff;
                    btn4.Content = "Font Size 14";
                    btn4.FontSize = 14;
                    break;

                case 3:
                    btn4.Background = Brushes.BlanchedAlmond;
                    btn4.Foreground = Brushes.DarkRed;
                    btn4.Content = "Font Size 16";
                    btn4.FontSize = 16;
                    break;

                case 4:
                    btn4.Background = Brushes.Green;
                    btn4.Foreground = Brushes.White;
                    btn4.Content = "Font Size 18";
                    btn4.FontSize = 18;
                    break;
            }
            _newcolor = _newcolor + 1;
            if (_newcolor > 4)
            {
                _newcolor = 0;
            }
        }

        private void OnClick5(object sender, RoutedEventArgs e)
        {
            btn6.FontSize = 16;
            btn6.Content = "This is my favorite photo.";
            btn6.Background = Brushes.Red;
        }

        private void OnClick6(object sender, RoutedEventArgs e)
        {
            btn7.FontSize = 16;
            txt.Text = "You clicked the button.";
            btn7.Background = Brushes.Yellow;
        }

        private void OnClick7(object sender, RoutedEventArgs e)
        {
            _btncsharp = new Button
            {
                Content = "Created with C# code.",
                Background = SystemColors.ControlDarkDarkBrush,
                FontSize = SystemFonts.CaptionFontSize
            };
            cv2.Children.Add(_btncsharp);
        }
    }
}

<|start_filename|>Application Management/CodeOnlyWindowsApplication/EntryPoint.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace CodeOnlyWindowsApplication
{
    public class EntryPoint
    {
        /// <summary>
        ///     WPF applications must run in a single-threaded apartment
        /// </summary>
        [STAThread]
        public static void Main()
        {
            // Start the WPF application
            var app = new App();
            app.Run();
        }
    }
}

<|start_filename|>Elements/HeightProperties/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace HeightProperties
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ChangeHeight(object sender, SelectionChangedEventArgs args)
        {
            var li = ((sender as ListBox).SelectedItem as ListBoxItem);
            var sz1 = double.Parse(li.Content.ToString());
            rect1.Height = sz1;
            rect1.UpdateLayout();
            txt1.Text = "ActualHeight is set to " + rect1.ActualHeight;
            txt2.Text = "Height is set to " + rect1.Height;
            txt3.Text = "MinHeight is set to " + rect1.MinHeight;
            txt4.Text = "MaxHeight is set to " + rect1.MaxHeight;
        }

        private void ChangeMinHeight(object sender, SelectionChangedEventArgs args)
        {
            var li = ((sender as ListBox).SelectedItem as ListBoxItem);
            var sz1 = double.Parse(li.Content.ToString());
            rect1.MinHeight = sz1;
            rect1.UpdateLayout();
            txt1.Text = "ActualHeight is set to " + rect1.ActualHeight;
            txt2.Text = "Height is set to " + rect1.Height;
            txt3.Text = "MinHeight is set to " + rect1.MinHeight;
            txt4.Text = "MaxHeight is set to " + rect1.MaxHeight;
        }

        private void ChangeMaxHeight(object sender, SelectionChangedEventArgs args)
        {
            var li = ((sender as ListBox).SelectedItem as ListBoxItem);
            var sz1 = double.Parse(li.Content.ToString());
            rect1.MaxHeight = sz1;
            rect1.UpdateLayout();
            txt1.Text = "ActualHeight is set to " + rect1.ActualHeight;
            txt2.Text = "Height is set to " + rect1.Height;
            txt3.Text = "MinHeight is set to " + rect1.MinHeight;
            txt4.Text = "MaxHeight is set to " + rect1.MaxHeight;
        }

        private void ClipRect(object sender, RoutedEventArgs args)
        {
            myCanvas.ClipToBounds = true;
            txt5.Text = "Canvas.ClipToBounds is set to " + myCanvas.ClipToBounds;
        }

        private void UnclipRect(object sender, RoutedEventArgs args)
        {
            myCanvas.ClipToBounds = false;
            txt5.Text = "Canvas.ClipToBounds is set to " + myCanvas.ClipToBounds;
        }
    }
}

<|start_filename|>Graphics/Point/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Point
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            ShowVars();
        }

        // This method performs the Point operations
        public void PerformOperation(object sender, RoutedEventArgs e)
        {
            var li = sender as RadioButton;

            // Strings used to display the results
            string syntaxString, resultType, operationString;

            // The local variables point1, point2, vector2, etc are defined in each
            // case block for readability reasons. Each variable is contained within
            // the scope of each case statement.  
            switch (li?.Name)
            {
                //begin switch

                case "rb1":
                {
                    // Translates a Point by a Vector using the overloaded + operator. 
                    // Returns a Point.
                    var point1 = new System.Windows.Point(10, 5);
                    var vector1 = new Vector(20, 30);

                    var pointResult = point1 + vector1;
                    // pointResult is equal to (30, 35)

                    // Note: Adding a Point to a Point is not a legal operation 

                    // Displaying Results
                    syntaxString = "pointResult = point1 + vector1;";
                    resultType = "Point";
                    operationString = "Adding a Point and Vector";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb2":
                {
                    // Translates a Point by a Vector using the static Add method.
                    // Returns a Point.  
                    var point1 = new System.Windows.Point(10, 5);
                    var vector1 = new Vector(20, 30);

                    var pointResult = System.Windows.Point.Add(point1, vector1);
                    // pointResult is equal to (30, 35)

                    // Displaying Results
                    syntaxString = "pointResult = Point.Add(point1, vector1);";
                    resultType = "Point";
                    operationString = "Adding a Point and Vector";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb3":
                {
                    // Subtracts a Vector from a Point using the overloaded - operator.
                    // Returns a Point.
                    var point1 = new System.Windows.Point(10, 5);
                    var vector1 = new Vector(20, 30);

                    var pointResult = point1 - vector1;
                    // pointResult is equal to (-10, -25) 

                    // Displaying Results
                    syntaxString = "pointResult = point1 - vector1;";
                    resultType = "Point";
                    operationString = "Subtracting a Vector from a Point";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb4":
                {
                    // Subtracts a Vector from a Point using the static Subtract method. 
                    // Returns a Point.
                    var point1 = new System.Windows.Point(10, 5);
                    var vector1 = new Vector(20, 30);

                    var pointResult = System.Windows.Point.Subtract(point1, vector1);
                    // pointResult is equal to (-10, -25)

                    // Displaying Results
                    syntaxString = "pointResult = Point.Subtract(point1, vector1);";
                    resultType = "Point";
                    operationString = "Subtracting a Vector from a Point";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb5":
                {
                    // Subtracts a Point from a Point using the overloaded - operator.
                    // Returns a Vector.
                    var point1 = new System.Windows.Point(10, 5);
                    var point2 = new System.Windows.Point(15, 40);

                    var vectorResult = point1 - point2;
                    // vectorResult is equal to (-5, -35)

                    // Displaying Results
                    syntaxString = "vectorResult = point1 - point2;";
                    resultType = "Vector";
                    operationString = "Subtracting a Point from a Point";
                    ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb6":
                {
                    // Subtracts a Point from a Point using the static Subtract method.  
                    // Returns a Vector.
                    var point1 = new System.Windows.Point(10, 5);
                    var point2 = new System.Windows.Point(15, 40);

                    var vectorResult = System.Windows.Point.Subtract(point1, point2);
                    // vectorResult is equal to (-5, -35)

                    // Displaying Results
                    syntaxString = "vectorResult = Point.Subtract(point1, point2);";
                    resultType = "Vector";
                    operationString = "Subtracting a Point from a Point";
                    ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb7":
                {
                    // Offsets the X and Y values of a Point.
                    var point1 = new System.Windows.Point(10, 5);

                    point1.Offset(20, 30);
                    // point1 is equal to (30, 35)

                    // Note: This operation is equivalent to adding a point 
                    // to vector with the corresponding X,Y values.

                    // Displaying Results
                    syntaxString = "point1.Offset(20,30);";
                    resultType = "Point";
                    operationString = "Offsetting a Point";
                    ShowResults(point1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb8":
                {
                    // Multiplies a Point by a Matrix.  
                    // Returns a Point.
                    var point1 = new System.Windows.Point(10, 5);
                    var matrix1 = new Matrix(40, 50, 60, 70, 80, 90);

                    var pointResult = point1*matrix1;
                    // pointResult is equal to (780, 940)

                    // Displaying Results
                    resultType = "Point";
                    syntaxString = "pointResult = point1 * matrix1;";
                    operationString = "Multiplying a Point by a Matrix";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb9":
                {
                    // Multiplies a Point by a Matrix.  
                    // Returns a Point.
                    var point1 = new System.Windows.Point(10, 5);
                    var matrix1 = new Matrix(40, 50, 60, 70, 80, 90);

                    var pointResult = System.Windows.Point.Multiply(point1, matrix1);
                    // pointResult is equal to (780, 940)

                    // Displaying Results
                    resultType = "Point";
                    syntaxString = "pointResult = Point.Multiply(point1, matrix1);";
                    operationString = "Multiplying a Point by a Matrix";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb10":
                {
                    // Checks if two Points are equal using the overloaded equality operator.
                    var point1 = new System.Windows.Point(10, 5);
                    var point2 = new System.Windows.Point(15, 40);

                    var areEqual = (point1 == point2);
                    // areEqual is False

                    // Displaying Results
                    syntaxString = "areEqual = (point1 == point2);";
                    resultType = "Boolean";
                    operationString = "Checking if two points are equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                    break;
                }


                case "rb11":
                {
                    // Checks if two Points are equal using the static Equals method.
                    var point1 = new System.Windows.Point(10, 5);
                    var point2 = new System.Windows.Point(15, 40);

                    var areEqual = System.Windows.Point.Equals(point1, point2);
                    // areEqual is False	

                    // Displaying Results
                    syntaxString = "areEqual = Point.Equals(point1, point2);";
                    resultType = "Boolean";
                    operationString = "Checking if two points are equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb12":
                {
                    // Compares an Object and a Point for equality using the non-static Equals method.
                    var point1 = new System.Windows.Point(10, 5);
                    var point2 = new System.Windows.Point(15, 40);

                    var areEqual = point1.Equals(point2);
                    // areEqual is False	


                    // Displaying Results
                    syntaxString = "areEqual = point1.Equals(point2);";
                    resultType = "Boolean";
                    operationString = "Checking if two points are equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb13":
                {
                    // Compares an Object and a Vector for equality using the non-static Equals method.
                    var vector1 = new Vector(20, 30);
                    var vector2 = new Vector(45, 70);

                    var areEqual = vector1.Equals(vector2);
                    // areEqual is False	


                    // Displaying Results
                    syntaxString = "areEqual = vector1.Equals(vector2);";
                    resultType = "Boolean";
                    operationString = "Checking if two vectors are equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb14":
                {
                    // Converts a string representation of a point into a Point structure

                    var pointResult = System.Windows.Point.Parse("1,3");
                    // pointResult is equal to (1, 3)

                    // Displaying Results
                    syntaxString = "pointResult = Point.Parse(\"1,3\");";
                    resultType = "Matrix";
                    operationString = "Converts a string into a Point structure.";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb15":
                {
                    // Gets a string representation of a Point structure
                    var point1 = new System.Windows.Point(10, 5);

                    var pointString = point1.ToString();
                    // pointString is equal to 10,5

                    // Displaying Results
                    syntaxString = "pointString = point1.ToString();";
                    resultType = "String";
                    operationString = "Getting the string representation of a Point";
                    ShowResults(pointString, syntaxString, resultType, operationString);
                    break;
                }
                case "rb16":
                {
                    // Gets the hashcode of a Point structure

                    var point1 = new System.Windows.Point(10, 5);

                    var pointHashCode = point1.GetHashCode();

                    // Displaying Results
                    syntaxString = "pointHashCode = point1.GetHashCode();";
                    resultType = "int";
                    operationString = "Getting the hashcode of Point";
                    ShowResults(pointHashCode.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb17":
                {
                    // Explicitly converts a Point structure into a Size structure
                    // Returns a Size.

                    var point1 = new System.Windows.Point(10, 5);

                    var size1 = (Size) point1;
                    // size1 has a width of 10 and a height of 5

                    // Displaying Results
                    syntaxString = "size1 = (Size)point1;";
                    resultType = "Size";
                    operationString = "Expliciting casting a Point into a Size";
                    ShowResults(size1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb18":
                {
                    // Explicitly converts a Point structure into a Vector structure
                    // Returns a Vector.

                    var point1 = new System.Windows.Point(10, 5);

                    var vector1 = (Vector) point1;
                    // vector1 is equal to (10,5)

                    // Displaying Results
                    syntaxString = "vector1 = (Vector)point1;";
                    resultType = "Vector";
                    operationString = "Expliciting casting a Point into a Vector";
                    ShowResults(vector1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                // task example.  Not accessed through radio buttons
                case "rb20":
                {
                    // Checks if two Points are not equal using the overloaded inequality operator.

                    // Declaring point1 and initializing x,y values
                    var point1 = new System.Windows.Point(10, 5);

                    // Declaring point2 without initializing x,y values
                    var point2 = new System.Windows.Point
                    {
                        X = 15,
                        Y = 40
                    };

                    // Boolean to hold the result of the comparison

                    // assigning values to point2

                    // checking for inequality
                    var areNotEqual = (point1 != point2);

                    // areNotEqual is True

                    // Displaying Results
                    syntaxString = "areNotEqual = (point1 != point2);";
                    resultType = "Boolean";
                    operationString = "Checking if two points are not equal";
                    ShowResults(areNotEqual.ToString(), syntaxString, resultType, operationString);
                    break;
                }
            } //end switch
        }

        // Displays the results of the operation
        private void ShowResults(string resultValue, string syntax, string resultType, string opString)
        {
            txtResultValue.Text = resultValue;
            txtSyntax.Text = syntax;
            txtResultType.Text = resultType;
            txtOperation.Text = opString;
        }

        // Displays the values of the variables
        public void ShowVars()
        {
            var p1 = new System.Windows.Point(10, 5);
            var p2 = new System.Windows.Point(15, 40);

            var v1 = new Vector(20, 30);
            var v2 = new Vector(45, 70);

            var m1 = new Matrix(40, 50, 60, 70, 80, 90);

            // Displaying values in Text objects
            txtPoint1.Text = p1.ToString();
            txtPoint2.Text = p2.ToString();
            txtVector1.Text = v1.ToString();
            txtVector2.Text = v2.ToString();
            txtMatrix1.Text = m1.ToString();
        }
    }
}

<|start_filename|>Data Binding/DirectionalBinding/NetIncome.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace DirectionalBinding
{
    public class NetIncome : INotifyPropertyChanged
    {
        private int _food;
        private int _misc;
        private int _rent = 2000;
        private int _savings;
        private int _totalIncome = 5000;

        public NetIncome()
        {
            _savings = _totalIncome - (_rent + _food + _misc);
        }

        public int TotalIncome
        {
            get { return _totalIncome; }
            set
            {
                if (TotalIncome != value)
                {
                    _totalIncome = value;
                    OnPropertyChanged("TotalIncome");
                }
            }
        }

        public int Rent
        {
            get { return _rent; }
            set
            {
                if (Rent != value)
                {
                    _rent = value;
                    OnPropertyChanged("Rent");
                    UpdateSavings();
                }
            }
        }

        public int Food
        {
            get { return _food; }
            set
            {
                if (Food != value)
                {
                    _food = value;
                    OnPropertyChanged("Food");
                    UpdateSavings();
                }
            }
        }

        public int Misc
        {
            get { return _misc; }
            set
            {
                if (Misc != value)
                {
                    _misc = value;
                    OnPropertyChanged("Misc");
                    UpdateSavings();
                }
            }
        }

        public int Savings
        {
            get { return _savings; }
            set
            {
                if (Savings != value)
                {
                    _savings = value;
                    OnPropertyChanged("Savings");
                    UpdateSavings();
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void UpdateSavings()
        {
            Savings = TotalIncome - (Rent + Misc + Food);
            if (Savings < 0)
            {
            }
            else if (Savings >= 0)
            {
            }
        }

        private void OnPropertyChanged(string info)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}

<|start_filename|>Graphics/VisualBrush/MagnifyingGlassExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace VisualBrush
{
    public partial class MagnifyingGlassExample : Page
    {
        private static readonly double DistanceFromMouse = 5;

        private void UpdateMagnifyingGlass(object sender, MouseEventArgs args)
        {
            Mouse.SetCursor(Cursors.Cross);

            // Get the current position of the mouse pointer.
            var currentMousePosition = args.GetPosition(this);

            // Determine whether the magnifying glass should be shown to the
            // the left or right of the mouse pointer.
            if (ActualWidth - currentMousePosition.X > magnifyingGlassEllipse.Width + DistanceFromMouse)
            {
                Canvas.SetLeft(magnifyingGlassEllipse, currentMousePosition.X + DistanceFromMouse);
            }
            else
            {
                Canvas.SetLeft(magnifyingGlassEllipse,
                    currentMousePosition.X - DistanceFromMouse - magnifyingGlassEllipse.Width);
            }

            // Determine whether the magnifying glass should be shown 
            // above or below the mouse pointer.
            if (ActualHeight - currentMousePosition.Y > magnifyingGlassEllipse.Height + DistanceFromMouse)
            {
                Canvas.SetTop(magnifyingGlassEllipse, currentMousePosition.Y + DistanceFromMouse);
            }
            else
            {
                Canvas.SetTop(magnifyingGlassEllipse,
                    currentMousePosition.Y - DistanceFromMouse - magnifyingGlassEllipse.Height);
            }


            // Update the visual brush's Viewbox to magnify a 20 by 20 rectangle,
            // centered on the current mouse position.
            myVisualBrush.Viewbox =
                new Rect(currentMousePosition.X - 10, currentMousePosition.Y - 10, 20, 20);
        }
    }
}

<|start_filename|>Migration and Interoperability/WindowsFormsHostingWpfControl/WPFControls/MyControlEventArgs.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace WPFControls
{
    public class MyControlEventArgs : EventArgs
    {
        public MyControlEventArgs(bool result,
            string name,
            string address,
            string city,
            string state,
            string zip)
        {
            IsOk = result;
            MyName = name;
            MyStreetAddress = address;
            MyCity = city;
            MyState = state;
            MyZip = zip;
        }

        public string MyName { get; set; }
        public string MyStreetAddress { get; set; }
        public string MyCity { get; set; }
        public string MyState { get; set; }
        public string MyZip { get; set; }
        public bool IsOk { get; set; }
    }
}

<|start_filename|>Animation/Per-FrameAnimation/Simple/SimpleExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Controls;
using System.Windows.Media;

namespace PerFrameAnimation
{
    /// <summary>
    ///     Interaction logic for Page1.xaml
    /// </summary>
    public partial class SimpleExample : Page
    {
        private readonly Random _rand = new Random();

        public SimpleExample()
        {
            CompositionTarget.Rendering += UpdateColor;
        }

        private void UpdateColor(object sender, EventArgs e)
        {
            // Set a random color
            animatedBrush.Color = Color.FromRgb((byte) _rand.Next(255),
                (byte) _rand.Next(255),
                (byte) _rand.Next(255));
        }
    }
}

<|start_filename|>Input and Commands/CommandSourceControlWithDispatcherTimer/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;

namespace CommandSourceControlWithDispatcherTimer
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static RoutedCommand CustomCommand = new RoutedCommand();
        //  The timer.
        private readonly DispatcherTimer _dispatcherTimer;

        public MainWindow()
        {
            InitializeComponent();
            _dispatcherTimer = new DispatcherTimer();
            _dispatcherTimer.Tick += dispatcherTimer_Tick;
            _dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
            _dispatcherTimer.Start();
        }

        //  System.Windows.Threading.DispatcherTimer.Tick handler
        //
        //  Updates the current seconds display and calls
        //  InvalidateRequerySuggested on the CommandManager to force 
        //  the Command to raise the CanExecuteChanged event.
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            // Updating the Label which displays the current second
            lblSeconds.Content = DateTime.Now.Second;

            // Forcing the CommandManager to raise the RequerySuggested event
            CommandManager.InvalidateRequerySuggested();
        }

        //  Executed Event Handler
        //
        //  Updates the output TextBox with the current seconds 
        //  and the target second, which is passed through Args.Parameter.
        private void CustomCommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            txtResults.Text = "Command Executed at " +
                              DateTime.Now.Second + " seconds after the minute \n\n" +
                              "The target second is set to " +
                              e.Parameter;
        }

        //CanExecute Event Handler
        //
        //  Retrun True, if the current seconds are greater than the target value
        //  which is set on the Slider that is defined in the XMAL file.
        private void CustomCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (secondSlider != null)
            {
                e.CanExecute = DateTime.Now.Second > secondSlider.Value;
            }
            else
            {
                e.CanExecute = false;
            }
        }

        // Moves the slider when the mouse wheel is rotated.
        private void OnSliderMouseWheel(object sender, MouseWheelEventArgs e)
        {
            var source = e.Source as Slider;

            if (source != null)
            {
                if (e.Delta > 0)
                {
                    //execute the Slider DecreaseSmall RoutedCommand
                    //the slider.value propety is passed as the command parameter
                    Slider.DecreaseSmall.Execute(
                        source.Value, source);
                }
                else
                {
                    //execute the Slider IncreaseSmall RoutedCommand
                    //the slider.value propety is passed as the command parameter
                    Slider.IncreaseSmall.Execute(
                        source.Value, source);
                }
            }
        }

        // Moves the slider when the mouse extended buttons are pressed.
        private void OnSliderMouseUp(object sender, MouseButtonEventArgs e)
        {
            var source = e.Source as Slider;

            if (source != null)
            {
                if (e.ChangedButton == MouseButton.XButton1)
                {
                    //  Execute the Slider DecreaseSmall RoutedCommand
                    //  The slider.value propety is passed as the command parameter
                    Slider.DecreaseSmall.Execute(
                        source.Value, source);
                }
                if (e.ChangedButton == MouseButton.XButton2)
                {
                    //  Execute the Slider IncreaseSmall RoutedCommand
                    //  The slider.value propety is passed as the command parameter
                    Slider.IncreaseSmall.Execute(
                        source.Value, source);
                }
            }
        }
    }

    //Converter to convert the Slider value property from a Double to an Int
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/InvalidExpressionException.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    [Serializable]
    public class InvalidExpressionException : FunctionParserException
    {
        public InvalidExpressionException(string msg) : base(msg)
        {
        }

        public InvalidExpressionException(string msg, Exception innerException) : base(msg, innerException)
        {
        }
    }
}

<|start_filename|>Data Binding/Colors/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Colors
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnNewColorClicked(object sender, RoutedEventArgs args)
        {
            var button = (Button) sender;
            var colorList = (ColorItemList) button.DataContext;
            var cv = (CollectionView) CollectionViewSource.GetDefaultView(colorList);

            // add a new color based on the current one, then select the new one
            var newItem = new ColorItem((ColorItem) cv.CurrentItem);
            colorList.Add(newItem);
            cv.MoveCurrentTo(newItem);
        }

        // Event handler for the SortBy radio buttons
        private void OnSortByChanged(object sender, RoutedEventArgs args)
        {
            var rb = (RadioButton) sender;
            var sortBy = rb.Content.ToString();

            if (sortBy != null)
            {
                // sort by the user's chosen property
                var cv = (CollectionView) CollectionViewSource.GetDefaultView((IEnumerable) rb.DataContext);
                cv.SortDescriptions.Clear();
                cv.SortDescriptions.Add(new SortDescription(sortBy, ListSortDirection.Descending));
            }
        }
    }
}

<|start_filename|>Graphics/BitmapEffectsGallery/BlurInteractiveExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Effects;

namespace SDKSample
{
    public partial class BlurInteractiveExample : Page
    {
        // Add Bevel effect.
        private void ChangeSelection(object sender, RoutedEventArgs args)
        {
            var cb = (ComboBox) sender;
            var cbi = (ComboBoxItem) cb.SelectedValue;

            var s = cbi.Content.ToString();
            if (s == "Box")
            {
                InteractiveEffect.KernelType = KernelType.Box;
            }
            else if (s == "Gaussian")
            {
                InteractiveEffect.KernelType = KernelType.Gaussian;
            }
        }
    }
}

<|start_filename|>Animation/CustomAnimation/ExponentialDoubleAnimation.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace CustomAnimation
{
    /// <summary>
    ///     ExponentialDoubleAnimation - gets exponentially faster / slower
    /// </summary>
    public class ExponentialDoubleAnimation : DoubleAnimationBase
    {
        public enum EdgeBehaviorEnum
        {
            EaseIn,
            EaseOut,
            EaseInOut
        }

        public static readonly DependencyProperty EdgeBehaviorProperty =
            DependencyProperty.Register("EdgeBehavior", typeof (EdgeBehaviorEnum), typeof (ExponentialDoubleAnimation),
                new PropertyMetadata(EdgeBehaviorEnum.EaseIn));

        public static readonly DependencyProperty PowerProperty =
            DependencyProperty.Register("Power", typeof (double), typeof (ExponentialDoubleAnimation),
                new PropertyMetadata(2.0));

        public static readonly DependencyProperty FromProperty =
            DependencyProperty.Register("From",
                typeof (double?),
                typeof (ExponentialDoubleAnimation),
                new PropertyMetadata(null));

        public static readonly DependencyProperty ToProperty =
            DependencyProperty.Register("To",
                typeof (double?),
                typeof (ExponentialDoubleAnimation),
                new PropertyMetadata(null));

        /// <summary>
        ///     which side gets the effect
        /// </summary>
        public EdgeBehaviorEnum EdgeBehavior
        {
            get { return (EdgeBehaviorEnum) GetValue(EdgeBehaviorProperty); }
            set { SetValue(EdgeBehaviorProperty, value); }
        }

        /// <summary>
        ///     exponential rate of growth
        /// </summary>
        public double Power
        {
            get { return (double) GetValue(PowerProperty); }
            set
            {
                if (value > 0.0)
                {
                    SetValue(PowerProperty, value);
                }
                else
                {
                    throw new ArgumentException("cannot set power to less than 0.0. Value: " + value);
                }
            }
        }

        /// <summary>
        ///     Specifies the starting value of the animation.
        /// </summary>
        public double? From
        {
            get { return (double?) GetValue(FromProperty); }
            set { SetValue(FromProperty, value); }
        }

        /// <summary>
        ///     Specifies the ending value of the animation.
        /// </summary>
        public double? To
        {
            get { return (double?) GetValue(ToProperty); }
            set { SetValue(ToProperty, value); }
        }

        protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue,
            AnimationClock clock)
        {
            double returnValue;
            var start = From ?? defaultOriginValue;
            var delta = To - start ?? defaultOriginValue - start;

            switch (EdgeBehavior)
            {
                case EdgeBehaviorEnum.EaseIn:
                    returnValue = EaseIn(clock.CurrentProgress.Value, start, delta, Power);
                    break;
                case EdgeBehaviorEnum.EaseOut:
                    returnValue = EaseOut(clock.CurrentProgress.Value, start, delta, Power);
                    break;
                default:
                    returnValue = EaseInOut(clock.CurrentProgress.Value, start, delta, Power);
                    break;
            }
            return returnValue;
        }

        protected override Freezable CreateInstanceCore() => new ExponentialDoubleAnimation();

        private static double EaseIn(double timeFraction, double start, double delta, double power)
        {
            // math magic: simple exponential growth
            var returnValue = Math.Pow(timeFraction, power);
            returnValue *= delta;
            returnValue = returnValue + start;
            return returnValue;
        }

        private static double EaseOut(double timeFraction, double start, double delta, double power)
        {
            // math magic: simple exponential decay
            var returnValue = Math.Pow(timeFraction, 1/power);
            returnValue *= delta;
            returnValue = returnValue + start;
            return returnValue;
        }

        private static double EaseInOut(double timeFraction, double start, double delta, double power)
        {
            double returnValue;

            // we cut each effect in half by multiplying the time fraction by two and halving the distance.
            if (timeFraction <= 0.5)
            {
                returnValue = EaseOut(timeFraction*2, start, delta/2, power);
            }
            else
            {
                returnValue = EaseIn((timeFraction - 0.5)*2, start, delta/2, power);
                returnValue += (delta/2);
            }
            return returnValue;
        }
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/Photo.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Media.Imaging;

namespace PhotoViewerDemo
{
    /// <summary>
    ///     This class describes a single photo - its location, the image and
    ///     the metadata extracted from the image.
    /// </summary>
    public class Photo
    {
        private readonly Uri _source;

        public Photo(string path)
        {
            Source = path;
            _source = new Uri(path);
            Image = BitmapFrame.Create(_source);
            Metadata = new ExifMetadata(_source);
        }

        public string Source { get; }
        public BitmapFrame Image { get; set; }
        public ExifMetadata Metadata { get; }

        public override string ToString() => _source.ToString();
    }
}

<|start_filename|>Elements/ThicknessConverter/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ThicknessConverter
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ChangeThickness(object sender, SelectionChangedEventArgs args)
        {
            var li = ((sender as ListBox).SelectedItem as ListBoxItem);
            var myThicknessConverter = new System.Windows.ThicknessConverter();
            var th1 = (Thickness) myThicknessConverter.ConvertFromString(li.Content.ToString());
            border1.BorderThickness = th1;
            bThickness.Text = "Border.BorderThickness =" + li.Content;
        }

        private void ChangeColor(object sender, SelectionChangedEventArgs args)
        {
            var li2 = ((sender as ListBox).SelectedItem as ListBoxItem);
            var myBrushConverter = new BrushConverter();
            border1.BorderBrush = (Brush) myBrushConverter.ConvertFromString((string) li2.Content);
            bColor.Text = "Border.Borderbrush =" + li2.Content;
        }
    }
}

<|start_filename|>Input and Commands/ProgrammaticFocusControl/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace ProgrammaticFocusControl
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // The direction to move/predict focus.
        private FocusNavigationDirection _focusMoveValue;
        // Used to keep track of when a PredictFocus has happened.
        private bool _focusPredicted;
        private Control _predictedControl;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            // Sets keyboard focus on the first Button in the sample.
            Keyboard.Focus(firstButton);
        }

        private void OnPredictFocus(object sender, RoutedEventArgs e)
        {
            DependencyObject predictionElement = null;

            var elementWithFocus = Keyboard.FocusedElement as UIElement;

            if (elementWithFocus != null)
            {
                // Only these four directions are currently supported
                // by PredictFocus, so we need to filter on these only.
                if ((_focusMoveValue == FocusNavigationDirection.Up) ||
                    (_focusMoveValue == FocusNavigationDirection.Down) ||
                    (_focusMoveValue == FocusNavigationDirection.Left) ||
                    (_focusMoveValue == FocusNavigationDirection.Right))
                {
                    // Get the element which would receive focus if focus were changed.
                    predictionElement = elementWithFocus.PredictFocus(_focusMoveValue);

                    var controlElement = predictionElement as Control;

                    // If a ContentElement.
                    if (controlElement != null)
                    {
                        controlElement.Foreground = Brushes.DarkBlue;
                        controlElement.FontSize += 10;
                        controlElement.FontWeight = FontWeights.ExtraBold;

                        // Fields used to reset the UI when the mouse 
                        // button is released.
                        _focusPredicted = true;
                        _predictedControl = controlElement;
                    }
                }
            }
        }

        private void OnMoveFocus(object sender, RoutedEventArgs e)
        {
            // Creating a FocusNavigationDirection object and setting it to a
            // local field that contains the direction selected.
            var focusDirection = _focusMoveValue;

            // MoveFocus takes a TraveralReqest as its argument.
            var request = new TraversalRequest(focusDirection);

            // Gets the element with keyboard focus.
            var elementWithFocus = Keyboard.FocusedElement as UIElement;

            // Change keyboard focus.
            elementWithFocus?.MoveFocus(request);
        }

        // Sets the FocusNavigationDirection.
        private void OnFocusSelected(object sender, RoutedEventArgs e)
        {
            var source = e.Source as RadioButton;

            if (source != null)
            {
                _focusMoveValue = (FocusNavigationDirection) Enum.Parse(
                    typeof (FocusNavigationDirection), (string) source.Content);
            }
        }

        // Resets the UI after PredictFocus changes the UI.
        private void OnPredictFocusMouseUp(object sender, RoutedEventArgs e)
        {
            if (_focusPredicted)
            {
                _predictedControl.Foreground = Brushes.Black;
                _predictedControl.FontSize -= 10;
                _predictedControl.FontWeight = FontWeights.Normal;

                _focusPredicted = false;
            }
        }
    }
}

<|start_filename|>Clipboard/ClipboardViewer/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using Microsoft.Win32;

namespace ClipboardViewer
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // This is called when UI is laid out, rendered and ready for interaction.
        private void WindowLoaded(object sender, RoutedEventArgs args)
        {
            // Check the current Clipboard data format status
            RefreshClipboardDataFormat();

            // Set the text copy information on RichTextBox
            SetTextOnRichTextBox("Please type clipboard copy data here!");
        }

        private void ClearClipboard(object sender, RoutedEventArgs args)
        {
            // Clear Clipboard
            Clipboard.Clear();

            // Update the current Clipboard data format status after clear Clipboard
            RefreshClipboardDataFormat();
        }

        private void RefreshClipboardDataFormatStatus(object sender, RoutedEventArgs args)
        {
            // Refresh the all clipboard data format into the information panel
            RefreshClipboardDataFormat();
        }

        private void DumpAllClipboardContents(object sender, RoutedEventArgs args)
        {
            // Dump all Clipboard contents on the Clipboard information panel
            DumpAllClipboardContentsInternal();
        }

        private void CopyToClipboard(object sender, RoutedEventArgs args)
        {
            var dataObject = new DataObject();

            // Copy data from RichTextBox/File content into DataObject
            if ((bool) rbCopyDataFromRichTextBox.IsChecked)
            {
                CopyDataFromRichTextBox(dataObject);
            }
            else
            {
                CopyDataFromFile(dataObject);
            }

            // Copy DataObject on the system Clipboard
            if (dataObject.GetFormats().Length > 0)
            {
                if ((bool) cbFlushOnCopy.IsChecked)
                {
                    // Copy data to the system clipboard with flush
                    Clipboard.SetDataObject(dataObject, true /*copy*/);
                }
                else
                {
                    // Copy data to the system clipboard without flush
                    Clipboard.SetDataObject(dataObject, false /*copy*/);
                }
            }

            // Dump the copied data contents on the information panel
            DumpAllClipboardContentsInternal();
        }

        private void PasteFromClipboard(object sender, RoutedEventArgs args)
        {
            var dataObject = GetDataObjectFromClipboard();

            if (dataObject == null)
            {
                MessageBox.Show("Couldn't get DataObject from system clipboard!\n", "Clipboard Error");
                return;
            }

            var autoConvert = (bool) cbAutoConvertibleData.IsChecked;
            var pasteDataFormat = lbPasteDataFormat.SelectedItems[0] as string;

            if ((bool) rbPasteDataToRichTextBox.IsChecked)
            {
                // Paste data from Clipboard to RichTextBox
                PasteClipboardDataToRichTextBox(pasteDataFormat, dataObject, autoConvert);
            }
            else
            {
                // Paste data from Clipboard to File
                PasteClipboardDataToFile(pasteDataFormat, dataObject, autoConvert);
            }
        }

        private void ClearRichTextBox(object sender, RoutedEventArgs args)
        {
            SetTextOnRichTextBox("");
        }

        // Update the data format status and describe all available data formats
        private void RefreshClipboardDataFormat()
        {
            clipboardInfo.Clear();

            lbPasteDataFormat.Items.Clear();

            var dataObject = GetDataObjectFromClipboard();

            if (dataObject == null)
            {
                clipboardInfo.Text = "Can't access clipboard now! Please click Refresh button again.";
            }
            else
            {
                // Check the data format whether it is on Clipboard or not
                cbAudio.IsChecked = dataObject.GetDataPresent(DataFormats.WaveAudio);
                cbFileDropList.IsChecked = dataObject.GetDataPresent(DataFormats.FileDrop);
                cbImage.IsChecked = dataObject.GetDataPresent(DataFormats.Bitmap);
                cbText.IsChecked = dataObject.GetDataPresent(DataFormats.Text);
                cbRtf.IsChecked = dataObject.GetDataPresent(DataFormats.Rtf);
                cbXaml.IsChecked = dataObject.GetDataPresent(DataFormats.Xaml);

                // Update the data format into the information panel
                UpdateAvailableDataFormats(dataObject);
            }
        }

        // Update and describe all available data formats
        private void UpdateAvailableDataFormats(IDataObject dataObject)
        {
            clipboardInfo.AppendText("Clipboard DataObject Type: ");
            clipboardInfo.AppendText(dataObject.GetType().ToString());

            clipboardInfo.AppendText("\n\n****************************************************\n\n");

            var formats = dataObject.GetFormats();

            clipboardInfo.AppendText(
                "The following data formats are present in the data object obtained from the clipboard:\n");

            if (formats.Length > 0)
            {
                foreach (var format in formats)
                {
                    bool nativeData;
                    if (dataObject.GetDataPresent(format, false))
                    {
                        nativeData = true;
                        clipboardInfo.AppendText("\t- " + format + " (native)\n");
                    }
                    else
                    {
                        nativeData = false;
                        clipboardInfo.AppendText("\t- " + format + " (autoconvertable)\n");
                    }

                    if (nativeData)
                    {
                        lbPasteDataFormat.Items.Add(format);
                    }
                    else if ((bool) cbAutoConvertibleData.IsChecked)
                    {
                        lbPasteDataFormat.Items.Add(format);
                    }
                }

                lbPasteDataFormat.SelectedIndex = 0;
            }
            else
            {
                clipboardInfo.AppendText("\t- no data formats are present\n");
            }
        }

        // Dump all available data contents
        private void DumpAllClipboardContentsInternal()
        {
            clipboardInfo.Clear();

            lbPasteDataFormat.Items.Clear();

            var dataObject = GetDataObjectFromClipboard();

            if (dataObject == null)
            {
                clipboardInfo.Text =
                    clipboardInfo.Text =
                        "Can't access clipboard now! \n\nPlease click Dump All Clipboard Contents button again.";
            }
            else
            {
                // Update the availabe data formats 
                UpdateAvailableDataFormats(dataObject);

                // Update the all available data contents
                var formats = dataObject.GetFormats();
                foreach (var format in formats)
                {
                    clipboardInfo.AppendText("\n\n****************************************************\n");
                    clipboardInfo.AppendText(format + " data:\n");
                    clipboardInfo.AppendText("****************************************************\n\n");

                    var data = GetDataFromDataObject(dataObject, format, true /*autoConvert*/);

                    clipboardInfo.AppendText(data?.ToString() ?? "null");
                }
            }
        }

        // Set the selected data format's data from RichTextBox's content 
        // into DataObject for copying data on the system clipboard
        private void CopyDataFromRichTextBox(IDataObject dataObject)
        {
            if ((bool) cbCopyTextDataFormat.IsChecked)
            {
                var textData = GetTextStringFromRichTextBox(DataFormats.Text);
                if (textData != string.Empty)
                {
                    dataObject.SetData(DataFormats.Text, textData);
                }
            }

            if ((bool) cbCopyXamlDataFormat.IsChecked)
            {
                var textData = GetTextStringFromRichTextBox(DataFormats.Xaml);
                if (textData != string.Empty)
                {
                    dataObject.SetData(DataFormats.Xaml, textData);
                }
            }

            if ((bool) cbCopyRtfDataFormat.IsChecked)
            {
                var textData = GetTextStringFromRichTextBox(DataFormats.Rtf);
                if (textData != string.Empty)
                {
                    dataObject.SetData(DataFormats.Rtf, textData);
                }
            }

            // Finally, consider a custom, application defined format.
            // We use an arbitrary encoding here, for demonstration purposes.
            if ((bool) cbCustomSampleDataFormat.IsChecked)
            {
                Stream customStream = new MemoryStream();

                var textData = "This is Custom Sample Data Start\n\n" +
                               GetTextStringFromRichTextBox(DataFormats.Text) +
                               "\nCustom Sample Data End.";

                var bytesUnicode = Encoding.Unicode.GetBytes(textData);
                var bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, bytesUnicode);

                if (bytes.Length > 0)
                {
                    customStream.Write(bytes, 0, bytes.Length);
                    dataObject.SetData("CustomSample", customStream);
                }
            }
        }

        // Set the selected data format's data from the file content 
        // into DataObject for copying data on the system clipboard
        private void CopyDataFromFile(IDataObject dataObject)
        {
            string fileName = null;

            var dialog = new OpenFileDialog {CheckFileExists = true};

            if ((bool) cbCopyTextDataFormat.IsChecked)
            {
                dialog.Filter = "Plain Text (*.txt)|*.txt";
                dialog.ShowDialog();
                fileName = dialog.FileName;

                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                var fileEncoding = Encoding.Default;
                var textData = GetTextStringFromFile(fileName, fileEncoding);
                if (!string.IsNullOrEmpty(textData))
                {
                    dataObject.SetData(DataFormats.Text, textData);
                }
            }

            if ((bool) cbCopyRtfDataFormat.IsChecked)
            {
                fileName = null;
                dialog.Filter = "RTF Documents (*.rtf)|*.rtf";
                dialog.ShowDialog();
                fileName = dialog.FileName;

                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                var fileEncoding = Encoding.ASCII;
                var textData = GetTextStringFromFile(fileName, fileEncoding);
                if (!string.IsNullOrEmpty(textData))
                {
                    dataObject.SetData(DataFormats.Rtf, textData);
                }
            }

            if ((bool) cbCopyXamlDataFormat.IsChecked)
            {
                fileName = null;
                dialog.Filter = "XAML Flow Documents (*.xaml)|*.xaml";
                dialog.ShowDialog();
                fileName = dialog.FileName;

                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                var fileEncoding = Encoding.UTF8;
                var textData = GetTextStringFromFile(fileName, fileEncoding);
                if (!string.IsNullOrEmpty(textData))
                {
                    dataObject.SetData(DataFormats.Xaml, textData);
                }
            }

            // Finally, consider a custom, application defined format.
            // We use an arbitrary encoding here, for demonstartion purposes.
            if ((bool) cbCustomSampleDataFormat.IsChecked)
            {
                fileName = null;
                dialog.Filter = "All Files (*.*)|*.*";
                dialog.ShowDialog();
                fileName = dialog.FileName;

                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                var fileEncoding = Encoding.UTF8;
                var textData = GetTextStringFromFile(fileName, fileEncoding);
                if (string.IsNullOrEmpty(textData)) return;
                var bytesUnicode = Encoding.Unicode.GetBytes(textData);
                var bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, bytesUnicode);

                if (bytes.Length > 0)
                {
                    var customStream = new MemoryStream();
                    customStream.Write(bytes, 0, bytes.Length);
                    dataObject.SetData("CustomSample", customStream);
                }
            }
        }

        // Paste a selected paste data format's data to RichTextBox
        private void PasteClipboardDataToRichTextBox(string dataFormat, IDataObject dataObject, bool autoConvert)
        {
            if (dataObject != null && dataObject.GetFormats().Length > 0)
            {
                var pasted = false;

                if (dataFormat == DataFormats.Xaml)
                {
                    var xamlData = dataObject.GetData(DataFormats.Xaml) as string;
                    if (!string.IsNullOrEmpty(xamlData))
                    {
                        pasted = PasteTextDataToRichTextBox(DataFormats.Xaml, xamlData);
                    }
                }
                else if (dataFormat == DataFormats.Rtf)
                {
                    var rtfData = dataObject.GetData(DataFormats.Rtf) as string;
                    if (!string.IsNullOrEmpty(rtfData))
                    {
                        pasted = PasteTextDataToRichTextBox(DataFormats.Rtf, rtfData);
                    }
                }
                else if (dataFormat == DataFormats.UnicodeText
                         || dataFormat == DataFormats.Text
                         || dataFormat == DataFormats.StringFormat)
                {
                    var textData = dataObject.GetData(dataFormat) as string;
                    if (textData != string.Empty)
                    {
                        SetTextOnRichTextBox(textData);
                        pasted = true;
                    }
                }
                else if (dataFormat == "CustomSample")
                {
                    // Paste the application defined custom data format's data to RichTextBox content
                    var customStream = dataObject.GetData(dataFormat, autoConvert) as Stream;
                    if (customStream.Length > 0)
                    {
                        var textRange = new TextRange(richTextBox.Document.ContentStart,
                            richTextBox.Document.ContentEnd);
                        textRange.Load(customStream, DataFormats.Text);
                        pasted = true;
                    }
                }

                if (!pasted)
                {
                    MessageBox.Show(
                        "Can't paste the selected data format into RichTextBox!\n\nPlease click Refresh button to update the current clipboard format Or select File RadioButton to paste data.",
                        "Paste Data Format Error",
                        MessageBoxButton.OK,
                        MessageBoxImage.Exclamation);
                }
            }
        }

        // Paste a selected paste data format's data to the fileSSS
        private void PasteClipboardDataToFile(string dataFormat, IDataObject dataObject, bool autoConvert)
        {
            var dialog = new SaveFileDialog {CheckFileExists = false};

            if (dataFormat == DataFormats.Text
                || dataFormat == DataFormats.UnicodeText
                || dataFormat == DataFormats.StringFormat)
            {
                dialog.Filter = "Plain Text (*.txt)|*.txt | All Files (*.*)|*.*";
            }
            else if (dataFormat == DataFormats.Xaml)
            {
                dialog.Filter = "XAML Flow Documents (*.xaml)|*.xaml | All Files (*.*)|*.*";
            }
            else if (dataFormat == DataFormats.Rtf)
            {
                dialog.Filter = "RTF Documents (*.rtf)|*.rtf | All Files (*.*)|*.*";
            }
            else
            {
                dialog.Filter = "All Files (*.*)|*.*";
            }

            if (!(bool) dialog.ShowDialog())
            {
                return;
            }

            var fileName = dialog.FileName;

            if (dataFormat == DataFormats.Xaml)
            {
                var xamlData = dataObject.GetData(DataFormats.Xaml) as string;
                if (!string.IsNullOrEmpty(xamlData))
                {
                    PasteTextDataToFile(dataFormat, xamlData, fileName, Encoding.UTF8);
                }
            }
            else if (dataFormat == DataFormats.Rtf)
            {
                var rtfData = dataObject.GetData(DataFormats.Rtf) as string;
                if (!string.IsNullOrEmpty(rtfData))
                {
                    PasteTextDataToFile(dataFormat, rtfData, fileName, Encoding.ASCII);
                }
            }
            else if (dataFormat == DataFormats.UnicodeText
                     || dataFormat == DataFormats.Text
                     || dataFormat == DataFormats.StringFormat)
            {
                var textData = dataObject.GetData(dataFormat, autoConvert) as string;
                if (!string.IsNullOrEmpty(textData))
                {
                    PasteTextDataToFile(dataFormat, textData, fileName,
                        dataFormat == DataFormats.Text ? Encoding.Default : Encoding.Unicode);
                }
            }
            else
            {
                // Paste the CustomSample data or others to the file
                //Stream customStream = dataObject.GetData(dataFormat, autoConvert) as Stream;
                var customStream = GetDataFromDataObject(dataObject, dataFormat, autoConvert) as Stream;
                if (customStream != null && customStream.Length > 0)
                {
                    PasteStreamDataToFile(customStream, fileName);
                }
            }
        }

        // Get DataObject from the system clipboard
        private IDataObject GetDataObjectFromClipboard()
        {
            IDataObject dataObject;

            try
            {
                dataObject = Clipboard.GetDataObject();
            }
            catch (COMException)
            {
                // Clipboard.GetDataObject can be failed by opening the system clipboard 
                // from other or processing clipboard operation like as setting data on clipboard
                dataObject = null;
            }

            return dataObject;
        }

        private object GetDataFromDataObject(IDataObject dataObject, string dataFormat, bool autoConvert)
        {
            object data = null;

            try
            {
                data = dataObject.GetData(dataFormat, autoConvert);
            }
            catch (COMException)
            {
                // Fail to get the data by the invalid value like tymed(DV_E_TYMED) 
                // or others(Aspect, Formatetc).
                // It depends on application's IDataObject::GetData implementation.
                clipboardInfo.AppendText("Fail to get data!!! ***COMException***");
            }
            catch (OutOfMemoryException)
            {
                // Fail by the out of memory from getting data on Clipboard. 
                // Occurs with the low memory.
                clipboardInfo.AppendText("Fail to get data!!! ***OutOfMemoryException***");
            }

            return data;
        }

        // Set the plain text on RichTextBox
        private void SetTextOnRichTextBox(string text)
        {
            var document = richTextBox.Document;
            var textRange = new TextRange(document.ContentStart, document.ContentEnd) {Text = text};
            richTextBox.Focus();
            richTextBox.SelectAll();
        }

        // Get text data string from RichTextBox content which encoded as UTF8
        private string GetTextStringFromRichTextBox(string dataFormat)
        {
            var document = richTextBox.Document;
            var textRange = new TextRange(document.ContentStart, document.ContentEnd);

            if (dataFormat == DataFormats.Text)
            {
                return textRange.Text;
            }
            Stream contentStream = new MemoryStream();
            textRange.Save(contentStream, dataFormat);

            if (contentStream.Length > 0)
            {
                var bytes = new byte[contentStream.Length];

                contentStream.Position = 0;
                contentStream.Read(bytes, 0, bytes.Length);

                var utf8Encoding = Encoding.UTF8;

                return utf8Encoding.GetString(bytes);
            }

            return null;
        }

        // Get text data string from file content with the proper encoding
        private string GetTextStringFromFile(string fileName, Encoding fileEncoding)
        {
            string textString = null;

            FileStream fileStream;

            try
            {
                fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            }
            catch (IOException)
            {
                MessageBox.Show("File is not acessible.\n", "File Open Error");
                return null;
            }

            fileStream.Position = 0;

            var bytes = new byte[fileStream.Length];

            fileStream.Read(bytes, 0, bytes.Length);

            if (bytes.Length > 0)
            {
                textString = fileEncoding.GetString(bytes);
            }

            fileStream.Close();

            return textString;
        }

        // Paste text data on RichTextBox as UTF8 encoding
        private bool PasteTextDataToRichTextBox(string dataFormat, string textData)
        {
            var pasted = false;

            var document = richTextBox.Document;
            var textRange = new TextRange(document.ContentStart, document.ContentEnd);

            Stream stream = new MemoryStream();

            var bytesUnicode = Encoding.Unicode.GetBytes(textData);
            var bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, bytesUnicode);

            if (bytes.Length > 0 && textRange.CanLoad(dataFormat))
            {
                stream.Write(bytes, 0, bytes.Length);
                textRange.Load(stream, dataFormat);
                pasted = true;
            }

            return pasted;
        }

        // Paste text data to the file with the file encoding
        private void PasteTextDataToFile(string dataFormat, string textData, string fileName, Encoding fileEncoding)
        {
            FileStream fileWriteStream;

            try
            {
                fileWriteStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
            }
            catch (IOException)
            {
                MessageBox.Show("File is not acessible.\n", "File Write Error");
                return;
            }

            fileWriteStream.SetLength(0);

            var bytesUnicode = Encoding.Unicode.GetBytes(textData);
            var bytes = Encoding.Convert(Encoding.Unicode, fileEncoding, bytesUnicode);

            if (bytes.Length > 0)
            {
                fileWriteStream.Write(bytes, 0, bytes.Length);
            }

            fileWriteStream.Close();
        }

        // Paste stream data to the file
        private void PasteStreamDataToFile(Stream stream, string fileName)
        {
            FileStream fileWriteStream = null;

            try
            {
                fileWriteStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
            }
            catch (IOException)
            {
                MessageBox.Show("File is not acessible.\n", "File Write Error");
            }

            fileWriteStream.SetLength(0);

            var bytes = new byte[stream.Length];

            stream.Position = 0;
            stream.Read(bytes, 0, bytes.Length);

            if (bytes.Length > 0)
            {
                fileWriteStream.Write(bytes, 0, bytes.Length);
            }

            fileWriteStream.Close();
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/ConstantExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;

namespace GraphingCalculatorDemo.Parser
{
    //--------------------------------------------------------------

    /// <summary>
    ///     ConstantExpression - An expression which always resolves to a constant
    ///     value.
    /// </summary>
    public sealed class ConstantExpression : IExpression
    {
        public ConstantExpression(double value)
        {
            Value = value;
        }

        public double Value { get; }

        /// <summary>
        ///     A constant always evaluates to its value.
        /// </summary>
        public double Evaluate() => Value;

        /// <summary>
        ///     The derivative of a constant is 0.
        /// </summary>
        public IExpression Differentiate(string byVar) => new ConstantExpression(0);

        public IExpression Simplify() => new ConstantExpression(Value);

        string IExpression.ToString() => Value.ToString(CultureInfo.InvariantCulture);
    }

    //--------------------------------------------------------------

    #region Unary Expressions

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    #endregion

    #region Binary Expressions

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    #endregion

    // TODO: support Tertiary Expressions (conditionals)
}

<|start_filename|>Windows/DialogBox/MarginsDialogBox.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

// Window, RoutedEventArgs, IInputElement, DependencyObject
// Validation

// Keyboard

namespace DialogBox
{
    public partial class MarginsDialogBox : Window
    {
        public MarginsDialogBox()
        {
            InitializeComponent();
        }

        public Thickness DocumentMargin
        {
            get { return (Thickness) DataContext; }
            set { DataContext = value; }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            // Dialog box canceled
            DialogResult = false;
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            // Don't accept the dialog box if there is invalid data
            if (!IsValid(this)) return;

            // Dialog box accepted
            DialogResult = true;
        }

        // Validate all dependency objects in a window
        private bool IsValid(DependencyObject node)
        {
            // Check if dependency object was passed
            if (node != null)
            {
                // Check if dependency object is valid.
                // NOTE: Validation.GetHasError works for controls that have validation rules attached 
                var isValid = !Validation.GetHasError(node);
                if (!isValid)
                {
                    // If the dependency object is invalid, and it can receive the focus,
                    // set the focus
                    if (node is IInputElement) Keyboard.Focus((IInputElement) node);
                    return false;
                }
            }

            // If this dependency object is valid, check all child dependency objects
            return LogicalTreeHelper.GetChildren(node).OfType<DependencyObject>().All(IsValid);

            // All dependency objects are valid
        }
    }
}

//</SnippetMarginsDialogBoxCancelResultSetCODEBEHIND3>

<|start_filename|>Sample Applications/HexSphereDemo/TrackBall.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Media3D;

namespace HexSphereDemo
{
    public class Trackball
    {
        private Vector3D _center;
        private bool _centered; // Have we already determined the rotation center?
        // The state of the trackball
        private bool _enabled;
        private Point _point; // Initial point of drag
        private bool _rotating;
        private Quaternion _rotation;
        private Quaternion _rotationDelta; // Change to rotation because of this drag
        private double _scale;
        private double _scaleDelta; // Change to scale because of this drag
        // The state of the current drag
        private bool _scaling; // Are we scaling?  NOTE otherwise we're rotating
        private List<Viewport3D> _slaves;
        private Vector3D _translate;
        private Vector3D _translateDelta;

        public Trackball()
        {
            Reset();
        }

        public List<Viewport3D> Slaves
        {
            get { return _slaves ?? (_slaves = new List<Viewport3D>()); }
            set { _slaves = value; }
        }

        public bool Enabled
        {
            get { return _enabled && (_slaves != null) && (_slaves.Count > 0); }
            set { _enabled = value; }
        }

        public void Attach(FrameworkElement element)
        {
            element.MouseMove += MouseMoveHandler;
            element.MouseRightButtonDown += MouseDownHandler;
            element.MouseRightButtonUp += MouseUpHandler;
            element.MouseWheel += OnMouseWheel;
        }

        public void Detach(FrameworkElement element)
        {
            element.MouseMove -= MouseMoveHandler;
            element.MouseRightButtonDown -= MouseDownHandler;
            element.MouseRightButtonUp -= MouseUpHandler;
            element.MouseWheel -= OnMouseWheel;
        }

        // Updates the matrices of the slaves using the rotation quaternion.
        private void UpdateSlaves(Quaternion q, double s, Vector3D t)
        {
            //RotateTransform3D rotation = new RotateTransform3D(q,_center);
            //ScaleTransform3D scale = new ScaleTransform3D(new Vector3D(s,s,s));
            //Transform3DCollection rotateAndScale = new Transform3DCollection(rotation,scale);

            if (_slaves != null)
            {
                foreach (var i in _slaves)
                {
                    var mv = i.Children[0] as ModelVisual3D;
                    var t3Dg = mv.Transform as Transform3DGroup;

                    var groupScaleTransform = t3Dg.Children[0] as ScaleTransform3D;
                    var groupRotateTransform = t3Dg.Children[1] as RotateTransform3D;
                    var groupTranslateTransform = t3Dg.Children[2] as TranslateTransform3D;

                    groupScaleTransform.ScaleX = s;
                    groupScaleTransform.ScaleY = s;
                    groupScaleTransform.ScaleZ = s;
                    groupRotateTransform.Rotation = new AxisAngleRotation3D(q.Axis, q.Angle);
                    groupTranslateTransform.OffsetX = t.X;
                    groupTranslateTransform.OffsetY = t.Y;
                    groupTranslateTransform.OffsetZ = t.Z;

                    // Note that we don't copy constantly here, we copy the first time someone tries to
                    // trackball a frozen Models, but we replace it with a ChangeableReference
                    // and so subsequent interactions go through without a copy.
                    /*
                    if (i.Models.Transform.IsChangeable)
                    {
                        Model3DGroup mutableCopy = i.Models.Copy();
                        mutableCopy.StatusOfNextUse = UseStatus.ChangeableReference;
                        i.Models = mutableCopy;
                    }
                    i.Models.Transform = rotateAndScale;
                    */
                }
            }
        }

        private void MouseMoveHandler(object sender, MouseEventArgs e)
        {
            if (!Enabled) return;
            e.Handled = true;

            var el = (UIElement) sender;

            if (el.IsMouseCaptured)
            {
                var delta = _point - e.MouseDevice.GetPosition(el);
                var t = new Vector3D();

                delta /= 2;
                var q = _rotation;

                if (_rotating)
                {
                    // We can redefine this 2D mouse delta as a 3D mouse delta
                    // where "into the screen" is Z
                    var mouse = new Vector3D(delta.X, -delta.Y, 0);
                    var axis = Vector3D.CrossProduct(mouse, new Vector3D(0, 0, 1));
                    var len = axis.Length;
                    if (len < 0.00001 || _scaling)
                        _rotationDelta = new Quaternion(new Vector3D(0, 0, 1), 0);
                    else
                        _rotationDelta = new Quaternion(axis, len);

                    q = _rotationDelta*_rotation;
                }
                else
                {
                    delta /= 20;
                    _translateDelta.X = delta.X*-1;
                    _translateDelta.Y = delta.Y;
                }

                t = _translate + _translateDelta;

                UpdateSlaves(q, _scale*_scaleDelta, t);
            }
        }

        private void MouseDownHandler(object sender, MouseButtonEventArgs e)
        {
            if (!Enabled) return;
            e.Handled = true;


            if (Keyboard.IsKeyDown(Key.F1))
            {
                Reset();
                return;
            }

            var el = (UIElement) sender;
            _point = e.MouseDevice.GetPosition(el);
            // Initialize the center of rotation to the lookatpoint
            if (!_centered)
            {
                var camera = (ProjectionCamera) _slaves[0].Camera;
                _center = camera.LookDirection;
                _centered = true;
            }

            _scaling = (e.MiddleButton == MouseButtonState.Pressed);

            _rotating = Keyboard.IsKeyDown(Key.Space) == false;

            el.CaptureMouse();
        }

        private void MouseUpHandler(object sender, MouseButtonEventArgs e)
        {
            if (!_enabled) return;
            e.Handled = true;

            // Stuff the current initial + delta into initial so when we next move we
            // start at the right place.
            if (_rotating)
                _rotation = _rotationDelta*_rotation;
            else
            {
                _translate += _translateDelta;
                _translateDelta.X = 0;
                _translateDelta.Y = 0;
            }

            //_scale = _scaleDelta*_scale;
            var el = (UIElement) sender;
            el.ReleaseMouseCapture();
        }

        private void OnMouseWheel(object sender, MouseWheelEventArgs e)
        {
            e.Handled = true;

            _scaleDelta += e.Delta/(double) 1000;
            var q = _rotation;

            UpdateSlaves(q, _scale*_scaleDelta, _translate);
        }

        private void MouseDoubleClickHandler(object sender, MouseButtonEventArgs e)
        {
            Reset();
        }

        private void Reset()
        {
            _rotation = new Quaternion(0, 0, 0, 1);
            _scale = 1;
            _translate.X = 0;
            _translate.Y = 0;
            _translate.Z = 0;
            _translateDelta.X = 0;
            _translateDelta.Y = 0;
            _translateDelta.Z = 0;

            // Clear delta too, because if reset is called because of a double click then the mouse
            // up handler will also be called and this way it won't do anything.
            _rotationDelta = Quaternion.Identity;
            _scaleDelta = 1;
            UpdateSlaves(_rotation, _scale, _translate);
        }
    }
}

<|start_filename|>Data Binding/DirectionalBinding/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace DirectionalBinding
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnRentRaise(object sender, RoutedEventArgs args)
        {
            // Update bills
            var random = new Random();
            double i = random.Next(10);
            var bindingExpression =
                BindingOperations.GetBindingExpression(SavingsText, TextBlock.TextProperty);
            var sourceData = (NetIncome) bindingExpression.DataItem;
            sourceData.Rent = (int) ((1 + i/100)*sourceData.Rent);
        }

        private void OnTargetUpdated(object sender, DataTransferEventArgs args)
        {
            // Handle event
            var fe = sender as FrameworkElement;
            infoText.Text = "";
            infoText.Text += args.Property.Name + " property of a " + args.Property.OwnerType.Name;
            infoText.Text += " element (";
            infoText.Text += fe.Name;
            infoText.Text += ") updated...";
            infoText.Text += DateTime.Now.ToLongDateString();
            infoText.Text += " at ";
            infoText.Text += DateTime.Now.ToLongTimeString();
        }
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/WhiteBalanceMode.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace PhotoViewerDemo
{
    public enum WhiteBalanceMode
    {
        Daylight,
        Fluorescent,
        Tungsten,
        Flash,
        StandardLightA,
        StandardLightB,
        StandardLightC,
        D55,
        D65,
        D75,
        Other,
        Unknown
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/TangentExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Evaluate the tangent of an expression.
    /// </summary>
    public sealed class TangentExpression : UnaryExpression
    {
        public TangentExpression(IExpression child) : base(child)
        {
        }

        protected override double Operate(double d) => Math.Tan(d);

        public override IExpression Differentiate(string byVar) => new MultExpression(new ExpExpression(new CosineExpression(child),
                new ConstantExpression(-2)),
                child.Differentiate(byVar));

        public override IExpression Simplify()
        {
            var newChild = child.Simplify();
            var childConst = newChild as ConstantExpression;

            if (childConst != null)
            {
                // child is constant;  just evaluate it;
                return new ConstantExpression(Math.Tan(childConst.Value));
            }
            return new TangentExpression(newChild);
        }

        public override string ToString() => "tan(" + child.ToString() + ")";
    }
}

<|start_filename|>Graphics/Matrix/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;
using System.Windows;
using System.Windows.Controls;

namespace Matrix
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Show();
            ShowVars();
        }

        public void PerformOperation(object sender, RoutedEventArgs e)
        {
            var li = sender as RadioButton;
            string syntaxString, resultType, operationString;

            switch (li?.Name)
            {
                // begin switch


                case "rb1":
                {
                    // Multiplies a Matrix by a Matrix using the overloaded * operator
                    // Returns a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);

                    var isInvertible = matrix1.HasInverse;
                    // isInvertible is equal to True    

                    // Displaying Results
                    syntaxString = "isInvertible = matrix1.HasInverse;";
                    resultType = "Boolean";
                    operationString = "Checking if matrix1 is invertible";
                    ShowResults(isInvertible.ToString(), syntaxString, resultType, operationString);

                    break;
                }
                case "rb2":
                {
                    // Translates a Matrix
                    // Returns a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    const double offsetX = 15;
                    const double offsetY = 25;

                    matrix1.Translate(offsetX, offsetY);
                    // matrix1 is not equal to 

                    //Displaying Results
                    syntaxString = "matrix1.Translate(offsetX, offsetY);";
                    resultType = "Void";
                    operationString = "Translating a Matrix by a Point";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);

                    break;
                }
                case "rb3":
                {
                    // Prepend a Tranlsation to a Matrix
                    // Returns a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    const double offsetX = 15;
                    const double offsetY = 25;

                    matrix1.TranslatePrepend(offsetX, offsetY);
                    // matrix1 is not equal to 

                    //Displaying Results
                    syntaxString = " matrix1.TranslatePrepend(offsetX, offsetY);";
                    resultType = "Void";
                    operationString = "Prepending Translating a matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb4":
                {
                    // Sets a Matrix to an identity matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);

                    matrix1.SetIdentity();
                    // matrix1 is now equal to (1,0,0,1,0,0)

                    //Displaying Results
                    syntaxString = "matrix1.SetIdentity();";
                    resultType = "Void";
                    operationString = "Setting a matrix to an identity matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb5":
                {
                    // Checks if a Matrix is an identity matrix
                    // Creates a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);

                    // Sets matrix1 into an identity matrix
                    matrix1.SetIdentity();

                    var isIdentityMatrix = matrix1.IsIdentity;
                    // isIdentityMatrix is equal to True

                    //Displaying Results
                    syntaxString = "isIdentityMatrix = matrix1.IsIdentity;";
                    resultType = "Boolean";
                    operationString = "Determining if a Matrix is an identity matrix";
                    ShowResults(isIdentityMatrix.ToString(), syntaxString, resultType, operationString);
                    break;
                }


                case "rb6":
                {
                    // Changes a Matrix into an identity matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    matrix1 = System.Windows.Media.Matrix.Identity;
                    // matrix1 is now equal to (1,0,0,1,0,0)
                    //Displaying Results
                    syntaxString = "matrix1 = Matrix.Identity;";
                    resultType = "Matrix";
                    operationString = "Gets an identity Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb7":
                {
                    // Converts a string representation of a matrix into a Matrix structure
                    var matrixResult = new System.Windows.Media.Matrix();

                    matrixResult = System.Windows.Media.Matrix.Parse("1,2,3,4,5,6");
                    // matrixResult is equal to (1,2,3,4,5,6)

                    //Displaying Results
                    syntaxString = "matrixResult = Matrix.Parse(\"1,2,3,4,5,6\");";
                    resultType = "Matrix";
                    operationString = "Convert a string into a Matrix structure";
                    ShowResults(matrixResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb8":
                {
                    // Checks if two Matrixes are equal using the static Equals method
                    // Returns a Boolean.
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);
                    var areEqual = System.Windows.Media.Matrix.Equals(matrix1, matrix2);
                    // areEqual is equal to False

                    //Displaying Results
                    syntaxString = "areEqual = Matrix.Equals(matrix1, matrix2);";
                    resultType = "Boolean";
                    operationString = "Checking if the matrices are equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);

                    break;
                }
                case "rb8b":
                {
                    // Checks if an Object is equal to a Matrix using the static Equals method
                    // Returns a Boolean.
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);

                    var areEqual = matrix1.Equals(matrix2);
                    // areEqual is equal to False

                    //Displaying Results
                    syntaxString = "areEqual = Matrix.Equals(matrix1, matrix2);";
                    resultType = "Boolean";
                    operationString = "Checking if the matrices are equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);

                    break;
                }

                case "rb9":
                {
                    // Checks if two Matrixes are equal using the overloaded == operator
                    // Returns a Boolean.    
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);

                    var areEqual = matrix1 == matrix2;
                    // areEqual is equal to False

                    //Displaying Results
                    syntaxString = "areEqual = matrix1 == matrix2;";
                    resultType = "Boolean";
                    operationString = "Checking if the matrices are equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb10":
                {
                    // Checks if two Matrixes are not equal using the overloaded != operator
                    // Returns a Boolean.    
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);

                    var areEqual = matrix1 != matrix2;
                    // areEqual is equal to False

                    //Displaying Results
                    syntaxString = "areEqual = matrix1 != matrix2;";
                    resultType = "Boolean";
                    operationString = "Checking if the matrices are not equal";
                    ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb11":
                {
                    // Inverts a Matrix
                    // Creating a Matrix structure
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    // Checking if matrix1 is invertible
                    if (matrix1.HasInverse)
                    {
                        // Inverting matrix1                         
                        matrix1.Invert();
                        // matrix1 is equal to (-0.04, 0.2 , 0.3, -0.1, 1, -2) 
                    }
                    //Displaying Results
                    syntaxString = "matrix1.Invert();";
                    resultType = "Void";
                    operationString = "Inverting a matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb12":
                {
                    // Prepends a Matrix to another Matrix.
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);
                    matrix1.Prepend(matrix2);
                    // matrix1 is equal to (70,100,150,220,255,370)     
                    //Displaying Results
                    syntaxString = "matrix1.Prepend(matrix2);";
                    resultType = "Void";
                    operationString = "Prepending a Matrix to another Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb13":
                {
                    // Appends a Matrix to another Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);
                    matrix1.Append(matrix2);
                    // matrix1 is equal to (70,100,150,220,240,352)    
                    //Displaying Results
                    syntaxString = "matrix1.Append(matrix2);";
                    resultType = "Void";
                    operationString = "Appending a Matrix to another Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb14":
                {
                    // Rotates a Matrix by a specified angle
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    double rotateAngle = 90;

                    matrix1.Rotate(rotateAngle);
                    // matrix1 is equal to (-10,5,-20,15,-30,25)   

                    //Displaying Results
                    syntaxString = "matrix1.Rotate(rotateAngle);";
                    resultType = "Void";
                    operationString = "Rotating a Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb15":
                {
                    // Rotates a Matrix by a specified angle at a specific point
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    matrix1.RotateAt(90, 2, 4);
                    // matrix1 is equal to (-10,5,-20,15,-24,27)    
                    //Displaying Results
                    syntaxString = "matrix1.RotateAt(rotateAngle, rotateCenterX, rotateCenterY);";
                    resultType = "Void";
                    operationString = "Rotating a Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb16":
                {
                    // Prepends a Rotation to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    double rotateAngle = 90;
                    matrix1.RotatePrepend(rotateAngle);
                    // matrix1 is equal to (15,20,-5,-10,25,30)    
                    //Displaying Results
                    syntaxString = "matrix1.RotatePrepend(rotateAngle);";
                    resultType = "Void";
                    operationString = "Rotating a Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb17":
                {
                    // Prepends a Rotation at a specific point to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    matrix1.RotateAtPrepend(90, 2, 4);
                    // matrix1 is equal to  (15,20,-5,-10,85,130)
                    //Displaying Results
                    syntaxString = "matrix1.RotateAtPrepend(rotateAngle, rotateCenterX, rotateCenterY);";
                    resultType = "Void";
                    operationString = "Rotating a Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb18":
                {
                    // Scales a Matrix 
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    double scaleX = (1);
                    double scaleY = (2);

                    matrix1.Scale(scaleX, scaleY);
                    // matrix1 is equal to     

                    //Displaying Results
                    syntaxString = "matrix1.Scale(scaleX, scaleY);";
                    resultType = "Void";
                    operationString = "Scaling a Matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb19":
                {
                    // Multiplies a Matrix by another Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);
                    var matrixResult = new System.Windows.Media.Matrix();

                    matrixResult = System.Windows.Media.Matrix.Multiply(matrix2, matrix1);
                    // matrixResult is equal to (70, 100, 150, 220, 255, 370)    

                    //Displaying Results
                    syntaxString = "matrixResult = Matrix.Multiply(matrix2, matrix1);";
                    resultType = "Matrix";
                    operationString = "Multiplying matrix1 and matrix2";
                    ShowResults(matrixResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb20":
                {
                    // Multiplies a Matrix by another Matrix using the overloaded * operator
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var matrix2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);
                    var matrixResult = new System.Windows.Media.Matrix();

                    matrixResult = matrix1*matrix2;
                    // matrixResult is equal to (70, 100, 150, 220, 240, 352)   

                    //Displaying Results
                    syntaxString = " matrixResult = matrix1 * matrix2;";
                    resultType = "Matrix";
                    operationString = "Multiplying matrix1 and matrix2";
                    ShowResults(matrixResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }


                case "rb21":
                {
                    // Appends a skew to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    double skewAngleX = 45;
                    double skewAngleY = 180;
                    matrix1.Skew(skewAngleX, skewAngleY);
                    // matrix1 is equal to (15, 10, 35, 20, 55, 30)
                    //Displaying Results
                    syntaxString = "matrix1.Skew(skewAngleX, skewAngleY);";
                    resultType = "Void";
                    operationString = "Multiplying matrix2 and matrix1";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb22":
                {
                    // Prepends a skew to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    double skewAngleX = 45;
                    double skewAngleY = 180;
                    matrix1.SkewPrepend(skewAngleX, skewAngleY);
                    // matrix1 is equal to (5, 10, 20, 30, 25, 30)
                    //Displaying Results
                    syntaxString = "matrix1.SkewPrepend(skewAngleX, skewAngleY);";
                    resultType = "Void";
                    operationString = "Multiplying matrix2 and matrix1";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }


                case "rb23":
                {
                    // Appends a scale to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    double scaleFactorX = 2;
                    double scaleFactorY = 4;
                    matrix1.Scale(scaleFactorX, scaleFactorY);
                    // matrix1 is equal to (10, 40, 30, 80, 50, 120)
                    //Displaying Results
                    syntaxString = "matrix1.Scale(scaleFactorX, scaleFactorY);";
                    resultType = "Void";
                    operationString = "Appending a scale to a matrix";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb24":
                {
                    // Appends a scale at a specific point to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    matrix1.ScaleAt(2, 4, 5, 10);
                    // matrix1 is equal to (10, 40, 30, 80, 45, 90)
                    //Displaying Results
                    syntaxString = " matrix1.ScaleAt(scaleFactorX, scaleFactorY, scaleCenterX, scaleCenterY);";
                    resultType = "Void";
                    operationString = "Appends a scale at a specific point to matrix1";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb25":
                {
                    // Prepends a scale to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    double scaleFactorX = 2;
                    double scaleFactorY = 4;
                    matrix1.ScalePrepend(scaleFactorX, scaleFactorY);
                    // matrix1 is equal to (10, 20, 60, 80, 25, 30)
                    //Displaying Results
                    syntaxString = "matrix1.ScalePrepend(scaleFactorX, scaleFactorY);";
                    resultType = "Void";
                    operationString = "Prepending a scale to matrix1";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb26":
                {
                    // Prepends a scale at a specific point to a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);

                    matrix1.ScaleAtPrepend(2, 4, 5, 10);
                    // matrix1 is equal to (10, 20, 60, 80, -450, -620)

                    //Displaying Results
                    syntaxString = "matrix1.ScalePrependAt(scaleFactorX, scaleFactorY, centerPointX, centerPointY);";
                    resultType = "Void";
                    operationString = "Prepending a scale at a specific point to matrix1";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb29":
                {
                    // Transform a point by a matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var point1 = new Point(15, 25);
                    var pointResult = new Point();

                    pointResult = matrix1.Transform(point1);
                    // pointResult is equal to (475, 680)

                    //Displaying Results
                    syntaxString = "pointResult = matrix1.Transform(point1)";
                    resultType = "Point";
                    operationString = "Transforming a point1 by matrix1";
                    ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb30":
                {
                    // Transform a Vector by a Matrix
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var vector1 = new Vector(15, 25);
                    new Vector();

                    matrix1.Transform(vector1);
                    // vectorResult is equal to (450, 650)

                    //Displaying Results
                    syntaxString = "vectorResult = matrix1.Transform(vector1);";
                    resultType = "Vector";
                    operationString = "Multiplying matrix2 and matrix1";
                    ShowResults(matrix1.ToString(), syntaxString, resultType, operationString);
                    break;
                }

                case "rb31":
                {
                    // Transform an array of Points by a Matrix

                    // Creating a Matrix and an array of Pointers
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var pointArray = new Point[2];

                    // Setting the Point's X and Y values
                    pointArray[0].X = 15;
                    pointArray[0].Y = 25;
                    pointArray[1].X = 30;
                    pointArray[1].Y = 35;

                    // Transforming the Points in pointArry by matrix1
                    matrix1.Transform(pointArray);

                    // pointArray[0] is equal to (475, 680)
                    // pointArray[1] is equal to (700, 1030)

                    //Displaying Results
                    syntaxString = "matrix1.Transform(pointArray);";
                    resultType = "void";
                    operationString = "Transforming an array of Points by matrix1";
                    ShowResults(pointArray[1].ToString(), syntaxString, resultType, operationString);
                    break;
                }
                case "rb32":
                {
                    // Transform an array of Vectors by a Matrix

                    // Creating  a Matrix and an array of Vectors
                    var matrix1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
                    var vectorArray = new Vector[2];

                    // Setting the Vector's X and Y values
                    vectorArray[0].X = 15;
                    vectorArray[0].Y = 25;
                    vectorArray[1].X = 30;
                    vectorArray[1].Y = 35;

                    // Transforming the Vectors in vectorArray by matrix1
                    matrix1.Transform(vectorArray);

                    // VectorArray[0] is equal to (450, 650)
                    // VectorArray[1] is equal to (675, 1000)

                    //Displaying Results
                    syntaxString = " matrix1.Transform(vectorArray);";
                    resultType = "Void";
                    operationString = "Multiplying matrix2 and matrix1";
                    ShowResults(vectorArray[0].ToString(), syntaxString, resultType, operationString);
                    break;
                }
            } // end switch
        }

        // Displays the results 

        private void ShowResults(string resultValue, string syntax, string resultType, string opString)
        {
            // Displays the results of the operation
            txtResultValue.Text = resultValue;
            txtSyntax.Text = syntax;
            txtResultType.Text = resultType;
            txtOperation.Text = opString;
        }

        // Displays the variables

        public void ShowVars()
        {
            // Displays the values of the variables
            var p1 = new Point(15, 25);
            var v1 = new Vector(15, 25);
            var m1 = new System.Windows.Media.Matrix(5, 10, 15, 20, 25, 30);
            var m2 = new System.Windows.Media.Matrix(2, 4, 6, 8, 10, 12);
            double s1 = 75;

            // Sets the Text in the text objects.  These are 
            // defined in the Windows1.xaml file

            txtPoint1.Text = p1.ToString();
            txtVector1.Text = v1.ToString();
            txtMatrix1.Text = m1.ToString();
            txtMatrix2.Text = m2.ToString();
            txtScalar1.Text = s1.ToString(CultureInfo.InvariantCulture);
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/basedecoder.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of BaseDecoder
//----------------------------------------------------------------------------------------
#include "precomp.hpp"

//----------------------------------------------------------------------------------------
// FRAME DECODE
//----------------------------------------------------------------------------------------

 // IUnknown Interface   
STDMETHODIMP_(ULONG) BaseFrameDecode::AddRef()
{
    return unknownImpl.AddRef();
}

STDMETHODIMP_(ULONG) BaseFrameDecode::Release()
{
    ULONG result = unknownImpl.Release();
    if (0 == result)
    {
        delete this;
    }
    return result;
}

STDMETHODIMP BaseFrameDecode::QueryInterface(REFIID iid, void **ppvObject)
{
    HRESULT result = E_INVALIDARG;

    if (ppvObject)
    {
        if (iid == IID_IUnknown)
        {
            *ppvObject = static_cast<IUnknown*>(this);
            AddRef();

            result = S_OK;
        }
        else if (iid == IID_IWICBitmapFrameDecode)
        {
            *ppvObject = static_cast<IWICBitmapFrameDecode*>(this);
            AddRef();

            result = S_OK;
        }
        else if (iid == IID_IWICBitmapSource)
        {
            *ppvObject = bitmapSource;

            if (NULL != bitmapSource)
            {
                bitmapSource->AddRef();
            }

            result = S_OK;
        }
        else
        {
            result = E_NOINTERFACE;
        }
    }

    return result;
}


// IWICBitmapFrameDecode Interface
void BaseFrameDecode::ReleaseMembers()
{
    if (factory)
    {
        factory->Release();
        factory = NULL;
    }
    if (bitmapSource)
    {
        bitmapSource->Release();
        bitmapSource = NULL;
    }
    if (palette)
    {
        palette->Release();
        palette = NULL;
    }
    for (size_t i = 0; i < colorContexts.size(); i++)
    {
        if (NULL != colorContexts[i])
        {
            colorContexts[i]->Release();
        }
    }
    colorContexts.clear();
    if (thumbnail)
    {
        thumbnail->Release();
        thumbnail = NULL;
    }
    if (preview)
    {
        preview->Release();
        preview = NULL;
    }
}

BaseFrameDecode::BaseFrameDecode(IWICImagingFactory *pIFactory, UINT num)
    : factory(pIFactory)
    , frameNumber(num)
    , bitmapSource(NULL)
    , palette(NULL)
    , thumbnail(NULL)
    , preview(NULL)
{
    if (NULL != factory)
    {
        factory->AddRef();
    }
}

BaseFrameDecode::~BaseFrameDecode()
{
   ReleaseMembers();
}


STDMETHODIMP BaseFrameDecode::GetMetadataQueryReader(IWICMetadataQueryReader **ppIMetadataQueryReader)
{
    return WINCODEC_ERR_UNSUPPORTEDOPERATION;
}


STDMETHODIMP BaseFrameDecode::GetColorContexts(UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
{
    HRESULT result = S_OK;
    if (ppIColorContexts == NULL)
    {
        //return the number of color contexts
        if (pcActualCount != NULL)
        {
            *pcActualCount = colorContexts.size();        
        }
        else
        {
            result = E_INVALIDARG;
        }
    }
    else
    {
        //return the actual color contexts
        for (int i = 0; i < (UINT)colorContexts.size(); i++)
        {
            ppIColorContexts[i] = colorContexts[i];
            colorContexts[i]->AddRef();            
        }        
    }
    return result;
} 

STDMETHODIMP BaseFrameDecode::GetThumbnail(IWICBitmapSource **ppIThumbnail)
{
    HRESULT result = S_OK;

    if (NULL == ppIThumbnail)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        *ppIThumbnail = thumbnail;

        if (NULL != thumbnail)
        {
            thumbnail->AddRef();
        }
        else
        {
            result = WINCODEC_ERR_CODECNOTHUMBNAIL;
        }
    }

    return result;
}

STDMETHODIMP BaseFrameDecode::GetSize(UINT *puiWidth, UINT *puiHeight)
{
    HRESULT result = E_UNEXPECTED;

    if (bitmapSource)
    {
        result = bitmapSource->GetSize(puiWidth, puiHeight);
    }

    return result;
}

STDMETHODIMP BaseFrameDecode::GetPixelFormat(WICPixelFormatGUID *pPixelFormat)
{
    HRESULT result = E_UNEXPECTED;

    if (bitmapSource)
    {
        result = bitmapSource->GetPixelFormat(pPixelFormat);
    }

    return result;
}

STDMETHODIMP BaseFrameDecode::GetResolution(double *pDpiX, double *pDpiY)
{
    HRESULT result = E_UNEXPECTED;

    if (bitmapSource)
    {
        result = bitmapSource->GetResolution(pDpiX, pDpiY);
    }

    return result;
}

STDMETHODIMP BaseFrameDecode::CopyPalette(IWICPalette *pIPalette)
{
    HRESULT result = S_OK;

    if (NULL == pIPalette)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (NULL != palette)
        {
            pIPalette->InitializeFromPalette(palette);
        }
        else
        {
            result = E_UNEXPECTED;
        }
    }

    return result;
}

STDMETHODIMP BaseFrameDecode::CopyPixels(const WICRect *prc, UINT cbStride, UINT cbPixelsSize, BYTE *pbPixels)
{
    HRESULT result = E_UNEXPECTED;

    if (bitmapSource)
    {
        result = bitmapSource->CopyPixels(prc, cbStride, cbPixelsSize, pbPixels);
    }

    return result;
}


//----------------------------------------------------------------------------------------
// DECODER
//----------------------------------------------------------------------------------------

BaseDecoder::BaseDecoder(GUID Me, GUID Container)
    : factory(NULL)
    , palette(NULL)
    , thumbnail(NULL)
    , preview(NULL)
{
    CLSID_This = Me;
    CLSID_Container = Container;
}

BaseDecoder::~BaseDecoder()
{
    ReleaseMembers(true);
}


// IUnknown Interface    

STDMETHODIMP_(ULONG) BaseDecoder::AddRef()
{
    return unknownImpl.AddRef();
}

STDMETHODIMP_(ULONG) BaseDecoder::Release()
{
    ULONG result = unknownImpl.Release();
    if (0 == result)
    {
        delete this;
    }
    return result;
}

STDMETHODIMP BaseDecoder::QueryInterface(REFIID iid, void **ppvObject)
{
    HRESULT result = E_INVALIDARG;

    if (ppvObject)
    {
        if (iid == IID_IUnknown)
        {
            *ppvObject = static_cast<IUnknown*>(this);
            AddRef();

            result = S_OK;
        }
        else if (iid == IID_IWICBitmapDecoder)
        {
            *ppvObject = static_cast<IWICBitmapDecoder*>(this);
            AddRef();

            result = S_OK;
        }
        else
        {
            result = E_NOINTERFACE;
        }
    }

    return result;
}
   //IWICBitmapDecoder Interface
HRESULT BaseDecoder::VerifyFactory()
{
    if (NULL == factory)
    {
        return CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*) &factory);
    }
    else
    {
        return S_OK;
    }
}

void BaseDecoder::ReleaseMembers(bool releaseFactory)
{
    if (releaseFactory && factory)
    {
        factory->Release();
        factory = NULL;
    }
    for (size_t i=0; i < frames.size(); ++i)
    {
        if (NULL != frames[i])
        {
            frames[i]->Release();
        }
    }
    frames.clear();
    if (palette)
    {
        palette->Release();
        palette = NULL;
    }
    for (size_t i = 0; i < colorContexts.size(); ++i)
    {
        if (NULL != colorContexts[i])
        {
            colorContexts[i]->Release();
        }
    }
    colorContexts.clear();
    if (thumbnail)
    {
        thumbnail->Release();
        thumbnail = NULL;
    }
    if (preview)
    {
        preview->Release();
        preview = NULL;
    }
}

STDMETHODIMP BaseDecoder::GetContainerFormat(GUID *pguidContainerFormat)
{
    HRESULT result = E_INVALIDARG;

    if (NULL != pguidContainerFormat)
    {
        result = S_OK;

        *pguidContainerFormat = CLSID_Container;
    }

    return result;
}

STDMETHODIMP BaseDecoder::GetDecoderInfo(IWICBitmapDecoderInfo **ppIDecoderInfo)
{
    HRESULT result = S_OK;

    IWICComponentInfo *compInfo = NULL;

    if (SUCCEEDED(result))
    {
        result = VerifyFactory();
    }

    if (SUCCEEDED(result))
    {
        result = factory->CreateComponentInfo(CLSID_This, &compInfo);
    }

    if (SUCCEEDED(result))
    {
        result = compInfo->QueryInterface(IID_IWICBitmapDecoderInfo, (void**)ppIDecoderInfo);
    }

    if (compInfo)
    {
        compInfo->Release();
    }

    return result;
}

STDMETHODIMP BaseDecoder::CopyPalette(IWICPalette *pIPalette)
{
    HRESULT result = S_OK;

    if (NULL == pIPalette)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (NULL != palette)
        {
            pIPalette->InitializeFromPalette(palette);
        }
        else
        {
            result = E_UNEXPECTED;
        }
    }

    return result;
}

STDMETHODIMP BaseDecoder::GetPreview(IWICBitmapSource **ppIPreview)
{
    HRESULT result = S_OK;

    if (NULL == ppIPreview)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (NULL != preview)
        {
            result = preview->QueryInterface(IID_IWICBitmapSource, (void**)ppIPreview);
        }
        else
        {
            result = E_UNEXPECTED;
        }
    }

    return result;
}



STDMETHODIMP BaseDecoder::GetColorContexts(UINT cCount, IWICColorContext **ppIColorContexts, UINT *pcActualCount)
{
    HRESULT result = S_OK;
    if (ppIColorContexts == NULL)
    {
        //return the number of color contexts
        if (pcActualCount != NULL)
        {
            *pcActualCount = colorContexts.size();        
        }
        else
        {
            result = E_INVALIDARG;
        }
    }
    else
    {
        //return the actual color contexts
        for (int i = 0; i < (UINT)colorContexts.size(); i++)
        {
            ppIColorContexts[i] = colorContexts[i];
            colorContexts[i]->AddRef();            
        }        
    }
    return result;
}

STDMETHODIMP BaseDecoder::GetThumbnail(IWICBitmapSource **ppIThumbnail)
{
    HRESULT result = S_OK;

    if (NULL == ppIThumbnail)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (NULL != thumbnail)
        {
            result = thumbnail->QueryInterface(IID_IWICBitmapSource, (void**)ppIThumbnail);
        }
        else
        {
            result = WINCODEC_ERR_CODECNOTHUMBNAIL;
        }
    }

    return result;
}

STDMETHODIMP BaseDecoder::GetFrameCount(UINT *pCount)
{
    HRESULT result = S_OK;

    if (NULL == pCount)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        *pCount = static_cast<UINT>(frames.size());
    }

    return result;
}

STDMETHODIMP BaseDecoder::GetFrame(UINT index, IWICBitmapFrameDecode **ppIBitmapFrame)
{
    HRESULT result = S_OK;

    if ((index >= static_cast<UINT>(frames.size())) || (NULL == ppIBitmapFrame))
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        result = frames[index]->QueryInterface(IID_IWICBitmapFrameDecode, (void**)ppIBitmapFrame);
    }

    return result;
}

STDMETHODIMP BaseDecoder::GetMetadataQueryReader(IWICMetadataQueryReader **ppIMetadataQueryReader)
{
    return E_NOTIMPL;
}
void BaseDecoder::AddDecoderFrame(BaseFrameDecode* frame)
{
     frames.push_back(frame);
     frames.back()->AddRef();
}


<|start_filename|>Data Binding/EditingCollections/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;
using System.Windows;

namespace EditingCollections
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            if (itemsControl.SelectedItem == null)
            {
                MessageBox.Show("No item is selected");
                return;
            }

            var editableCollectionView =
                itemsControl.Items as IEditableCollectionView;

            // Create a window that prompts the user to edit an item.
            var win = new ChangeItem();
            editableCollectionView.EditItem(itemsControl.SelectedItem);
            win.DataContext = itemsControl.SelectedItem;

            // If the user submits the new item, commit the changes.
            // If the user cancels the edits, discard the changes. 
            if ((bool) win.ShowDialog())
            {
                editableCollectionView.CommitEdit();
            }
            else
            {
                editableCollectionView.CancelEdit();
            }
        }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            var editableCollectionView = itemsControl.Items as IEditableCollectionView;

            if (!editableCollectionView.CanAddNew)
            {
                MessageBox.Show("You cannot add items to the list.");
                return;
            }

            // Create a window that prompts the user to enter a new
            // item to sell.
            var win = new ChangeItem {DataContext = editableCollectionView.AddNew()};

            //Create a new item to be added to the collection.

            // If the user submits the new item, commit the new
            // object to the collection.  If the user cancels 
            // adding the new item, discard the new item.
            if ((bool) win.ShowDialog())
            {
                editableCollectionView.CommitNew();
            }
            else
            {
                editableCollectionView.CancelNew();
            }
        }

        private void Remove_Click(object sender, RoutedEventArgs e)
        {
            var item = itemsControl.SelectedItem as PurchaseItem;

            if (item == null)
            {
                MessageBox.Show("No Item is selected");
                return;
            }

            var editableCollectionView =
                itemsControl.Items as IEditableCollectionView;

            if (!editableCollectionView.CanRemove)
            {
                MessageBox.Show("You cannot remove items from the list.");
                return;
            }

            if (MessageBox.Show("Are you sure you want to remove " + item.Description,
                "Remove Item", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                editableCollectionView.Remove(itemsControl.SelectedItem);
            }
        }
    }

    // PurchaseItem implements INotifyPropertyChanged so that the 
    // application is notified when a property changes.  It 
    // implements IEditableObject so that pending changes can be discarded.
}

<|start_filename|>Tools/BamlReflector/BamlReflector/ReferenceAssembly_VM.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BamlTools;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Reflection;

namespace BamlReflector
{
    public class ReferenceAssembly_VM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private readonly String _pathName;
        private Assembly _loadedAssembly;
        private String _errorMessage;
        private readonly int _hashCode;
        private readonly ObservableCollection<ApplicationResource> _applicationResources;

        public ReferenceAssembly_VM(string name)
        {
            _pathName = name;
            _errorMessage = "Have not attemped to load";
            _hashCode = name.GetHashCode();
            _applicationResources = new ObservableCollection<ApplicationResource>();
        }

        public ReferenceAssembly_VM(Assembly assembly)
        {
            _loadedAssembly = assembly;
            _pathName = String.Empty;
            _errorMessage = "Loaded by caller";
            _hashCode = assembly.GetHashCode();
            _applicationResources = LoadApplicationResources(assembly);
        }

        public bool IsLoaded
        {
            get { return _loadedAssembly != null; }
        }

        public String Name
        {
            get
            {
                if (IsLoaded)
                {
                    AssemblyName asmName = new AssemblyName(_loadedAssembly.FullName);
                    return asmName.Name;
                }
                return "Err: " + _pathName;
            }
        }

        public String AssemblyName
        {
            get
            {
                if (IsLoaded)
                    return _loadedAssembly.FullName;
                return _pathName;
            }
        }

        public Assembly LoadedAssembly
        {
            get { return _loadedAssembly; }
            set
            {
                _loadedAssembly = value;
                NotifyProperyChanged("AssemblyName");
                NotifyProperyChanged("IsLoaded");
            }
        }

        public String ErrorMessage
        {
            get { return _errorMessage; }
            set
            {
                NotifyProperyChanged("ErrorMessage");
                _errorMessage = value;
            }
        }

        public ObservableCollection<ApplicationResource> ApplicationResources
        {
            get { return _applicationResources; }
        }

        public String PathName
        {
            get { return _pathName; }
        }

        public override bool Equals(object obj)
        {
            if (!(obj is ReferenceAssembly_VM that))
                return false;

            if (this.LoadedAssembly != null && that.LoadedAssembly != null)
            {
                if (this.LoadedAssembly.FullName.Equals(that.LoadedAssembly.FullName, StringComparison.OrdinalIgnoreCase))
                    return true;
                return false;
            }
            if (this.LoadedAssembly == null && that.LoadedAssembly == null)
            {
                if (this.PathName != null && that.PathName != null)
                {
                    if (this.PathName.Equals(that.PathName, StringComparison.OrdinalIgnoreCase))
                        return true;
                    return false;
                }
                return false;
            }
            return false;
        }

        public override int GetHashCode()
        {
            return _hashCode;
        }

        //  ========= private =========================

        private void NotifyProperyChanged(string propertyName)
        {
            PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
            PropertyChanged?.Invoke(this, e);
        }

        private static ObservableCollection<ApplicationResource> LoadApplicationResources(Assembly assembly)
        {
            ObservableCollection<ApplicationResource> applicationResources = new ObservableCollection<ApplicationResource>();
            if (assembly != null)
            {
                string[] allResourceNames = assembly.GetManifestResourceNames();
                foreach (string resourceName in allResourceNames)
                {
                    if (resourceName.EndsWith(".resources", StringComparison.InvariantCultureIgnoreCase))
                    {
                        applicationResources.Add(new ApplicationResource(assembly, resourceName));
                    }
                }
            }
            return applicationResources;
        }
    }
}


<|start_filename|>Animation/AnimationTiming/ElapsedTimeControl.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace AnimationTiming
{
    public class ElapsedTimeControl : Control
    {
        public static readonly DependencyProperty CurrentTimeProperty =
            DependencyProperty.Register(
                "CurrentTime",
                typeof (TimeSpan?),
                typeof (ElapsedTimeControl),
                new FrameworkPropertyMetadata(
                    null,
                    currentTime_Changed));

        public static readonly DependencyProperty CurrentTimeAsStringProperty =
            DependencyProperty.Register("CurrentTimeAsString", typeof (string),
                typeof (ElapsedTimeControl));

        private TimeSpan? _previousTime;
        private Clock _theClock;

        public ElapsedTimeControl(TimeSpan? previousTime)
        {
            _previousTime = previousTime;
        }

        public ElapsedTimeControl()
        {
        }

        public Clock Clock
        {
            get { return _theClock; }
            set
            {
                if (_theClock != null)
                {
                    _theClock.CurrentTimeInvalidated -= OnClockTimeInvalidated;
                }

                _theClock = value;

                if (_theClock != null)
                {
                    _theClock.CurrentTimeInvalidated += OnClockTimeInvalidated;
                }
            }
        }

        public string CurrentTimeAsString
        {
            get { return GetValue(CurrentTimeAsStringProperty) as string; }
            set { SetValue(CurrentTimeAsStringProperty, value); }
        }

        private void OnClockTimeInvalidated(object sender, EventArgs args)
        {
            SetValue(CurrentTimeProperty, _theClock.CurrentTime);
        }

        private static void currentTime_Changed(DependencyObject d,
            DependencyPropertyChangedEventArgs args)
        {
            ((ElapsedTimeControl) d).SetValue(CurrentTimeAsStringProperty, args.NewValue.ToString());
        }
    }
}

<|start_filename|>Sample Applications/SlidePuzzleDemo/PuzzleLogic.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;

namespace SlidePuzzleDemo
{
    internal class PuzzleLogic
    {
        public PuzzleLogic(int numRows)
        {
            _numRows = numRows;
            _cells = new short[_numRows, _numRows];

            short tileNumber = 1;
            for (var r = 0; r < _numRows; r++)
            {
                for (var c = 0; c < _numRows; c++)
                {
                    _cells[r, c] = tileNumber++;
                }
            }

            // overwrite empty cell
            _emptyCol = _numRows - 1;
            _emptyRow = _numRows - 1;
            _cells[_emptyRow, _emptyCol] = EmptyCellId;
        }

        public bool IsEmptyCell(int row, int col) => (row == _emptyRow && col == _emptyCol);

        public MoveStatus GetMoveStatus(int row, int col)
        {
            var rowDiff = _emptyRow - row;
            var colDiff = _emptyCol - col;

            if (rowDiff == 0 && colDiff == 1)
            {
                return MoveStatus.Right;
            }
            if (rowDiff == 0 && colDiff == -1)
            {
                return MoveStatus.Left;
            }
            if (colDiff == 0 && rowDiff == 1)
            {
                return MoveStatus.Down;
            }
            if (colDiff == 0 && rowDiff == -1)
            {
                return MoveStatus.Up;
            }
            return MoveStatus.BadMove;
        }

        /// <summary>
        ///     Moves the piece
        /// </summary>
        /// <param name="row"></param>
        /// <param name="col"></param>
        /// <returns>The cell of the newly opened position</returns>
        public PuzzleCell MovePiece(int row, int col)
        {
            Debug.Assert(GetMoveStatus(row, col) != MoveStatus.BadMove);

            var cell = new PuzzleCell(_emptyRow, _emptyCol, EmptyCellId);

            var origCell = _cells[row, col];

            _cells[_emptyRow, _emptyCol] = origCell;
            _cells[row, col] = EmptyCellId;

            _emptyCol = col;
            _emptyRow = row;


            return cell;
        }

        public bool CheckForWin()
        {
            // Easy out with check for empty cell
            if (_emptyRow != _numRows - 1 || _emptyCol != _numRows - 1)
            {
                return false;
            }

            // Just walk through cells and make sure they're all consecutive values
            short tileNumber = 1;
            for (var r = 0; r < _numRows; r++)
            {
                for (var c = 0; c < _numRows; c++)
                {
                    if (tileNumber++ != _cells[r, c])
                    {
                        // Something is in the wrong place, unless we hit the empty cell.
                        if (!(r == _numRows - 1 && c == _numRows - 1))
                        {
                            return false;
                        }
                    }
                }
            }

            return true;
        }

        public PuzzleCell FindCell(short cellNumber)
        {
            Debug.Assert(cellNumber < _numRows*_numRows && cellNumber > 0);

            // This is a slow, linear operation, but for the size puzzles we have, it doesn't matter.
            for (var r = 0; r < _numRows; r++)
            {
                for (var c = 0; c < _numRows; c++)
                {
                    if (_cells[r, c] == cellNumber)
                    {
                        return new PuzzleCell(r, c, cellNumber);
                    }
                }
            }

            Debug.Assert(false, "Should have found a matching cell");
            return new PuzzleCell(-1, -1, -1);
        }

        public void MixUpPuzzle()
        {
            // Ensure that we can still solve it by only emulating legal moves.
            var r = new Random();
            var i = 8*_numRows*_numRows; // fairly arbitrary choice of number of moves
            while (i > 0)
            {
                var choice = r.Next(4);
                var row = -1;
                var col = -1;

                // 0,1,2,3 - left, right, up, down from empty cell, when possible.  Skip when not.
                switch (choice)
                {
                    case 0:
                        if (_emptyCol != 0)
                        {
                            col = _emptyCol - 1;
                            row = _emptyRow;
                        }
                        break;

                    case 1:
                        if (_emptyCol != _numRows - 1)
                        {
                            col = _emptyCol + 1;
                            row = _emptyRow;
                        }
                        break;

                    case 2:
                        if (_emptyRow != 0)
                        {
                            row = _emptyRow - 1;
                            col = _emptyCol;
                        }
                        break;

                    case 3:
                        if (_emptyRow != _numRows - 1)
                        {
                            row = _emptyRow + 1;
                            col = _emptyCol;
                        }
                        break;
                }
                if (row != -1)
                {
                    MovePiece(row, col);
                    i--;
                }
            }
        }

        #region Private Data

        private int _emptyCol;
        private int _emptyRow;
        private readonly int _numRows;
        private readonly short[,] _cells;
        private const short EmptyCellId = -1;

        #endregion
    }
}

<|start_filename|>Sample Applications/PhotoFlipperDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;

namespace PhotoFlipperDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnLoaded(object sender, EventArgs e)
        {
            // setup trackball for moving the model around
            _trackball = new Trackball();
            _trackball.Attach(this);
            _trackball.Servants.Add(myViewport3D);
            _trackball.Enabled = true;

            // Get the mesh objects for changing the material
            var mv3D = myViewport3D.Children[0] as ModelVisual3D;
            var m3DgBase = mv3D.Content as Model3DGroup;

            var m3Dg = m3DgBase.Children[0] as Model3DGroup;
            _topPlane = m3Dg.Children[2] as GeometryModel3D;
            _bottomPlane = m3Dg.Children[3] as GeometryModel3D;

            m3Dg = m3DgBase.Children[1] as Model3DGroup;
            _frontSpinPlane = m3Dg.Children[0] as GeometryModel3D;
            _backSpinPlane = m3Dg.Children[1] as GeometryModel3D;

            AnimateToNextPicture();
        }

        #region Events

        private void OnToggleAutoRun(object sender, RoutedEventArgs e)
        {
            if (_autorun)
            {
                _autorun = false;
            }
            else
            {
                _autorun = true;
                AnimateToNextPicture();
            }
        }

        private void OnSingleStep(object sender, RoutedEventArgs e)
        {
            AnimateToNextPicture();
        }

        #endregion

        #region Private Methods

        private void AnimateToNextPicture()
        {
            var nextPic = _currentPic + 1;

            if (nextPic > MaxPics)
                nextPic = 1;

            var df1 = FindResource("Pic01" + _currentPic) as DiffuseMaterial;
            var df2 = FindResource("Pic01" + nextPic) as DiffuseMaterial;

            if ((df1 == null) || (df2 == null))
                return;

            _bottomPlane.Material = df1;
            _frontSpinPlane.Material = df1;
            _topPlane.Material = df2;
            _backSpinPlane.Material = df2;

            _currentPic++;
            if (_currentPic > MaxPics)
                _currentPic = 1;

            var s = (Storyboard) FindResource("FlipPicTimeline");
            BeginStoryboard(s);
        }

        private void OnFlipPicTimeline(object sender, EventArgs e)
        {
            var clock = (Clock) sender;

            if (clock.CurrentState == ClockState.Active) // Begun case
            {
                return;
            }

            if (clock.CurrentState != ClockState.Active) // Ended case
            {
                if (_autorun)
                {
                    AnimateToNextPicture();
                }
            }
        }

        #endregion

        #region Globals

        // Geometry models
        private GeometryModel3D _topPlane;
        private GeometryModel3D _bottomPlane;
        private GeometryModel3D _frontSpinPlane;
        private GeometryModel3D _backSpinPlane;

        private Trackball _trackball;
        private int _currentPic = 1;
        private const int MaxPics = 6;

        private bool _autorun;

        #endregion
    }
}

<|start_filename|>Data Binding/CodeOnlyBinding/MyApp.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace CodeOnlyBinding
{
    internal class MyApp : Application
    {
        public Button Button;
        public Button Button2;
        public DockPanel Dp;
        public TextBlock MyText;

        public void OnClick(object obj, RoutedEventArgs args)
        {
            var fe = (FrameworkElement) obj;
            switch (fe.Name)
            {
                case "Clear":
                    BindingOperations.ClearBinding(MyText, TextBlock.TextProperty);
                    break;

                case "Refresh":

                    BindingOperations.ClearBinding(MyText, TextBlock.TextProperty);
                    //make a new source
                    var myDataObject = new MyData(DateTime.Now);
                    var myBinding = new Binding("MyDataProperty") {Source = myDataObject};
                    MyText.SetBinding(TextBlock.TextProperty, myBinding);
                    break;
            }
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var clickHandler = new RoutedEventHandler(OnClick);

            var win = new Window
            {
                Width = 250,
                Height = 200
            };

            var root = new DockPanel();
            win.Content = root;
            root.Width = 200;
            root.Height = 150;

            Dp = new DockPanel();
            DockPanel.SetDock(Dp, Dock.Top);
            root.Children.Add(Dp);

            Button = new Button
            {
                Name = "Clear",
                Content = "Clear Binding",
                Width = 120,
                Height = 30
            };
            Button.Click += clickHandler;
            DockPanel.SetDock(Button, Dock.Top);
            Dp.Children.Add(Button);

            Button2 = new Button
            {
                Name = "Refresh",
                Content = "Refresh Binding",
                Width = 120,
                Height = 30
            };
            Button2.Click += clickHandler;
            DockPanel.SetDock(Button2, Dock.Top);
            Dp.Children.Add(Button2);

            MyText = new TextBlock
            {
                Text = "no binding yet...",
                Height = 35,
                HorizontalAlignment = HorizontalAlignment.Center
            };
            DockPanel.SetDock(MyText, Dock.Top);
            Dp.Children.Add(MyText);

            win.Show();
        }
    }
}

<|start_filename|>Windows/WindowHiding/ChildWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;

namespace WindowHiding
{
    /// <summary>
    ///     Interaction logic for ChildWindow.xaml
    /// </summary>
    public partial class ChildWindow : Window
    {
        private bool _close;

        public ChildWindow()
        {
            InitializeComponent();

            // Get date/time when window is first shown
            firstShownTextBlock.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture);
        }

        // Shadow Window.Close to make sure we bypass the Hide call in 
        // the Closing event handler
        public new void Close()
        {
            _close = true;
            base.Close();
        }

        private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // Get date/time the window is shown now (ie when it becomes visible)
            if ((bool) e.NewValue)
            {
                shownThisTimeTextBlock.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture);
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            // If Close() was called, close the window (instead of hiding it)
            if (_close) return;

            // Hide the window (instead of closing it)
            e.Cancel = true;
            Hide();
        }
    }
}

<|start_filename|>Data Binding/BindingToMethod/TemperatureScale.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;
using System.Globalization;

namespace BindingToMethod
{
    public class TemperatureScale : INotifyPropertyChanged
    {
        private TempType _type;

        public TemperatureScale()
        {
        }

        public TemperatureScale(TempType type)
        {
            _type = type;
        }

        public TempType Type
        {
            get { return _type; }
            set
            {
                _type = value;
                OnPropertyChanged("Type");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public string ConvertTemp(double degree, TempType temptype)
        {
            Type = temptype;
            switch (temptype)
            {
                case TempType.Celsius:
                    return (degree*9/5 + 32).ToString(CultureInfo.InvariantCulture) + " " + "Fahrenheit";
                case TempType.Fahrenheit:
                    return ((degree - 32)/9*5).ToString(CultureInfo.InvariantCulture) + " " + "Celsius";
            }
            return "Unknown Type";
        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}

<|start_filename|>Sample Applications/SlidePuzzleDemo/PuzzleGrid.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace SlidePuzzleDemo
{
    /// <summary>
    ///     Interaction logic for PuzzleGrid.xaml
    /// </summary>
    public partial class PuzzleGrid : Grid
    {
        #region Brush Tiling Logic

        private void PuzzleGridLoaded(object sender, RoutedEventArgs e)
        {
            if (IsApplyingStyle)
            {
                Width = _masterPuzzleSize.Width;
                Height = _masterPuzzleSize.Height;

                var edgeSize = 1.0f/_numRows;
                var pieceRowHeight = _masterPuzzleSize.Height/_numRows;
                var pieceColWidth = _masterPuzzleSize.Width/_numRows;

                // Set up viewbox appropriately for each tile.
                foreach (Button b in Children)
                {
                    var root = (Border) b.Template.FindName("TheTemplateRoot", b);

                    var row = (int) b.GetValue(RowProperty);
                    var col = (int) b.GetValue(ColumnProperty);

                    var vb = new VisualBrush(_elementForPuzzle)
                    {
                        Viewbox = new Rect(col*edgeSize, row*edgeSize, edgeSize, edgeSize),
                        ViewboxUnits = BrushMappingMode.RelativeToBoundingBox
                    };

                    root.Background = vb;
                    root.Height = pieceRowHeight;
                    root.Width = pieceColWidth;
                }
            }
        }

        #endregion

        #region Grid Setup Logic

        public PuzzleGrid()
        {
            InitializeComponent();

            // Centralize handling of all clicks in the puzzle grid.
            AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(OnPuzzleButtonClick));
        }

        private void SetupThePuzzleGridStructure()
        {
            _puzzleLogic = new PuzzleLogic(_numRows);

            // Define rows and columns in the Grid
            for (var row = 0; row < _numRows; row++)
            {
                var r = new RowDefinition {Height = GridLength.Auto};
                RowDefinitions.Add(r);

                var c = new ColumnDefinition {Width = GridLength.Auto};
                ColumnDefinitions.Add(c);
            }

            var buttonStyle = (Style) Resources["PuzzleButtonStyle"];

            // Now add the buttons in
            var i = 1;
            for (var row = 0; row < _numRows; row++)
            {
                for (var col = 0; col < _numRows; col++)
                {
                    // lower right cell is empty
                    if (_numRows != 1 && row == _numRows - 1 && col == _numRows - 1)
                    {
                        continue;
                    }
                    var b = new Button {FontSize = 24};

                    // Styling comes in only here...
                    if (IsApplyingStyle)
                    {
                        b.Style = buttonStyle;
                    }

                    b.SetValue(RowProperty, row);
                    b.SetValue(ColumnProperty, col);
                    b.Content = i.ToString();
                    i++;
                    Children.Add(b);
                }
            }
        }

        #endregion

        #region Interaction Logic

        private void OnPuzzleButtonClick(object sender, RoutedEventArgs e)
        {
            var b = e.Source as Button;
            if (b != null)
            {
                var row = (int) b.GetValue(RowProperty);
                var col = (int) b.GetValue(ColumnProperty);

                var moveStatus = _puzzleLogic.GetMoveStatus(row, col);

                MoveMade?.Invoke(this, new HandledEventArgs(moveStatus != MoveStatus.BadMove));

                if (moveStatus != MoveStatus.BadMove)
                {
                    if (!IsApplyingStyle || !ShouldAnimateInteractions)
                    {
                        // Not templated, just move piece
                        MovePiece(b, row, col);
                    }
                    else
                    {
                        AnimatePiece(b, row, col, moveStatus);
                    }
                }
            }
        }


        // Assumed to be a valid move.
        private void AnimatePiece(Button b, int row, int col, MoveStatus moveStatus)
        {
            var root = (FrameworkElement) b.Template.FindName("TheTemplateRoot", b);

            double distance;
            bool isMoveHorizontal;

            Debug.Assert(moveStatus != MoveStatus.BadMove);
            if (moveStatus == MoveStatus.Left || moveStatus == MoveStatus.Right)
            {
                isMoveHorizontal = true;
                distance = (moveStatus == MoveStatus.Left ? -1 : 1)*root.Width;
            }
            else
            {
                isMoveHorizontal = false;
                distance = (moveStatus == MoveStatus.Up ? -1 : 1)*root.Height;
            }

            // pull the animation after it's complete, because we move change Grid cells.
            var slideAnim = new DoubleAnimation(distance, TimeSpan.FromSeconds(0.3), FillBehavior.Stop);
            slideAnim.CurrentStateInvalidated += delegate(object sender2, EventArgs e2)
            {
                // Anonymous delegate -- invoke when done.
                var clock = (Clock) sender2;
                if (clock.CurrentState != ClockState.Active)
                {
                    // remove the render transform and really move the piece in the Grid.
                    MovePiece(b, row, col);
                }
            };

            var directionProperty =
                isMoveHorizontal ? TranslateTransform.XProperty : TranslateTransform.YProperty;

            root.RenderTransform.BeginAnimation(directionProperty, slideAnim);
        }


        // Assumed to be a valid move.
        private void MovePiece(Button b, int row, int col)
        {
            var newPosition = _puzzleLogic.MovePiece(row, col);

            b.SetValue(ColumnProperty, newPosition.Col);
            b.SetValue(RowProperty, newPosition.Row);

            if (_puzzleLogic.CheckForWin())
            {
                PuzzleWon?.Invoke(this, EventArgs.Empty);
            }
        }

        #endregion

        #region Less Consequential Portions

        public void MixUpPuzzle()
        {
            _puzzleLogic.MixUpPuzzle();

            short cellNumber = 1;
            foreach (Button b in Children)
            {
                var location = _puzzleLogic.FindCell(cellNumber++);
                b.SetValue(ColumnProperty, location.Col);
                b.SetValue(RowProperty, location.Row);
            }
        }

        public void ShowNumbers(bool showNumbers)
        {
            var nlb = ((SolidColorBrush) Resources["NumberLabelBrush"]).Clone();
            nlb.Color = showNumbers ? Colors.Yellow : Colors.Transparent;
            Resources["NumberLabelBrush"] = nlb;
        }

        #endregion

        #region Public Properties

        public int NumRows
        {
            get { return _numRows; }
            set
            {
                // Only support setting this once per PuzzleGrid instance.
                if (_numRows != -1)
                {
                    throw new InvalidOperationException("NumRows already initialized for this PuzzleGrid instance.");
                }
                _numRows = value;
                CheckToSetup();
            }
        }

        public UIElement ElementToChopUp
        {
            get { return _elementForPuzzle; }
            set
            {
                if (_elementForPuzzle != null)
                {
                    throw new InvalidOperationException(
                        "ElementForPuzzle already initialized for this PuzzleGrid instance.");
                }
                _elementForPuzzle = value;
                CheckToSetup();
            }
        }

        public bool IsApplyingStyle { get; set; } = true;

        public bool ShouldAnimateInteractions { get; set; } = false;

        public Size PuzzleSize
        {
            get { return _masterPuzzleSize; }
            set
            {
                if (!_masterPuzzleSize.IsEmpty)
                {
                    throw new InvalidOperationException(
                        "SizeForPuzzle already initialized for this PuzzleGrid instance.");
                }
                _masterPuzzleSize = value;
                CheckToSetup();
            }
        }

        public event EventHandler PuzzleWon;
        public event EventHandler<HandledEventArgs> MoveMade;

        private void CheckToSetup()
        {
            if (_numRows != -1 && (!IsApplyingStyle || _elementForPuzzle != null) && !_masterPuzzleSize.IsEmpty)
            {
                SetupThePuzzleGridStructure();
            }
        }

        #endregion

        #region Private Data

        private PuzzleLogic _puzzleLogic;
        private Size _masterPuzzleSize = Size.Empty;
        private UIElement _elementForPuzzle;
        private int _numRows = -1;

        #endregion
    }
}

<|start_filename|>Data Binding/EditingCollections/ChangeItem.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace EditingCollections
{
    /// <summary>
    ///     Interaction logic for ChangeItem.xaml
    /// </summary>
    public partial class ChangeItem : Window
    {
        public ChangeItem()
        {
            InitializeComponent();
        }

        private void Submit_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
            Close();
        }
    }
}

<|start_filename|>Visual Layer/CompositionTarget/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace CompositionTarget
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private double _frameCounter;
        private Point _pt;

        public MainWindow()
        {
            InitializeComponent();

            // Add an event handler to update canvas background color just before it is rendered.
            System.Windows.Media.CompositionTarget.Rendering += UpdateColor;
        }

        // Called just before frame is rendered to allow custom drawing.
        protected void UpdateColor(object sender, EventArgs e)
        {
            if (_frameCounter++ == 0)
            {
                // Starting timing.
                _stopwatch.Start();
            }

            // Determine frame rate in fps (frames per second).
            var frameRate = (long) (_frameCounter/_stopwatch.Elapsed.TotalSeconds);
            if (frameRate > 0)
            {
                // Update elapsed time, number of frames, and frame rate.
                myStopwatchLabel.Content = _stopwatch.Elapsed.ToString();
                myFrameCounterLabel.Content = _frameCounter.ToString(CultureInfo.InvariantCulture);
                myFrameRateLabel.Content = frameRate.ToString();
            }

            // Update the background of the canvas by converting MouseMove info to RGB info.
            var redColor = (byte) (_pt.X/3.0);
            var blueColor = (byte) (_pt.Y/2.0);
            myCanvas.Background = new SolidColorBrush(Color.FromRgb(redColor, 0x0, blueColor));
        }

        public void MouseMoveHandler(object sender, MouseEventArgs e)
        {
            // Retreive the coordinates of the mouse button event.
            _pt = e.GetPosition((UIElement) sender);
        }
    }
}

<|start_filename|>Data Binding/ValidateItemSample/PurchaseItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;

namespace ValidateItemSample
{
    public class PurchaseItem : INotifyPropertyChanged, IEditableObject
    {
        private ItemData _copyData = ItemData.NewItem();
        private ItemData _currentData = ItemData.NewItem();

        public PurchaseItem()
        {
        }

        public PurchaseItem(string desc, double price, DateTime endDate)
        {
            Description = desc;
            Price = price;
            OfferExpires = endDate;
        }

        public string Description
        {
            get { return _currentData.Description; }
            set
            {
                if (_currentData.Description != value)
                {
                    _currentData.Description = value;
                    NotifyPropertyChanged("Description");
                }
            }
        }

        public double Price
        {
            get { return _currentData.Price; }
            set
            {
                if (_currentData.Price != value)
                {
                    _currentData.Price = value;
                    NotifyPropertyChanged("Price");
                }
            }
        }

        public DateTime OfferExpires
        {
            get { return _currentData.OfferExpires; }
            set
            {
                if (value != _currentData.OfferExpires)
                {
                    _currentData.OfferExpires = value;
                    NotifyPropertyChanged("OfferExpires");
                }
            }
        }

        public override string ToString() => $"{Description}, {Price:c}, {OfferExpires:D}";

        private struct ItemData
        {
            internal string Description;
            internal DateTime OfferExpires;
            internal double Price;

            internal static ItemData NewItem()
            {
                var data = new ItemData
                {
                    Description = "New item",
                    Price = 0,
                    OfferExpires = DateTime.Now + new TimeSpan(7, 0, 0, 0)
                };

                return data;
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string info)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
        }

        #endregion

        #region IEditableObject Members

        public void BeginEdit()
        {
            _copyData = _currentData;
        }

        public void CancelEdit()
        {
            _currentData = _copyData;
            NotifyPropertyChanged("");
        }

        public void EndEdit()
        {
            _copyData = ItemData.NewItem();
        }

        #endregion
    }
}

<|start_filename|>Graphics/Brushes/GradientBrushesExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace Brushes
{
    /// <summary>
    ///     Implements the show/hide gradient stops functionlity for
    ///     GradientBrushesExample.xaml.
    /// </summary>
    public partial class GradientBrushesExample : Page
    {
        public GradientBrushesExample()
        {
            InitializeComponent();
        }

        private void PageLoaded(object sender, RoutedEventArgs args)
        {
            showHideGradientStopsCheckBox.Checked += ShowGradientStops;
            showHideGradientStopsCheckBox.Unchecked += HideGradientStops;
        }

        private void ShowGradientStops(object sender, RoutedEventArgs args)
        {
            gradientLine1.Opacity = 1.0;
            gradientLine2.Opacity = 1.0;
            gradientLine3.Opacity = 1.0;
            gradientLine4.Opacity = 1.0;
            gradientLine5.Opacity = 1.0;
            gradientPath1.Opacity = 1.0;
            gradientPath2.Opacity = 1.0;
            gradientPath3.Opacity = 1.0;
            gradientPath4.Opacity = 1.0;
            gradientPath5.Opacity = 1.0;
        }

        private void HideGradientStops(object sender, RoutedEventArgs args)
        {
            gradientLine1.Opacity = 0.0;
            gradientLine2.Opacity = 0.0;
            gradientLine3.Opacity = 0.0;
            gradientLine4.Opacity = 0.0;
            gradientLine5.Opacity = 0.0;
            gradientPath1.Opacity = 0.0;
            gradientPath2.Opacity = 0.0;
            gradientPath3.Opacity = 0.0;
            gradientPath4.Opacity = 0.0;
            gradientPath5.Opacity = 0.0;
        }
    }
}

<|start_filename|>Data Binding/MasterDetail/Team.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace MasterDetail
{
    public class Team
    {
        public Team(string name)
        {
            Name = name;
        }

        public string Name { get; }

        public override string ToString() => Name;
    }
}

<|start_filename|>Sample Applications/ExpenseIt/ExpenseItDemo/LineItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace ExpenseItDemo
{
    public class LineItem : INotifyPropertyChanged
    {
        private int _cost;
        private string _description = "(Description)";
        private string _type = "(Expense type)";

        public string Type
        {
            get { return _type; }
            set
            {
                _type = value;
                OnPropertyChanged("Type");
            }
        }

        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                OnPropertyChanged("Description");
            }
        }

        public int Cost
        {
            get { return _cost; }
            set
            {
                _cost = value;
                OnPropertyChanged("Cost");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/IExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    public interface IExpression
    {
        double Evaluate();
        IExpression Differentiate(string byVar);
        IExpression Simplify();
        string ToString();
    }
}

<|start_filename|>Migration and Interoperability/WpfHostingWindowsFormsControl/WPFApp/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Navigation;
using MyControls;

namespace WPFApp
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Application _app;
        private SolidColorBrush _initBackBrush;
        private FontFamily _initFontFamily;
        private double _initFontSize;
        private FontStyle _initFontStyle;
        private FontWeight _initFontWeight;
        private SolidColorBrush _initForeBrush;
        private MainWindow _myWindow;
        private bool _uiIsReady;

        public MainWindow() {
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
            Init(sender, e);
        }

        private void Init(object sender, EventArgs e)
        {
            _app = Application.Current;
            _myWindow = (MainWindow)_app.MainWindow;
            _myWindow.SizeToContent = SizeToContent.WidthAndHeight;
            wfh.TabIndex = 10;
            _initFontSize = wfh.FontSize;
            _initFontWeight = wfh.FontWeight;
            _initFontFamily = wfh.FontFamily;
            _initFontStyle = wfh.FontStyle;
            _initBackBrush = (SolidColorBrush) wfh.Background;
            _initForeBrush = (SolidColorBrush) wfh.Foreground;
            (wfh.Child as MyControl).OnButtonClick += Pane1_OnButtonClick;
            _uiIsReady = true;
        }

        private void BackColorChanged(object sender, RoutedEventArgs e)
        {
            if (sender == rdbtnBackGreen)
                wfh.Background = new SolidColorBrush(Colors.LightGreen);
            else if (sender == rdbtnBackSalmon)
                wfh.Background = new SolidColorBrush(Colors.LightSalmon);
            else if (_uiIsReady)
                wfh.Background = _initBackBrush;
        }

        private void ForeColorChanged(object sender, RoutedEventArgs e)
        {
            if (sender == rdbtnForeRed)
                wfh.Foreground = new SolidColorBrush(Colors.Red);
            else if (sender == rdbtnForeYellow)
                wfh.Foreground = new SolidColorBrush(Colors.Yellow);
            else if (_uiIsReady)
                wfh.Foreground = _initForeBrush;
        }

        private void FontChanged(object sender, RoutedEventArgs e)
        {
            if (sender == rdbtnTimes)
                wfh.FontFamily = new FontFamily("Times New Roman");
            else if (sender == rdbtnWingdings)
                wfh.FontFamily = new FontFamily("Wingdings");
            else if (_uiIsReady)
                wfh.FontFamily = _initFontFamily;
        }

        private void FontSizeChanged(object sender, RoutedEventArgs e)
        {
            if (sender == rdbtnTen)
                wfh.FontSize = 10;
            else if (sender == rdbtnTwelve)
                wfh.FontSize = 12;
            else if (_uiIsReady)
                wfh.FontSize = _initFontSize;
        }

        private void StyleChanged(object sender, RoutedEventArgs e)
        {
            if (sender == rdbtnItalic)
                wfh.FontStyle = FontStyles.Italic;
            else if (_uiIsReady)
                wfh.FontStyle = _initFontStyle;
        }

        private void WeightChanged(object sender, RoutedEventArgs e)
        {
            if (sender == rdbtnBold)
                wfh.FontWeight = FontWeights.Bold;
            else if (_uiIsReady)
                wfh.FontWeight = _initFontWeight;
        }

        //Handle button clicks on the Windows Form control
        private void Pane1_OnButtonClick(object sender, MyControlEventArgs args)
        {
            txtName.Inlines.Clear();
            txtAddress.Inlines.Clear();
            txtCity.Inlines.Clear();
            txtState.Inlines.Clear();
            txtZip.Inlines.Clear();

            if (args.IsOk)
            {
                txtName.Inlines.Add(" " + args.MyName);
                txtAddress.Inlines.Add(" " + args.MyStreetAddress);
                txtCity.Inlines.Add(" " + args.MyCity);
                txtState.Inlines.Add(" " + args.MyState);
                txtZip.Inlines.Add(" " + args.MyZip);
            }
        }
    }
}

<|start_filename|>Sample Applications/LayoutTransitionsDemo/LayoutToLayoutTarget.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;

namespace LayoutTransitionsDemo
{
    public class LayoutToLayoutTarget : Border
    {
        /*
         * Create a dependency property for binding the host to the target
         * */

        public static readonly DependencyProperty HostProperty =
            DependencyProperty.Register("Host", typeof (LayoutToLayoutHost), typeof (LayoutToLayoutTarget), null);

        /*
         * If the layout changes for the target (the object that actually gets passed between layout schemes)
         * then let the host know so that it can update itself if it wants to (i.e. if it's not in the middle of
         * an animation).
         * */

        public LayoutToLayoutTarget()
        {
            LayoutUpdated += UpdateHost;
        }

        public LayoutToLayoutHost Host
        {
            get { return (LayoutToLayoutHost) GetValue(HostProperty); }
            set { SetValue(HostProperty, value); }
        }

        private void UpdateHost(object sender, EventArgs e)
        {
            Host?.UpdateFromTarget();
        }
    }
}

<|start_filename|>Sample Applications/ExpenseIt/ExpenseItDemo/Validation/NumberValidationrule.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;
using System.Windows.Controls;

// ValidationRule

// CultureInfo

namespace ExpenseItDemo.Validation
{
    // Number Validation Rule
    public class NumberValidationRule : ValidationRule
    {
        /// <summary>
        ///     Must the number be a specific length
        /// </summary>
        public bool IsFixedLength { get; set; }

        /// <summary>
        ///     The required length of the number, if IsFixedLength is true
        /// </summary>
        public int Length { get; set; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            // Is the value a number?
            int number;
            if (!int.TryParse((string) value, out number))
            {
                var msg = $"{value} is not a number.";
                return new ValidationResult(false, msg);
            }

            // Does value contain the number of digits specified by Length?
            if (IsFixedLength && (((string) value).Length != Length))
            {
                var msg = $"Number must be {Length} digits long.";
                return new ValidationResult(false, msg);
            }

            // Number is valid
            return new ValidationResult(true, null);
        }
    }
}

<|start_filename|>Data Binding/MultiBinding/PersonName.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace MultiBinding
{
    public class PersonName
    {
        public PersonName(string first, string last)
        {
            FirstName = first;
            LastName = last;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

<|start_filename|>Animation/LocalAnimations/LocalAnimationExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace LocalAnimations
{
    // Create the demonstration.
    public class LocalAnimationExample : Page
    {
        public LocalAnimationExample()
        {
            WindowTitle = "Local Animation Example";
            var myStackPanel = new StackPanel {Margin = new Thickness(20)};


            // Create and set the Button.
            var aButton = new Button {Content = "A Button"};

            // Animate the Button's Width.
            var myDoubleAnimation = new DoubleAnimation
            {
                From = 75,
                To = 300,
                Duration = new Duration(TimeSpan.FromSeconds(5)),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            // Apply the animation to the button's Width property.
            aButton.BeginAnimation(WidthProperty, myDoubleAnimation);

            // Create and animate a Brush to set the button's Background.
            var myBrush = new SolidColorBrush {Color = Colors.Blue};

            var myColorAnimation = new ColorAnimation
            {
                From = Colors.Blue,
                To = Colors.Red,
                Duration = new Duration(TimeSpan.FromMilliseconds(7000)),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            // Apply the animation to the brush's Color property.
            myBrush.BeginAnimation(SolidColorBrush.ColorProperty, myColorAnimation);
            aButton.Background = myBrush;

            // Add the Button to the panel.
            myStackPanel.Children.Add(aButton);
            Content = myStackPanel;
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/utility.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of Utility/Helper functions
//----------------------------------------------------------------------------------------

#include "precomp.hpp"

//----------------------------------------------------------------------------------------
// MISC UTILITY FUNCTIONS
//----------------------------------------------------------------------------------------
UINT GetScanlineStride(UINT width, REFWICPixelFormatGUID pixelFormat)
{
    UINT bpp = 0;

    if ((GUID_WICPixelFormat1bppIndexed == pixelFormat) ||
        (GUID_WICPixelFormatBlackWhite == pixelFormat))
    {
        bpp = 1;
    }
    else if ((GUID_WICPixelFormat2bppIndexed == pixelFormat) ||
             (GUID_WICPixelFormat2bppGray == pixelFormat))
    {
        bpp = 2;
    }
    else if ((GUID_WICPixelFormat4bppIndexed == pixelFormat) ||
             (GUID_WICPixelFormat4bppGray == pixelFormat))
    {
        bpp = 4;
    }
    else if ((GUID_WICPixelFormat8bppIndexed == pixelFormat) ||
             (GUID_WICPixelFormat8bppGray == pixelFormat))
    {
        bpp = 8;
    }
    else if ((GUID_WICPixelFormat16bppBGR555 == pixelFormat) ||
             (GUID_WICPixelFormat16bppBGR565 == pixelFormat) ||
             (GUID_WICPixelFormat16bppGray == pixelFormat)   ||
             (GUID_WICPixelFormat16bppGrayFixedPoint == pixelFormat))
    {
        bpp = 16;
    }
    else if ((GUID_WICPixelFormat24bppBGR == pixelFormat) ||
             (GUID_WICPixelFormat24bppRGB == pixelFormat))
    {
        bpp = 24;
    }
    else if ((GUID_WICPixelFormat32bppBGR == pixelFormat)       ||
             (GUID_WICPixelFormat32bppBGRA == pixelFormat)      ||
             (GUID_WICPixelFormat32bppPBGRA == pixelFormat)     ||
             (GUID_WICPixelFormat32bppGrayFloat == pixelFormat) ||
             (GUID_WICPixelFormat32bppBGR101010 == pixelFormat) ||
             (GUID_WICPixelFormat32bppCMYK == pixelFormat))
    {
        bpp = 32;
    }
    else if ((GUID_WICPixelFormat48bppRGBFixedPoint == pixelFormat) ||
             (GUID_WICPixelFormat48bppRGB == pixelFormat))
    {
        bpp = 48;
    }
    else if ((GUID_WICPixelFormat64bppRGBA == pixelFormat) ||
             (GUID_WICPixelFormat64bppPRGBA == pixelFormat))
    {
        bpp = 64;
    }
    else if ((GUID_WICPixelFormat96bppRGBFixedPoint == pixelFormat))
    {
        bpp = 96;
    }
    else if ((GUID_WICPixelFormat128bppRGBAFloat == pixelFormat)  ||
             (GUID_WICPixelFormat128bppPRGBAFloat == pixelFormat) ||
             (GUID_WICPixelFormat128bppRGBFloat == pixelFormat))
    {
        bpp = 128;
    }	

    return (bpp * width + 7)/8;
};




<|start_filename|>Windows/CustomWindowUI/CustomWindowChrome.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace CustomWindowUI
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class CustomWindowChrome : Window
    {
        public CustomWindowChrome()
        {
            InitializeComponent();
        }

        private void CloseButtonRectangle_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void ResizeThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            // Resize window width (honoring minimum width)
            var desiredWidth = (int) (ActualWidth + e.HorizontalChange);
            var minWidth = (int) (MinWidth + resizeThumb.Width + resizeThumb.Margin.Right);
            Width = Math.Max(desiredWidth, minWidth);

            // Resize window height (honoring minimum height)
            var desiredHeight = (int) (ActualHeight + e.VerticalChange);
            var minHeight = (int) (MinHeight + resizeThumb.Height + resizeThumb.Margin.Bottom);
            Height = Math.Max(desiredHeight, minHeight);
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/TokenSet.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    //--------------------------------------------------------------

    // TokenTypes are bit-exclusive so that we can easily group them
    //  together in sets using a bit-vector

    //--------------------------------------------------------------

    public class TokenSet
    {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private readonly uint _tokens;
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public TokenSet(TokenType type)
        {
            _tokens = (uint) type;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public TokenSet(TokenSet t)
        {
            _tokens = t._tokens;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private TokenSet(uint tokens)
        {
            _tokens = tokens;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public static TokenSet operator +(TokenSet t1, TokenSet t2) => new TokenSet(t1._tokens | t2._tokens);

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public static TokenSet operator +(TokenSet t1, TokenType t2) => new TokenSet(t1._tokens | (uint)t2);

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public bool Contains(TokenType type) => (_tokens & (uint)type) != 0;
    }
}

<|start_filename|>Documents/Flow Content/FlowDocumentNewsClient/DockPanel3.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace FlowDocumentNewsClient
{
    public partial class DockPanel3 : DockPanel
    {
        public void ColWidest(object sender, RoutedEventArgs args)
        {
            fd3.ColumnWidth = 150;
        }

        public void ColMore(object sender, RoutedEventArgs args)
        {
            fd3.ColumnWidth = 250;
        }

        public void ColAverage(object sender, RoutedEventArgs args)
        {
            fd3.ColumnWidth = 350;
        }

        public void ColFewer(object sender, RoutedEventArgs args)
        {
            fd3.ColumnWidth = 450;
        }

        public void ColLeast(object sender, RoutedEventArgs args)
        {
            fd3.ColumnWidth = 550;
        }

        public void TextLargest(object sender, RoutedEventArgs args)
        {
            fd3.FontSize = 18;
        }

        public void TextLarge(object sender, RoutedEventArgs args)
        {
            fd3.FontSize = 15;
        }

        public void TextAverage(object sender, RoutedEventArgs args)
        {
            fd3.FontSize = 12;
        }

        public void TextSmall(object sender, RoutedEventArgs args)
        {
            fd3.FontSize = 10;
        }

        public void TextSmallest(object sender, RoutedEventArgs args)
        {
            fd3.FontSize = 8;
        }
    }
}

<|start_filename|>Tools/LocBaml/TranslationDictionaries.cs<|end_filename|>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//---------------------------------------------------------------------------
//
// Description: TranslationDictionariesWriter & TranslationDictionariesReader class
//
//---------------------------------------------------------------------------

using System;
using System.IO;
using System.Resources;
using System.Collections;
using System.Globalization;
using System.Windows;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Markup.Localizer;

namespace BamlLocalization
{
    /// <summary>
    /// Writer to write out localizable values into CSV or tab-separated txt files.     
    /// </summary>
    internal static class  TranslationDictionariesWriter
    {
        /// <summary>
        /// Write the localizable key-value pairs
        /// </summary>
        /// <param name="options"></param>
        internal static void Write(LocBamlOptions options)            
        {   
            Stream output = new FileStream(options.Output, FileMode.Create);
            InputBamlStreamList bamlStreamList = new InputBamlStreamList(options);

            using (ResourceTextWriter writer = new ResourceTextWriter(options.TranslationFileType, output))
            {
                options.WriteLine(StringLoader.Get("WriteBamlValues"));
                for (int i = 0; i < bamlStreamList.Count; i++)
                {
                    options.Write("    ");
                    options.Write(StringLoader.Get("ProcessingBaml", bamlStreamList[i].Name));

                    // Search for comment file in the same directory. The comment file has the extension to be 
                    // "loc".
                    string commentFile = Path.ChangeExtension(bamlStreamList[i].Name, "loc");
                    TextReader commentStream = null;

                    try
                    {
                        if (File.Exists(commentFile))
                        {
                            commentStream = new StreamReader(commentFile);
                        }

                        // create the baml localizer
                        BamlLocalizer mgr = new BamlLocalizer(
                            bamlStreamList[i].Stream,
                            new BamlLocalizabilityByReflection(options.Assemblies),
                            commentStream
                            );

                        // extract localizable resource from the baml stream
                        BamlLocalizationDictionary dict = mgr.ExtractResources();

                        // write out each resource
                        foreach (DictionaryEntry entry in dict)
                        {
                            // column 1: baml stream name
                            writer.WriteColumn(bamlStreamList[i].Name);
                            
                            BamlLocalizableResourceKey key = (BamlLocalizableResourceKey) entry.Key;
                            BamlLocalizableResource resource = (BamlLocalizableResource)entry.Value;

                            // column 2: localizable resource key
                            writer.WriteColumn(LocBamlConst.ResourceKeyToString(key));

                            // column 3: localizable resource's category
                            writer.WriteColumn(resource.Category.ToString());

                            // column 4: localizable resource's readability
                            writer.WriteColumn(resource.Readable.ToString());

                            // column 5: localizable resource's modifiability
                            writer.WriteColumn(resource.Modifiable.ToString());

                            // column 6: localizable resource's localization comments
                            writer.WriteColumn(resource.Comments);

                            // column 7: localizable resource's content
                            writer.WriteColumn(resource.Content);

                            // Done. finishing the line
                            writer.EndLine();
                        }

                        options.WriteLine(StringLoader.Get("Done"));
                    }
                    finally
                    {
                        if (commentStream != null)
                            commentStream.Close();
                    }
                }
                
                // close all the baml input streams, output stream is closed by writer.
                bamlStreamList.Close();            
            }   
        }
    }


    /// <summary>
    /// Reader to read the translations from CSV or tab-separated txt file    
    /// </summary> 
    internal class TranslationDictionariesReader
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="reader">resoure text reader that reads CSV or a tab-separated txt file</param>
        internal TranslationDictionariesReader(ResourceTextReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            // hash key is case insensitive strings
            _table = new Hashtable();

            // we read each Row
            int rowNumber = 0;
            while (reader.ReadRow())
            {
                rowNumber ++;
                
                // field #1 is the baml name.
                string bamlName = reader.GetColumn(0);

                // it can't be null
                if (bamlName == null)
                    throw new ApplicationException(StringLoader.Get("EmptyRowEncountered"));

                if (string.IsNullOrEmpty(bamlName))
                {
                    // allow for comment lines in csv file.
                    // each comment line starts with ",". It will make the first entry as String.Empty.
                    // and we will skip the whole line.
                    continue;   // if the first column is empty, take it as a comment line
                }

                // field #2: key to the localizable resource
                string key = reader.GetColumn(1);
                if (key == null)
                    throw new ApplicationException(StringLoader.Get("NullBamlKeyNameInRow"));

                BamlLocalizableResourceKey resourceKey = LocBamlConst.StringToResourceKey(key);

                // get the dictionary 
                BamlLocalizationDictionary dictionary = this[bamlName];                
                if (dictionary == null)
                {   
                    // we create one if it is not there yet.
                    dictionary = new BamlLocalizationDictionary();
                    this[bamlName] = dictionary;                
                }
                
                BamlLocalizableResource resource;
                
                // the rest of the fields are either all null,
                // or all non-null. If all null, it means the resource entry is deleted.
                
                // get the string category
                string categoryString = reader.GetColumn(2);
                if (categoryString == null)
                {
                    // it means all the following fields are null starting from column #3.
                    resource = null;
                }
                else
                {
                    // the rest must all be non-null.
                    // the last cell can be null if there is no content
                    for (int i = 3; i < 6; i++)
                    {
                        if (reader.GetColumn(i) == null)
                            throw new Exception(StringLoader.Get("InvalidRow"));
                    }

                    // now we know all are non-null. let's try to create a resource
                    resource  = new BamlLocalizableResource();
                    
                    // field #3: Category
                    resource.Category = (LocalizationCategory) StringCatConverter.ConvertFrom(categoryString);
                    
                    // field #4: Readable
                    resource.Readable     = (bool) BoolTypeConverter.ConvertFrom(reader.GetColumn(3));

                    // field #5: Modifiable
                    resource.Modifiable   = (bool) BoolTypeConverter.ConvertFrom(reader.GetColumn(4));

                    // field #6: Comments
                    resource.Comments     = reader.GetColumn(5);

                    // field #7: Content
                    resource.Content      = reader.GetColumn(6);

                    // in case content being the last column, consider null as empty.
                    if (resource.Content == null)
                        resource.Content = string.Empty;

                    // field > #7: Ignored.
                }                             

                // at this point, we are good.
                // add to the dictionary.
                dictionary.Add(resourceKey, resource);
            }        
        }

        internal BamlLocalizationDictionary this[string key]
        {
            get{
                return (BamlLocalizationDictionary) _table[key.ToLowerInvariant()];
            }
            set
            {
                _table[key.ToLowerInvariant()] = value;
            }
        }

        // hashtable that maps from baml name to its ResourceDictionary
        private Hashtable _table;                
        private static TypeConverter BoolTypeConverter  = TypeDescriptor.GetConverter(true);
        private static TypeConverter StringCatConverter = TypeDescriptor.GetConverter(LocalizationCategory.Text);
    }
}


<|start_filename|>Data Binding/BindingToMethod/InvalidCharacteRrule.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Controls;

namespace BindingToMethod
{
    internal class InvalidCharacterRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var myvalue = 0.00;

            try
            {
                if (((string) value).Length > 0)
                    myvalue = double.Parse((string) value);
            }
            catch (Exception e)
            {
                return new ValidationResult(false, "Illegal characters or " + e.Message);
            }

            return new ValidationResult(true, null);
        }
    }
}

<|start_filename|>Tools/LocBaml/ResourceGenerator.cs<|end_filename|>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//---------------------------------------------------------------------------
//
// Description: ResourceGenerator class
//              It generates the localized baml from translations
//
//---------------------------------------------------------------------------
using System;
using System.IO;
using System.Windows;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
using System.Resources;
using System.Threading; 
using System.Windows.Threading;
using System.Windows.Markup.Localizer;

namespace BamlLocalization
{
    /// <summary>
    /// ResourceGenerator class
    /// </summary>
    internal static class ResourceGenerator
    {
        /// <summary>
        /// Generates localized Baml from translations
        /// </summary>
        /// <param name="options">LocBaml options</param>
        /// <param name="dictionaries">the translation dictionaries</param>
        internal static void Generate(LocBamlOptions options, TranslationDictionariesReader dictionaries)
        {   
            // base on the input, we generate differently            
            switch(options.InputType)
            {
                case FileType.BAML :                    
                {                    
                    // input file name
                    string bamlName = Path.GetFileName(options.Input);

                    // outpuf file name is Output dir + input file name
                    string outputFileName = GetOutputFileName(options);                    

                    // construct the full path
                    string fullPathOutput = Path.Combine(options.Output, outputFileName);

                    options.Write(StringLoader.Get("GenerateBaml", fullPathOutput));
                                                                                
                    using (Stream input = File.OpenRead(options.Input))
                    {
                        using (Stream output = new FileStream(fullPathOutput, FileMode.Create))
                        {
                            BamlLocalizationDictionary dictionary = dictionaries[bamlName];

                            // if it is null, just create an empty dictionary.
                            if (dictionary == null)                            
                                dictionary = new BamlLocalizationDictionary();
                            
                            GenerateBamlStream(input, output, dictionary, options);
                        }                               
                    }

                    options.WriteLine(StringLoader.Get("Done"));
                    break;
                }
                case FileType.RESOURCES :
                {
                    string outputFileName = GetOutputFileName(options);
                    string fullPathOutput = Path.Combine(options.Output, outputFileName);
                                       
                    using (Stream input = File.OpenRead(options.Input))
                    {
                        using (Stream output = File.OpenWrite(fullPathOutput))
                        {
                            // create a Resource reader on the input;
                            IResourceReader reader = new ResourceReader(input);
    
                            // create a writer on the output;
                            IResourceWriter writer = new ResourceWriter(output);

                            GenerateResourceStream(
                                options,         // options
                                options.Input,   // resources name
                                reader,          // resource reader
                                writer,          // resource writer
                                dictionaries);   // translations

                            reader.Close();
                            
                            // now generate and close
                            writer.Generate();
                            writer.Close();
                        }
                    }

                    options.WriteLine(StringLoader.Get("DoneGeneratingResource", outputFileName));
                    break;
                }
		case FileType.EXE:
                case FileType.DLL:
                {   
                    GenerateAssembly(options, dictionaries);                    
                    break;
                }
                default:
                {
                    Debug.Assert(false, "Can't generate to this type");       
                    break;
                }
            }            
        }


        private static void GenerateBamlStream(Stream input, Stream output, BamlLocalizationDictionary dictionary, LocBamlOptions options)
        {
            string commentFile = Path.ChangeExtension(options.Input, "loc");
            TextReader commentStream = null;           

            try
            {
                if (File.Exists(commentFile))
                {
                    commentStream = new StreamReader(commentFile);
                }

                // create a localizabilty resolver based on reflection
                BamlLocalizabilityByReflection localizabilityReflector =
                    new BamlLocalizabilityByReflection(options.Assemblies); 

                // create baml localizer
                BamlLocalizer mgr = new BamlLocalizer(
                    input,
                    localizabilityReflector,
                    commentStream
                    );

                // get the resources
                BamlLocalizationDictionary source = mgr.ExtractResources();
                BamlLocalizationDictionary translations = new BamlLocalizationDictionary();

                foreach (DictionaryEntry entry in dictionary)
                {
                    BamlLocalizableResourceKey key = (BamlLocalizableResourceKey) entry.Key;
                    // filter out unchanged items
                    if (!source.Contains(key)
                      || entry.Value == null
                      || source[key].Content != ((BamlLocalizableResource)entry.Value).Content)
                    {
                        translations.Add(key, (BamlLocalizableResource)entry.Value);
                    }
                }
                
                // update baml
                mgr.UpdateBaml(output, translations);
            }
            finally
            {
                if (commentStream != null)
                {
                    commentStream.Close();
                }
            }
        }

        private static void GenerateResourceStream(
                LocBamlOptions options,                     // options from the command line
                string resourceName,                        // the name of the .resources file
                IResourceReader reader,                     // the reader for the .resources
                IResourceWriter writer,                     // the writer for the output .resources
                TranslationDictionariesReader dictionaries  // the translations
            )
        {

            options.WriteLine(StringLoader.Get("GenerateResource", resourceName));
            // enumerate through each resource and generate it
            foreach(DictionaryEntry entry in reader)            
            {
                string name = entry.Key as string;                
				object resourceValue = null;
                                
                // See if it looks like a Baml resource
                if (BamlStream.IsResourceEntryBamlStream(name, entry.Value))
                {
		    Stream targetStream = null;
                    options.Write("    ");
                    options.Write(StringLoader.Get("GenerateBaml", name));

                    // grab the localizations available for this Baml
                    string bamlName = BamlStream.CombineBamlStreamName(resourceName, name);
                    BamlLocalizationDictionary localizations = dictionaries[bamlName];                    
                    if (localizations != null)
                    {
                        targetStream = new MemoryStream();
                        
                        // generate into a new Baml stream
                        GenerateBamlStream(
                            (Stream) entry.Value,
                            targetStream,
                            localizations,
                            options
                        );
                    }
                    options.WriteLine(StringLoader.Get("Done"));

		    // sets the generated object to be the generated baml stream
		    resourceValue = targetStream;
                }

		if (resourceValue == null)
                {
                    //
                    // The stream is not localized as Baml yet, so we will make a copy of this item into 
                    // the localized resources
                    //

		    // We will add the value as is if it is serializable. Otherwise, make a copy
		    resourceValue = entry.Value;

                    object[] serializableAttributes = resourceValue.GetType().GetCustomAttributes(typeof(SerializableAttribute), true);
                    if (serializableAttributes.Length == 0)
                    {
                        // The item returned from resource reader is not serializable
                        // If it is Stream, we can wrap all the values in a MemoryStream and 
                        // add to the resource. Otherwise, we had to skip this resource.
			Stream resourceStream = resourceValue as Stream;						
                        if (resourceStream != null)
                        {
			    Stream targetStream = new MemoryStream();
                            byte[] buffer = new byte[resourceStream.Length];
                            resourceStream.Read(buffer, 0, buffer.Length);
                            targetStream = new MemoryStream(buffer);
			    resourceValue = targetStream;
                        }                        
                    }                
                }

		if (resourceValue != null)
                {
			writer.AddResource(name, resourceValue);
                }
            }
        }

        private static void GenerateStandaloneResource(string fullPathName, Stream resourceStream)
        {
            // simply do a copy for the stream
            using (FileStream file = new FileStream(fullPathName, FileMode.Create, FileAccess.Write))
            {
                const int BUFFER_SIZE = 4096;
                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead = 1;
                while (bytesRead > 0)
                {
                     bytesRead = resourceStream.Read(buffer, 0, BUFFER_SIZE);
                     file.Write(buffer, 0, bytesRead);
                }                                                           
            }            
        }

        //--------------------------------------------------
        // The function follows Managed code parser
        // implementation. in the future, maybe they should 
        // share the same code
        //--------------------------------------------------
        private static void GenerateAssembly(LocBamlOptions options, TranslationDictionariesReader dictionaries)
        {
            // there are many names to be used when generating an assembly
            string sourceAssemblyFullName   = options.Input;                // source assembly full path 
            string outputAssemblyDir        = options.Output;               // output assembly directory
            string outputAssemblyLocalName  = GetOutputFileName(options);   // output assembly name
            string moduleLocalName          = GetAssemblyModuleLocalName(options, outputAssemblyLocalName); // the module name within the assmbly
                
            // get the source assembly
            Assembly srcAsm = Assembly.LoadFrom(sourceAssemblyFullName);

            // obtain the assembly name
            AssemblyName targetAssemblyNameObj = srcAsm.GetName();

            // store the culture info of the source assembly
            CultureInfo srcCultureInfo  = targetAssemblyNameObj.CultureInfo;
            
            // update it to use it for target assembly
            targetAssemblyNameObj.Name        = Path.GetFileNameWithoutExtension(outputAssemblyLocalName);
            targetAssemblyNameObj.CultureInfo = options.CultureInfo;

            // we get a assembly builder
            AssemblyBuilder targetAssemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(
                targetAssemblyNameObj,                  // name of the assembly
                AssemblyBuilderAccess.RunAndSave,       // access rights
                outputAssemblyDir                       // storage dir
                );            

            // we create a module builder for embeded resource modules
            ModuleBuilder moduleBuilder = targetAssemblyBuilder.DefineDynamicModule(
                moduleLocalName,
                outputAssemblyLocalName
                );

            options.WriteLine(StringLoader.Get("GenerateAssembly"));
                      
            // now for each resource in the assembly
            foreach (string resourceName in srcAsm.GetManifestResourceNames())
            {                
                // get the resource location for the resource
                ResourceLocation resourceLocation = srcAsm.GetManifestResourceInfo(resourceName).ResourceLocation;
                               
                // if this resource is in another assemlby, we will skip it
                if ((resourceLocation & ResourceLocation.ContainedInAnotherAssembly) != 0)
                {
                    continue;   // in resource assembly, we don't have resource that is contained in another assembly
                }

                // gets the neutral resource name, giving it the source culture info
                string neutralResourceName  = GetNeutralResModuleName(resourceName, srcCultureInfo);

                // gets the target resource name, by giving it the target culture info
                string targetResourceName   = GetCultureSpecificResourceName(neutralResourceName, options.CultureInfo);

                // resource stream              
                Stream resourceStream       = srcAsm.GetManifestResourceStream(resourceName);
                
                // see if it is a .resources
                if (neutralResourceName.ToLower(CultureInfo.InvariantCulture).EndsWith(".resources"))
                {                                   
                    // now we think we have resource stream 
                    // get the resource writer
                    IResourceWriter writer;
                    // check if it is a embeded assembly
                    if ((resourceLocation & ResourceLocation.Embedded) != 0)
                    {
                        // gets the resource writer from the module builder
                        writer = moduleBuilder.DefineResource(
                            targetResourceName,         // resource name
                            targetResourceName,         // resource description
                            ResourceAttributes.Public   // visibilty of this resource to other assembly
                            );
                    }                                
                    else
                    {
                        // it is a standalone resource, we get the resource writer from the assembly builder
                        writer =  targetAssemblyBuilder.DefineResource(
                            targetResourceName,         // resource name 
                            targetResourceName,         // description
                            targetResourceName,         // file name to save to   
                            ResourceAttributes.Public   // visibility of this resource to other assembly
                        );
                    }

                    // get the resource reader
                    IResourceReader reader = new ResourceReader(resourceStream);

                    // generate the resources
                    GenerateResourceStream(options, resourceName, reader, writer, dictionaries);

                    // we don't call writer.Generate() or writer.Close() here 
                    // because the AssemblyBuilder will call them when we call Save() on it.
                }
                else
                {
                    // else it is a stand alone untyped manifest resources.
                    string extension = Path.GetExtension(targetResourceName);                    

                    string fullFileName = Path.Combine(outputAssemblyDir, targetResourceName);
                    
                    // check if it is a .baml, case-insensitive
                    if (string.Compare(extension, ".baml", true, CultureInfo.InvariantCulture) == 0)
                    {
                        // try to localized the the baml
                        // find the resource dictionary
                        BamlLocalizationDictionary dictionary = dictionaries[resourceName];

                        // if it is null, just create an empty dictionary.
                        if (dictionary != null)                            
                        {
                            // it is a baml stream
                            using (Stream output = File.OpenWrite(fullFileName))
                            {
                                options.Write("    ");
                                options.WriteLine(StringLoader.Get("GenerateStandaloneBaml", fullFileName));
                                GenerateBamlStream(resourceStream, output, dictionary, options);
                                options.WriteLine(StringLoader.Get("Done"));
                            }
                        }
                        else
                        {
                            // can't find localization of it, just copy it
                            GenerateStandaloneResource( fullFileName, resourceStream);
                        }
                    }
                    else
                    {
                        // it is an untyped resource stream, just copy it
                        GenerateStandaloneResource( fullFileName, resourceStream);
                    }
    
                    // now add this resource file into the assembly
                    targetAssemblyBuilder.AddResourceFile(
                        targetResourceName,           // resource name
                        targetResourceName,           // file name
                        ResourceAttributes.Public     // visibility of the resource to other assembly
                    );
                    
                }  
            }

            // at the end, generate the assembly
            targetAssemblyBuilder.Save(outputAssemblyLocalName);
            options.WriteLine(StringLoader.Get("DoneGeneratingAssembly"));
        }


        //-----------------------------------------
        // private function dealing with naming 
        //-----------------------------------------

        // return the local output file name, i.e. without directory
        private static string GetOutputFileName(LocBamlOptions options)
        {
            string outputFileName;
            string inputFileName  = Path.GetFileName(options.Input);
            
            switch(options.InputType)
            {
                case FileType.BAML:
                {
                    return inputFileName;
                }
		case FileType.EXE:
		{
                     inputFileName = inputFileName.Remove(inputFileName.LastIndexOf('.')) + ".resources.dll";
			return inputFileName;
		}
                case FileType.DLL :
                {
                    return inputFileName;                    
                }
                case FileType.RESOURCES :
                {
                    // get the output file name
                    outputFileName        = inputFileName;
                    
                    // get to the last dot seperating filename and extension
                    int lastDot = outputFileName.LastIndexOf('.');   
                    int secondLastDot = outputFileName.LastIndexOf('.', lastDot - 1);
                    if (secondLastDot > 0)
                    {
                        string cultureName = outputFileName.Substring(secondLastDot + 1, lastDot - secondLastDot - 1);
                        if (LocBamlConst.IsValidCultureName(cultureName))
                        {
                            string extension = outputFileName.Substring(lastDot);
                            string frontPart = outputFileName.Substring(0, secondLastDot + 1);
                            outputFileName = frontPart + options.CultureInfo.Name + extension;
                        }
                    }
                    return outputFileName;
                }
                default :
                {
                    throw new NotSupportedException();
                }
            }
        }

        private static string GetAssemblyModuleLocalName(LocBamlOptions options, string targetAssemblyName)
        {
            string moduleName;
            if (targetAssemblyName.ToLower(CultureInfo.InvariantCulture).EndsWith(".resources.dll"))                
            {
                // we create the satellite assembly name
                moduleName = string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}.{1}.{2}", 
                    targetAssemblyName.Substring(0, targetAssemblyName.Length - ".resources.dll".Length),
                    options.CultureInfo.Name,
                    "resources.dll"
                    );               
            }
            else
            {
                moduleName = targetAssemblyName;
            }
            return moduleName;
        }



        // return the neutral resource name
        private static string GetNeutralResModuleName(string resourceName, CultureInfo cultureInfo)
        {
            if (cultureInfo.Equals(CultureInfo.InvariantCulture))
            {
                return resourceName;
            }
            else
            {
                // if it is an satellite assembly, we need to strip out the culture name
                string normalizedName = resourceName.ToLower(CultureInfo.InvariantCulture);
                int end = normalizedName.LastIndexOf(".resources");

                if (end < 0)
                {
                    return resourceName;
                }

                int start = normalizedName.LastIndexOf('.', end - 1);

                if (start > 0 && end - start > 0)
                {
                    string cultureStr = resourceName.Substring( start + 1, end - start - 1);

                    if (string.Compare(cultureStr, cultureInfo.Name, true) == 0)
                    {
                        // it has the correct culture name, so we can take it out
                        return resourceName.Remove(start, end - start);
                    }
                }        
                return resourceName;                       
            }
        }

        private static string GetCultureSpecificResourceName(string neutralResourceName, CultureInfo culture)
        {
            // gets the extension
            string extension    = Path.GetExtension(neutralResourceName);

            // swap in culture name
            string cultureName  = Path.ChangeExtension(neutralResourceName, culture.Name);

            // return the new name with the same extension
            return cultureName + extension;
        }
    }   
}


<|start_filename|>Graphics/AITCodec/cpp/ycbcrpixelformatconverter.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Declaration of YCbCrPixelFormatConverter
//----------------------------------------------------------------------------------------
#pragma once

extern const GUID CLSID_YCbCrPixelFormatConverter;

class YCbCrPixelFormatConverter : public BasePixelFormatConverter
{
public:
    YCbCrPixelFormatConverter();

    STDMETHOD(CanConvert)( 
        /* [in] */ REFWICPixelFormatGUID srcPixelFormat,
        /* [in] */ REFWICPixelFormatGUID dstPixelFormat,
        /* [out] */ BOOL *pfCanConvert);   

    STDMETHOD(CopyPixels)( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels);

    //Additional Functions
private :
    HRESULT ConvertYCbCrToRgb( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels);
    HRESULT ConvertRgbToYCbCr( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels);
};

<|start_filename|>Tools/BamlReflector/BamlTools/OldBamlDisassembler.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace BamlTools
{
    public class OldBamlDisassembler
    {
        const int LineLength = 16;    // hexbyte length
        static Type _formatVersionType = typeof(MockFormatVersion);

        BamlBinaryReader _reader;
        bool _showAddresses;
        bool _showRecordNumbers;
        bool _showDebugRecords;
        bool _showTableRecords;

        int _recordNumber;
        Dictionary<int, string> _attributeIdMap;

        enum TextType { Record, Size, Data, String, BrokenString };

        public struct TextLineSections
        {
            public string addrStr;
            public string hexStr;
            public string meaningStr;

            public TextLineSections(string pos, string hex, string meaning)
            {
                addrStr = pos;
                hexStr = hex;
                meaningStr = meaning;
            }

            public TextLineSections(long pos, byte[] hex, string meaning)
            {
                addrStr = string.Format("{0:x5}: ", pos);
                hexStr = FormatHexBytes(hex);
                meaningStr = meaning;
            }
        };

        public OldBamlDisassembler(Stream stream)
        {
            _reader = new BamlBinaryReader(stream);
            _attributeIdMap = new Dictionary<int, string>();
        }

        public string DasmOneBigString()
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                foreach (string line in GetLines())
                {
                    sb.AppendLine(line);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.ToString());
            }
            return sb.ToString();
        }

        public IEnumerable<String> GetLines()
        {
            foreach (string line in DumpVersionHeader())
            {
                yield return line;
            }

            yield return "";   // blank line;

            while (!Done())
            {
                foreach (string line in DumpRecord())
                {
                    yield return line;
                }
            }
        }

        public Type FormatVersionType
        {
            get { return _formatVersionType; }
        }

        public bool ShowAddresses
        {
            get { return _showAddresses; }
            set { _showAddresses = value; }
        }

        public bool ShowRecordNumbers
        {
            get { return _showRecordNumbers; }
            set { _showRecordNumbers = value; }
        }

        public bool ShowDebugRecords
        {
            get { return _showDebugRecords; }
            set { _showDebugRecords = value; }
        }

        public bool ShowTableRecords
        {
            get { return _showTableRecords; }
            set { _showTableRecords = value; }
        }

        public long Position
        {
            get { return _reader.BaseStream.Position; }
            set { _reader.BaseStream.Position = value; }
        }

        public long Length
        {
            get { return _reader.BaseStream.Length; }
        }

        public bool Done()
        {
            return (Position >= Length - 1);
        }

        public IEnumerable<string> DumpVersionHeader()
        {
            TextLineSections[] textSections;

            ReadFormatVersion(out textSections);
            foreach (string line in OutputTextLines(textSections, TextType.Data))
            {
                yield return line;
            }
        }

        public IEnumerable<string> DumpRecord()
        {
            _recordNumber += 1;
            foreach (string line in DefaultDumpRecord())
            {
                yield return line;
            }
            yield return ""; // blank line seperating records.
        }

        public IEnumerable<string> DefaultDumpRecord()
        {
            BamlRecord record;
            BamlRecordType recordType;
            int variableSize = 0;
            TextLineSections text;
            TextLineSections[] textList;

            recordType = ReadRecordType(out text);
            yield return OutputTextLine(text, TextType.Record);

            long startPosition = Position;

            // If we read a bad Record type, dump a few more bytes to help debug.
            if ((int)recordType >= (int)BamlRecordType.LastRecordType
                || null == StaticBamlRecords.GetRecord(recordType))
            {
                byte[] bytes = _reader.ReadBytes(64);
                textList = CutIntoLines(startPosition, bytes, "", "");
                foreach (string line in OutputTextLines(textList, TextType.Data))
                {
                    yield return line;
                }
                // Go ahead and throw the nullRef/outofBounds exception below...
            }

            record = StaticBamlRecords.GetRecord(recordType);
            Debug.Assert(record != null);

            if (record.IsVariableSize)
            {
                variableSize = Read7bitEncodedInt("size", out text);
                yield return OutputTextLine(text, TextType.Size);
            }

            for (int i = 0; i < record.Fields.Length; i++)
            {
                object val = ReadField(record.Fields[i], out textList);
                record.Fields[i].Value = val;

                if (textList.Length == 1)
                {
                    ImproveMeaning(record.Fields[i], textList);
                }
                TextType textType = TextType.Data;
                if (val is String)
                    textType = TextType.String;

                foreach (string line in OutputTextLines(textList, textType))
                {
                    yield return line;
                }
            }

            // this deals with the rare case of undefined padding
            // at the end of a record.  Only allowed for PropertyCustom
            if (record.IsVariableSize)
            {
                int processedSize = (int)(Position - startPosition);
                int extraPadding = variableSize - processedSize;
                if (extraPadding < 0)
                {
                    System.Diagnostics.Debugger.Break();
                }
                if (extraPadding > 0)
                {
                    long pos = Position;
                    byte[] bytes = _reader.ReadBytes(extraPadding);

                    string meaning = "?? custom";
                    if (recordType == BamlRecordType.PropertyCustom)
                    {
                        meaning = "Custom Data (variable size)";
                    }
                    textList = CutIntoLines(pos, bytes, meaning, "");
                    foreach (string line in OutputTextLines(textList, TextType.Data))
                    {
                        yield return line;
                    }
                }
            }

            ProcessRecord(record);
        }

        private BamlRecordType ReadRecordType(out TextLineSections text)
        {
            long pos = Position;
            int recordId = _reader.ReadByte();
            Position = pos;

            BamlRecordType val = (BamlRecordType)recordId;
            string meaning = string.Format("{0} [BamlRecord]", val.ToString());

            byte[] bytes = _reader.ReadBytes(1);
            text = new TextLineSections(pos, bytes, meaning);
            return val;
        }

        private object ReadField(BamlField field, out TextLineSections[] textList)
        {
            TextLineSections text = new TextLineSections("Err", "Err", "Err");
            object val = null;
            Type t = field.ClrType;

            textList = null;
            if (t == typeof(short))
            {
                val = (Int16)ReadIntType(2, field.Name, out text);
            }
            else if (t == typeof(int))
            {
                val = (Int32)ReadIntType(4, field.Name, out text);
            }
            else if (t == typeof(string))
            {
                val = (string)ReadString(field.Name, out textList);
            }
            else if (t == typeof(bool))
            {
                val = (bool)ReadBool(field.Name, out text);
            }
            else if (t == typeof(byte))
            {
                val = (byte)ReadIntType(1, field.Name, out text);
            }
            else if (t == FormatVersionType)
            {
                ReadFormatVersion(out textList);
            }
            else if (t == typeof(Int16[]))
            {
                val = (Int16[])ReadIntArrayType(field.Name, out textList);
            }
            else
            {
                throw new InvalidOperationException("Field Type not known");
            }
            if (null == textList)
            {
                textList = new TextLineSections[1];
                textList[0] = text;
            }

            return val;
        }

        private void ReadFormatVersion(out TextLineSections[] text)
        {
            TextLineSections UnicodeLength;
            TextLineSections[] Unicode;
            TextLineSections Version1;
            TextLineSections Version2;
            TextLineSections Version3;

            int strByteLength = (int)ReadIntType(4, "Unicode String Length(bytes)", out UnicodeLength);
            ReadByteLengthPrefixedDWordPaddedUnicodeString(strByteLength, out Unicode);
            ReadVersion("Reader Version", out Version1);
            ReadVersion("Update Version", out Version2);
            ReadVersion("Writer Version", out Version3);

            text = new TextLineSections[4 + Unicode.Length];
            text[0] = UnicodeLength;
            for (int i = 0; i < Unicode.Length; i++)
                text[1 + i] = Unicode[i];
            text[1 + Unicode.Length] = Version1;
            text[2 + Unicode.Length] = Version2;
            text[3 + Unicode.Length] = Version3;
            return;
        }

        private void ReadByteLengthPrefixedDWordPaddedUnicodeString(int strByteLength, out TextLineSections[] textList)
        {
            string val = "";

            long pos = Position;
            {
                BinaryReader tempReader = new BinaryReader(_reader.BaseStream, System.Text.Encoding.Unicode);
                char[] chars = tempReader.ReadChars(strByteLength / 2);
                val = new string(chars);
            }
            Position = pos;

            byte[] bytes = _reader.ReadBytes(strByteLength);
            string meaning = string.Format("\"{0}\"", val);

            textList = CutIntoLines(pos, bytes, meaning, "");
        }

        private void ReadVersion(string label, out TextLineSections text)
        {
            short val1;
            short val2;

            long pos = Position;
            val1 = _reader.ReadInt16();
            val2 = _reader.ReadInt16();
            Position = pos;

            byte[] bytes = _reader.ReadBytes(4);
            string meaning = string.Format("{0}={1}.{2}", label, val1.ToString(), val2.ToString());

            text = new TextLineSections(pos, bytes, meaning);
        }

        private long ReadIntType(int size, string label, out TextLineSections text)
        {
            long val = -1;


            string meaning = "";

            long pos = Position;
            switch (size)
            {
                case 1:
                    val = (sbyte)_reader.ReadSByte();
                    break;

                case 2:
                    val = (short)_reader.ReadInt16();
                    break;

                case 4:
                    val = (int)_reader.ReadInt32();
                    break;

                case 8:
                    val = (long)_reader.ReadInt64();
                    break;

                default:
                    throw new InvalidOperationException("Bad integral datatype size");
            }
            Position = pos;

            byte[] bytes = _reader.ReadBytes(size);

            sbyte val8 = -1;
            short val16 = -1;
            int val32 = -1;
            long val64 = -1;
            string formatString = (0 <= val && val < 10) ? "{0}={1}" : "{0}={1}({2})";
            switch (size)
            {
                case 1:
                    val8 = (sbyte)val;
                    meaning = string.Format(formatString, label, val8.ToString("x"), val8.ToString("d"));
                    break;

                case 2:
                    val16 = (short)val;
                    meaning = string.Format(formatString, label, val16.ToString("x"), val16.ToString("d"));
                    break;

                case 4:
                    val32 = (int)val;
                    meaning = string.Format(formatString, label, val32.ToString("x"), val32.ToString("d"));
                    break;

                case 8:
                    val64 = (long)val;
                    meaning = string.Format(formatString, label, val64.ToString("x"), val64.ToString("d"));
                    break;
            }

            text = new TextLineSections(pos, bytes, meaning);
            return val;
        }

        private bool ReadBool(string label, out TextLineSections text)
        {
            long pos = Position;
            bool val = _reader.ReadBoolean();
            Position = pos;

            byte[] bytes = _reader.ReadBytes(1);
            string meaning = string.Format("{0}={1}", label, val.ToString());

            text = new TextLineSections(pos, bytes, meaning);
            return val;
        }

        private int Read7bitEncodedInt(string label, out TextLineSections text)
        {
            long pos = Position;
            int val = _reader.Read7BitEncodedInt();
            int sizeOfEncoding = (int)(Position - pos);
            Position = pos;

            byte[] bytes = _reader.ReadBytes(sizeOfEncoding);
            string meaning = string.Format("{0}={1}", label, val.ToString());
            text = new TextLineSections(pos, bytes, meaning);
            return val;
        }

        private string ReadString(string label, out TextLineSections[] textList)
        {
            long pos = Position;
            string val = _reader.ReadString();
            int sizeInBytesOfString = (int)(Position - pos);
            Position = pos;

            // Can't use val.Length to compute number of bytes because multiple
            // bytes might make one Unicode character.
            // For Example:   the bytes 03 E2 97 8f make one Unicode char (The
            // Dot used in password boxes).
            byte[] bytes = _reader.ReadBytes(sizeInBytesOfString);
            if (sizeInBytesOfString <= LineLength)
            {
                string meaning = string.Format("{0}='{1}'", label, val);
                textList = new TextLineSections[1];
                textList[0] = new TextLineSections(pos, bytes, meaning);
            }
            else
            {
                TextLineSections[] textListCut = CutIntoLines(pos, bytes, val, label);
                textList = new TextLineSections[textListCut.Length + 1];
                Array.Copy(textListCut, textList, textListCut.Length);
                textList[textListCut.Length] = new TextLineSections(pos, new byte[0], val);
            }
            return val;
        }

        private short[] ReadIntArrayType(string label, out TextLineSections[] textList)
        {
            long pos = Position;

            short arrayLength = (short)_reader.ReadInt16();
            short[] array = new short[arrayLength];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = (short)_reader.ReadInt16();
            }
            int sizeOfArray = (int)(Position - pos);
            Position = pos;

            textList = new TextLineSections[arrayLength + 1];
            string meaning = string.Format("{0}={1}", label, array.Length);
            byte[] subBytes = _reader.ReadBytes(2);
            textList[0] = new TextLineSections(Position - 2, subBytes, meaning);

            for (int i = 0; i < array.Length; i++)
            {
                meaning = string.Format("Assembly ID[{0}]={1}", i, array[i]);
                subBytes = _reader.ReadBytes(2);
                textList[i + 1] = new TextLineSections(Position - 2, subBytes, meaning);
            }
            return array;
        }


        // OUTPUT methods.


        private string OutputTextLine(TextLineSections text, TextType textType)
        {
            string outputLine = String.Empty;
            if (ShowRecordNumbers)
            {
                string numString = String.Format("#{0:d3}: ", _recordNumber);
                if (textType == TextType.Record)
                {
                    outputLine += numString;
                }
                else
                {
                    outputLine += FormatPadToColumn(numString.Length, 0);
                }
            }
            if (ShowAddresses)
            {
                outputLine += text.addrStr;
            }
            outputLine += string.Format(" {0}", text.hexStr);

            int column = 0;
            if (outputLine.Length < 40)
                column = 40;
            else
                column = 60;
            outputLine += this.FormatPadToColumn(column, outputLine.Length);

            outputLine += text.meaningStr;

            return outputLine;
        }

        private IEnumerable<string> OutputTextLines(TextLineSections[] textList, TextType textType)
        {
            foreach (TextLineSections text in textList)
            {
                yield return OutputTextLine(text, textType);
            }
        }

        // Output a long block of bytes possibly over several lines.
        // If "label" is non-null then there is a header line of output.
        // If "val" is non-null then the byte block has a parallel "string" version.
        private TextLineSections[] CutIntoLines(long position, byte[] bytes, string val, string label)
        {
            TextLineSections[] textList;

            bool hasLabel = (label != null && label.Length > 0);
            bool hasString = (val != null && val.Length > 0);

            // Output the first "header" line.
            // If there is a Lable then the header line is the string length
            //   and label text.
            // If there is a Lable but no string, then the bytes is not a string
            //   is the just a blob of bytes.
            int headerOffset = 0;
            int currentLine = 0;
            if (!hasLabel)
            {
                int lineCount = (bytes.Length + LineLength - 1) / LineLength;
                textList = new TextLineSections[lineCount];
            }
            else
            {
                int sizeOfHeader = 0;
                byte[] headerBytes = null;
                TextLineSections labelLine;

                if (!hasString)
                {
                    sizeOfHeader = (bytes.Length > LineLength) ? LineLength : bytes.Length;
                    headerBytes = SnipBytes(bytes, 0, LineLength);
                    labelLine = new TextLineSections(position, headerBytes, label);
                    headerOffset = sizeOfHeader;
                }
                else
                {
                    sizeOfHeader = ComputeLengthOf7bitEncodedLengthPrefix(bytes.Length);
                    headerBytes = SnipBytes(bytes, 0, sizeOfHeader);
                    int stringLength = val.Length;
                    string meaning = string.Format("{0}= string of length {1}({2})", label, stringLength.ToString("x2"), stringLength);
                    labelLine = new TextLineSections(position, headerBytes, meaning);
                    headerOffset = sizeOfHeader;
                }
                int lineCount = 1 + ((bytes.Length - sizeOfHeader) + LineLength - 1) / LineLength;
                textList = new TextLineSections[lineCount];
                textList[currentLine++] = labelLine;
            }

            // Output the middle "full length lines"
            int byteOffset = 0;
            int valOffset = 0;
            for (valOffset = 0; (byteOffset = valOffset + headerOffset) < bytes.Length - LineLength; valOffset += LineLength)
            {
                byte[] subBytes = SnipBytes(bytes, byteOffset, LineLength);
                string subText = "";
                if (hasString)
                {   // The unicode string may run short early.
                    int remainingVal = val.Length - valOffset;
                    if (remainingVal > 0)
                    {
                        int subValLen = (remainingVal < LineLength) ? remainingVal : LineLength;
                        char[] subChars = val.ToCharArray(valOffset, subValLen);
                        subText = new string(subChars);
                    }
                }
                // March 2010: removed the subStrings at the ends of the lines.  
                textList[currentLine++] = new TextLineSections(position + byteOffset, subBytes, /*subText*/String.Empty);
            }

            // output the last line.
            int remaining = bytes.Length - byteOffset;
            if (remaining > 0)
            {
                byte[] subBytes = SnipBytes(bytes, byteOffset, remaining);
                string subText = "";
                if (hasString)
                {
                    int remainingVal = val.Length - valOffset;
                    if (remainingVal > 0)
                    {
                        char[] subChars = val.ToCharArray(valOffset, remainingVal);
                        subText = new string(subChars);
                    }
                }
                // March 2010: removed the subStrings at the ends of the lines.  
                textList[currentLine++] = new TextLineSections(position + byteOffset, subBytes, /*subText*/String.Empty);
            }
            return textList;
        }

        private byte[] SnipBytes(byte[] src, int start, int count)
        {
            byte[] dest = new byte[count];
            for (int i = 0; i < count; i++)
                dest[i] = src[start + i];
            return dest;
        }

        // this function is passed the length of a buffer, including the
        // variable size length prefix.   Given that total length, how 
        // many bytes long is the length prefix.
        private int ComputeLengthOf7bitEncodedLengthPrefix(int length)
        {
            if (length <= 0x80)  // 0 to 7F have 1 byte headers 7F+1=0x80.
                return 1;
            if (length <= 0x4001) // 80 to 3FFF have 2 byte headers 3FFF+2=0x4001
                return 2;
            if (length < 0x200002) // 1FFFFF + 3 = 0x200002
                return 3;
            return 4;       // this could go bigger and bigger, but reasonable numbers...
        }

        private static string FormatHexBytes(byte[] bytes)
        {
            if (null == bytes || bytes.Length > 16 || bytes.Length < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            string outStr = "";

            if (bytes.Length == 16)
            {
                outStr += string.Format("{0} {1} {2} {3} {4} {5} {6} {7}",
                    bytes[0].ToString("x2"), bytes[1].ToString("x2"),
                    bytes[2].ToString("x2"), bytes[3].ToString("x2"),
                    bytes[4].ToString("x2"), bytes[5].ToString("x2"),
                    bytes[6].ToString("x2"), bytes[7].ToString("x2"));
                outStr += string.Format("  {0} {1} {2} {3} {4} {5} {6} {7}",
                    bytes[8].ToString("x2"), bytes[9].ToString("x2"),
                    bytes[10].ToString("x2"), bytes[11].ToString("x2"),
                    bytes[12].ToString("x2"), bytes[13].ToString("x2"),
                    bytes[14].ToString("x2"), bytes[15].ToString("x2"));
            }
            else
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    outStr += string.Format("{0} ", bytes[i].ToString("x2"));
                    if (7 == i % 8)
                        outStr += " ";
                }
            }

            return outStr;
        }

        private string FormatPadToColumn(int column, int strLength)
        {
            int diff = column - strLength;
            string padding = "";
            while (diff > 0)
            {
                if (diff >= 8)
                {
                    padding += "        ";
                    diff -= 8;
                }
                else if (diff >= 4)
                {
                    padding += "    ";
                    diff -= 4;
                }
                else if (diff >= 2)
                {
                    padding += "  ";
                    diff -= 2;
                }
                else if (diff >= 1)
                {
                    padding += " ";
                    diff -= 1;
                }
            }
            return padding;
        }

        private void ProcessRecord(BamlRecord record)
        {
            switch (record.Id)
            {
                case BamlRecordType.AttributeInfo:
                    ProcessAttributeInfo(record);
                    break;
            }
        }

        private void ProcessAttributeInfo(BamlRecord record)
        {
            System.Diagnostics.Debug.Assert(record.Fields[0].BamlFieldType == BamlFieldType.AttributeId);
            Int16 attrId = (Int16)record.Fields[0].Value;

            System.Diagnostics.Debug.Assert(record.Fields[3].BamlFieldType == BamlFieldType.Value);
            string strValue = (string)record.Fields[3].Value;

            _attributeIdMap[attrId] = strValue;
        }

        private void ImproveMeaning(BamlField field, TextLineSections[] textList)
        {
            string oldMeaning = textList[0].meaningStr;
            string strValue = null;
            switch (field.BamlFieldType)
            {
                case BamlFieldType.AttributeId:
                    Int16 attrId = (Int16)field.Value;
                    if (attrId < 0)
                    {
                        strValue = KnownProperties.Properties[-attrId].PropertyName;
                    }
                    else if (_attributeIdMap.ContainsKey(attrId))
                    {
                        strValue = _attributeIdMap[attrId];
                    }
                    break;
                case BamlFieldType.TypeId:
                case BamlFieldType.ConverterTypeId:
                    Int16 typeId = (Int16)field.Value;
                    if (typeId < 0)
                    {
                        strValue = KnownElements.Elements[-typeId].ShortName;
                    }
                    break;
                case BamlFieldType.AttributeUsage:
                    byte usage = (byte)field.Value;
                    switch (usage)
                    {
                        case 0: strValue = "Default"; break;
                        case 1: strValue = "XmlLang"; break;
                        case 2: strValue = "XmlSpace"; break;
                        case 3: strValue = "RuntimeName"; break;
                    }
                    break;
            }
            if (null != strValue)
            {
                textList[0].meaningStr = string.Format("{0}  <{1}>", oldMeaning, strValue);
            }
        }
    }

}


<|start_filename|>Data Binding/ValidateItemsInItemsControl/Customers.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;

namespace ValidateItemsInItemsControl
{
    public class Customers : ObservableCollection<Customer>
    {
        public Customers()
        {
            Add(new Customer());
        }
    }

    // Check whether the customer and service representative are in the
    // same area.
}

<|start_filename|>Windows/Wizard/WizardDialogBox.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Wizard
{
    public class WizardDialogBox : NavigationWindow
    {
        public WizardDialogBox()
        {
            InitializeComponent();

            // Launch the wizard
            var wizardLauncher = new WizardLauncher();
            wizardLauncher.WizardReturn += wizardLauncher_WizardReturn;
            Navigate(wizardLauncher);
        }

        public WizardData WizardData { get; private set; }

        private void wizardLauncher_WizardReturn(object sender, WizardReturnEventArgs e)
        {
            // Handle wizard return
            WizardData = e.Data as WizardData;
            if (DialogResult == null)
            {
                DialogResult = (e.Result == WizardResult.Finished);
            }
        }
    }
}

<|start_filename|>Input and Commands/KeyboardKey/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Input;

namespace KeyboardKey
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnKeyDownHandler(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                textBlock1.Text = "You Entered: " + textBox1.Text;
            }
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;
using GraphingCalculatorDemo.Parser;
using Microsoft.Win32;

namespace GraphingCalculatorDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window //IB: was Window
    {
        private const string AnswerKey = "ans";
        private readonly string _regSaveBase = Registry.CurrentUser.Name + @"\Software\GraphCalc\Settings";
        private DrawAxisHelper _axisHelper;
        private TextBox _focusedBox;
        private IExpression _lastAnswer;
        private string _lastRendered;
        private IExpression _memory;
        private Point _selectionStart;
        private bool _selectionStarted;
        private Trackball _trackball;
        private Viewport3D _viewport;

        public MainWindow()
        {
            _memory = null;
            _lastAnswer = new ConstantExpression(0.0);
            _trackball = null;
            _viewport = null;
            VariableExpression.Define(AnswerKey, 0.0);
            Focusable = true;
        }

        private string Buffer
        {
            get { return _focusedBox.Text; }
            set
            {
                _focusedBox.Text = value;
                _focusedBox.Focus();
                _focusedBox.Select(value.Length, 0);
            }
        }

        private string ScreenBuffer
        {
            get { return screenText.Text; }
            set
            {
                screenText.Text = value;
                screenText.ScrollToEnd();
            }
        }

        private void OnLoaded(object sender, EventArgs args)
        {
            immediate.Focus();
            _viewport = new Viewport3D();
            _trackball = new Trackball();
            _trackball.Servants.Add(_viewport);
            _trackball.Attach(screen);
            _trackball.Enabled = true;

            graphNone.Header = Settings.FunctionNone;
            graph.Header = Settings.Function;
            graph2D.Header = Settings.Function2D;
            graph3D.Header = Settings.Function3D;
            graphOptions.Header = Settings.Function;
            graphOptions2D.Header = Settings.Function2D;
            graphOptions3D.Header = Settings.Function3D;

            // Workaround for registry bug (key base must exist before getting values - else default won't work)
            Registry.SetValue(_regSaveBase, "Version", "GraphCalc v.1.0", RegistryValueKind.String);

            xMin.Text = (string) Registry.GetValue(_regSaveBase, Settings.XMinReg, Settings.XMinDefault);
            xMax.Text = (string) Registry.GetValue(_regSaveBase, Settings.XMaxReg, Settings.XMaxDefault);
            yMin.Text = (string) Registry.GetValue(_regSaveBase, Settings.YMinReg, Settings.YMinDefault);
            yMax.Text = (string) Registry.GetValue(_regSaveBase, Settings.YMaxReg, Settings.YMaxDefault);

            xMinLabel.Text = Settings.XMin;
            xMaxLabel.Text = Settings.XMax;
            yMinLabel.Text = Settings.YMin;
            yMaxLabel.Text = Settings.YMax;

            xMin2D.Text = (string) Registry.GetValue(_regSaveBase, Settings.XMin2DReg, Settings.XMin2DDefault);
            xMax2D.Text = (string) Registry.GetValue(_regSaveBase, Settings.XMax2DReg, Settings.XMax2DDefault);
            yMin2D.Text = (string) Registry.GetValue(_regSaveBase, Settings.YMin2DReg, Settings.YMin2DDefault);
            yMax2D.Text = (string) Registry.GetValue(_regSaveBase, Settings.YMax2DReg, Settings.YMax2DDefault);
            tMin2D.Text = (string) Registry.GetValue(_regSaveBase, Settings.Min2DReg, Settings.Min2DDefault);
            tMax2D.Text = (string) Registry.GetValue(_regSaveBase, Settings.Max2DReg, Settings.Max2DDefault);
            tStep2D.Text = (string) Registry.GetValue(_regSaveBase, Settings.Step2DReg, Settings.Step2DDefault);

            xMin2DLabel.Text = Settings.XMin2D;
            xMax2DLabel.Text = Settings.XMax2D;
            yMin2DLabel.Text = Settings.YMin2D;
            yMax2DLabel.Text = Settings.YMax2D;
            tMin2DLabel.Text = Settings.Min2D;
            tMax2DLabel.Text = Settings.Max2D;
            tStep2DLabel.Text = Settings.Step2D;

            uMin.Text = (string) Registry.GetValue(_regSaveBase, Settings.UMinReg, Settings.UMinDefault);
            uMax.Text = (string) Registry.GetValue(_regSaveBase, Settings.UMaxReg, Settings.UMaxDefault);
            uGrid.Text = (string) Registry.GetValue(_regSaveBase, Settings.UGridReg, Settings.UGridDefault);
            vMin.Text = (string) Registry.GetValue(_regSaveBase, Settings.VMinReg, Settings.VMinDefault);
            vMax.Text = (string) Registry.GetValue(_regSaveBase, Settings.VMaxReg, Settings.VMaxDefault);
            vGrid.Text = (string) Registry.GetValue(_regSaveBase, Settings.VGridReg, Settings.VGridDefault);

            uMinLabel.Text = Settings.UMin;
            uMaxLabel.Text = Settings.UMax;
            uGridLabel.Text = Settings.UGrid;
            vMinLabel.Text = Settings.VMin;
            vMaxLabel.Text = Settings.VMax;
            vGridLabel.Text = Settings.VGrid;

            y.Text = (string) Registry.GetValue(_regSaveBase, Settings.YReg, Settings.YDefault);
            xt.Text = (string) Registry.GetValue(_regSaveBase, Settings.XtReg, Settings.XtDefault);
            yt.Text = (string) Registry.GetValue(_regSaveBase, Settings.YtReg, Settings.YtDefault);
            fx.Text = (string) Registry.GetValue(_regSaveBase, Settings.FxReg, Settings.FxDefault);
            fy.Text = (string) Registry.GetValue(_regSaveBase, Settings.FyReg, Settings.FyDefault);
            fz.Text = (string) Registry.GetValue(_regSaveBase, Settings.FzReg, Settings.FzDefault);

            yLabel.Text = Settings.Y;
            xtLabel.Text = Settings.Xt;
            ytLabel.Text = Settings.Yt;
            fxLabel.Text = Settings.Fx;
            fyLabel.Text = Settings.Fy;
            fzLabel.Text = Settings.Fz;
        }

        private void WindowSizeChanged(object sender, SizeChangedEventArgs args)
        {
            if (screenCanvas.Visibility == Visibility.Visible)
            {
                switch (_lastRendered)
                {
                    case Settings.Function:
                        GraphScene(false);
                        break;

                    case Settings.Function2D:
                        GraphScene2D(false);
                        break;

                    case Settings.Function3D:
                        GraphScene3D(false);
                        break;
                }
            }
        }

        private void ShowFunctionNone(object sender, RoutedEventArgs args)
        {
            ShowScreenText();
        }

        private void ShowFunction(object sender, RoutedEventArgs args)
        {
            ShowFunction();
        }

        private void ShowFunction2D(object sender, RoutedEventArgs args)
        {
            ShowFunction2D();
        }

        private void ShowFunction3D(object sender, RoutedEventArgs args)
        {
            ShowFunction3D();
        }

        private void ShowOptions(object sender, RoutedEventArgs args)
        {
            ShowOptions();
        }

        private void ShowOptions2D(object sender, RoutedEventArgs args)
        {
            ShowOptions2D();
        }

        private void ShowOptions3D(object sender, RoutedEventArgs args)
        {
            ShowOptions3D();
        }

        private void Clear(object sender, RoutedEventArgs args)
        {
            if (Buffer == string.Empty)
            {
                screenText.Text = string.Empty;
            }
            Buffer = string.Empty;
        }

        private void Differentiate(object sender, RoutedEventArgs args)
        {
            ScreenBuffer += "> d/dx(" + Buffer.Trim() + ")\n";
            ShowScreenText();

            try
            {
                var exp = FunctionParser.Parse(Buffer);
                exp = exp.Differentiate("x").Simplify();
                ScreenBuffer += exp.ToString() + "\n";
                Buffer = string.Empty;
            }
            catch (FunctionParserException)
            {
                ScreenBuffer += "Error!\n";
                Buffer = string.Empty;
            }
        }

        private void ComputeAnswer(object sender, RoutedEventArgs args)
        {
            if (ComputeAnswer())
            {
                ScreenBuffer += _lastAnswer.ToString() + "\n";
                Buffer = string.Empty;
            }
        }

        private bool ComputeAnswer()
        {
            immediate.Focus();
            Buffer = Buffer.Trim();

            if (Buffer.Length == 0)
            {
                Buffer = AnswerKey;
            }

            // Print what we're about to evaluate
            ScreenBuffer += "> " + Buffer.Trim() + "\n";
            ShowScreenText();

            try
            {
                var exp = FunctionParser.Parse(Buffer);
                _lastAnswer = exp.Simplify();
                if (_lastAnswer is ConstantExpression)
                {
                    VariableExpression.Define(AnswerKey, ((ConstantExpression) _lastAnswer).Value);
                }
                return true;
            }
            catch (FunctionParserException)
            {
                ScreenBuffer += "Error!\n";
                _lastAnswer = new ConstantExpression(0);
                VariableExpression.Define(AnswerKey, 0.0);
                Buffer = string.Empty;
                return false;
            }
        }

        private void OnPreviewKeyDown(object sender, KeyEventArgs args)
        {
            switch (args.Key)
            {
                case Key.Enter:
                    if (immediate.IsFocused)
                    {
                        ComputeAnswer(sender, null);
                        args.Handled = true;
                    }
                    else if (function.Visibility == Visibility.Visible)
                    {
                        GraphScene(false);
                        args.Handled = true;
                    }
                    else if (functions2D.Visibility == Visibility.Visible)
                    {
                        GraphScene2D(false);
                        args.Handled = true;
                    }
                    else if (functions3D.Visibility == Visibility.Visible)
                    {
                        GraphScene3D(false);
                        args.Handled = true;
                    }
                    break;
                case Key.Escape:
                    Clear(sender, null);
                    args.Handled = true;
                    break;

                case Key.D2:
                    if ((args.KeyboardDevice.Modifiers & ModifierKeys.Control) != ModifierKeys.None)
                    {
                        AppendPow2(sender, null);
                    }
                    break;
            }
        }

        private void OnTextBoxGotFocus(object sender, RoutedEventArgs args)
        {
            if (sender.Equals(screenText))
            {
                immediate.Focus();
                args.Handled = true;
            }
            else
            {
                _focusedBox = (TextBox) sender;
            }
        }

        private void AppendText(string text)
        {
            if (text.Length == 0)
            {
                return;
            }
            if (Buffer.Length == 0)
            {
                if (text == "+" || text == "-" || text == "*" || text == "/")
                {
                    text = AnswerKey + text;
                }
            }
            Buffer += text;
        }

        #region Toggle what's displayed on the screen

        private void ShowScreenCanvas()
        {
            screenCanvas.Visibility = Visibility.Visible;
            screenText.Visibility = Visibility.Collapsed;
            function.Visibility = Visibility.Collapsed;
            options.Visibility = Visibility.Collapsed;
            functions2D.Visibility = Visibility.Collapsed;
            options2D.Visibility = Visibility.Collapsed;
            functions3D.Visibility = Visibility.Collapsed;
            options3D.Visibility = Visibility.Collapsed;
            immediate.Focus();
        }

        private void ShowScreenText()
        {
            screenCanvas.Visibility = Visibility.Collapsed;
            screenText.Visibility = Visibility.Visible;
            function.Visibility = Visibility.Collapsed;
            options.Visibility = Visibility.Collapsed;
            functions2D.Visibility = Visibility.Collapsed;
            options2D.Visibility = Visibility.Collapsed;
            functions3D.Visibility = Visibility.Collapsed;
            options3D.Visibility = Visibility.Collapsed;
        }

        private void ShowFunction()
        {
            screenCanvas.Visibility = Visibility.Collapsed;
            screenText.Visibility = Visibility.Collapsed;
            function.Visibility = Visibility.Visible;
            options.Visibility = Visibility.Collapsed;
            functions2D.Visibility = Visibility.Collapsed;
            options2D.Visibility = Visibility.Collapsed;
            functions3D.Visibility = Visibility.Collapsed;
            options3D.Visibility = Visibility.Collapsed;
        }

        private void ShowOptions()
        {
            screenCanvas.Visibility = Visibility.Collapsed;
            screenText.Visibility = Visibility.Collapsed;
            function.Visibility = Visibility.Collapsed;
            options.Visibility = Visibility.Visible;
            functions2D.Visibility = Visibility.Collapsed;
            options2D.Visibility = Visibility.Collapsed;
            functions3D.Visibility = Visibility.Collapsed;
            options3D.Visibility = Visibility.Collapsed;
        }

        private void ShowFunction2D()
        {
            screenCanvas.Visibility = Visibility.Collapsed;
            screenText.Visibility = Visibility.Collapsed;
            function.Visibility = Visibility.Collapsed;
            options.Visibility = Visibility.Collapsed;
            functions2D.Visibility = Visibility.Visible;
            options2D.Visibility = Visibility.Collapsed;
            functions3D.Visibility = Visibility.Collapsed;
            options3D.Visibility = Visibility.Collapsed;
        }

        private void ShowOptions2D()
        {
            screenCanvas.Visibility = Visibility.Collapsed;
            screenText.Visibility = Visibility.Collapsed;
            function.Visibility = Visibility.Collapsed;
            options.Visibility = Visibility.Collapsed;
            functions2D.Visibility = Visibility.Collapsed;
            options2D.Visibility = Visibility.Visible;
            functions3D.Visibility = Visibility.Collapsed;
            options3D.Visibility = Visibility.Collapsed;
        }

        private void ShowFunction3D()
        {
            screenCanvas.Visibility = Visibility.Collapsed;
            screenText.Visibility = Visibility.Collapsed;
            function.Visibility = Visibility.Collapsed;
            options.Visibility = Visibility.Collapsed;
            functions2D.Visibility = Visibility.Collapsed;
            options2D.Visibility = Visibility.Collapsed;
            functions3D.Visibility = Visibility.Visible;
            options3D.Visibility = Visibility.Collapsed;
        }

        private void ShowOptions3D()
        {
            screenCanvas.Visibility = Visibility.Collapsed;
            screenText.Visibility = Visibility.Collapsed;
            function.Visibility = Visibility.Collapsed;
            options.Visibility = Visibility.Collapsed;
            functions2D.Visibility = Visibility.Collapsed;
            options2D.Visibility = Visibility.Collapsed;
            functions3D.Visibility = Visibility.Collapsed;
            options3D.Visibility = Visibility.Visible;
        }

        #endregion

        #region Graphing options and validation

        private void ShowOptions(object sender, EventArgs args)
        {
            ShowOptions();
        }

        private void SaveOptions(object sender, EventArgs args)
        {
            try
            {
                ValidateOptions();
                ShowFunction();
            }
            catch (FunctionParserException ex)
            {
                var message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "\n" + ex.InnerException.Message;
                }
                MessageBox.Show(message);
            }
        }

        private void ValidateOptions()
        {
            ValidateOption(xMin.Text, Settings.XMinReg);
            ValidateOption(xMax.Text, Settings.XMaxReg);
            ValidateOption(yMin.Text, Settings.YMinReg);
            ValidateOption(yMax.Text, Settings.YMaxReg);

            if (XMax == XMin)
            {
                throw new InvalidExpressionException("\"" + Settings.XMin + "\" and \"" + Settings.XMax +
                                                     "\" cannot have the same value");
            }
            if (XMax < XMin)
            {
                throw new InvalidExpressionException("\"" + Settings.XMin + "\" must be less than \"" + Settings.XMax +
                                                     "\"");
            }
            if (YMax == YMin)
            {
                throw new InvalidExpressionException("\"" + Settings.YMin + "\" and \"" + Settings.YMax +
                                                     "\" cannot have the same value");
            }
            if (YMax < YMin)
            {
                throw new InvalidExpressionException("\"" + Settings.YMin + "\" must be less than \"" + Settings.YMax +
                                                     "\"");
            }
        }

        private void ResetOptions(object sender, EventArgs args)
        {
            xMin.Text = Settings.XMinDefault;
            xMax.Text = Settings.XMaxDefault;
            yMin.Text = Settings.YMinDefault;
            yMax.Text = Settings.YMaxDefault;
            ValidateOptions();
        }

        private void ShowOptions2D(object sender, EventArgs args)
        {
            ShowOptions2D();
        }

        private void SaveOptions2D(object sender, EventArgs args)
        {
            try
            {
                ValidateOptions2D();
                ShowFunction2D();
            }
            catch (FunctionParserException ex)
            {
                var message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "\n" + ex.InnerException.Message;
                }
                MessageBox.Show(message);
            }
        }

        private void ValidateOptions2D()
        {
            ValidateOption(xMin2D.Text, Settings.XMin2DReg);
            ValidateOption(xMax2D.Text, Settings.XMax2DReg);
            ValidateOption(yMin2D.Text, Settings.YMin2DReg);
            ValidateOption(yMax2D.Text, Settings.YMax2DReg);
            ValidateOption(tMin2D.Text, Settings.Min2DReg);
            ValidateOption(tMax2D.Text, Settings.Max2DReg);
            ValidateOption(tStep2D.Text, Settings.Step2DReg);

            if (XMax2D == XMin2D)
            {
                throw new InvalidExpressionException("\"" + Settings.XMin2D + "\" and \"" + Settings.XMax2D +
                                                     "\" cannot have the same value");
            }
            if (XMax2D < XMin2D)
            {
                throw new InvalidExpressionException("\"" + Settings.XMin2D + "\" must be less than \"" +
                                                     Settings.XMax2D + "\"");
            }
            if (YMax2D == YMin2D)
            {
                throw new InvalidExpressionException("\"" + Settings.YMin2D + "\" and \"" + Settings.YMax2D +
                                                     "\" cannot have the same value");
            }
            if (YMax2D < YMin2D)
            {
                throw new InvalidExpressionException("\"" + Settings.YMin2D + "\" must be less than \"" +
                                                     Settings.YMax2D + "\"");
            }
        }

        private void ResetOptions2D(object sender, EventArgs args)
        {
            xMin2D.Text = Settings.XMin2DDefault;
            xMax2D.Text = Settings.XMax2DDefault;
            yMin2D.Text = Settings.YMin2DDefault;
            yMax2D.Text = Settings.YMax2DDefault;
            tMin2D.Text = Settings.Min2DDefault;
            tMax2D.Text = Settings.Max2DDefault;
            tStep2D.Text = Settings.Step2DDefault;
            ValidateOptions2D();
        }

        private void ShowOptions3D(object sender, EventArgs args)
        {
            ShowOptions3D();
        }

        private void SaveOptions3D(object sender, EventArgs args)
        {
            try
            {
                ValidateOptions3D();
                ShowFunction3D();
            }
            catch (FunctionParserException ex)
            {
                var message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "\n" + ex.InnerException.Message;
                }
                MessageBox.Show(message);
            }
        }

        private void ValidateOptions3D()
        {
            ValidateOption(uMin.Text, Settings.UMinReg);
            ValidateOption(uMax.Text, Settings.UMaxReg);
            ValidateOption(uGrid.Text, Settings.UGridReg);
            ValidateOption(vMin.Text, Settings.VMinReg);
            ValidateOption(vMax.Text, Settings.VMaxReg);
            ValidateOption(vGrid.Text, Settings.VGridReg);

            if (UGrid <= 0)
            {
                throw new InvalidExpressionException("\"" + Settings.UGrid + "\" must be greater than 0");
            }
            if (VGrid <= 0)
            {
                throw new InvalidExpressionException("\"" + Settings.VGrid + "\" must be greater than 0");
            }
        }

        private void ResetOptions3D(object sender, EventArgs args)
        {
            uMin.Text = Settings.UMinDefault;
            uMax.Text = Settings.UMaxDefault;
            uGrid.Text = Settings.UGridDefault;
            vMin.Text = Settings.VMinDefault;
            vMax.Text = Settings.VMaxDefault;
            vGrid.Text = Settings.VGridDefault;
            ValidateOptions3D();
        }

        private void ValidateOption(string value, string registryName)
        {
            try
            {
                var exp = FunctionParser.Parse(value).Simplify();
                if (!(exp is ConstantExpression))
                {
                    throw new InvalidExpressionException("The input expression must be constant");
                }
                Registry.SetValue(_regSaveBase, registryName, value, RegistryValueKind.String);
            }
            catch (FunctionParserException ex)
            {
                throw new InvalidExpressionException("Cannot save value for \"" + registryName + "\"", ex);
            }
        }

        #endregion

        #region Immediate Input

        private void AppendSin(object sender, RoutedEventArgs args)
        {
            AppendText("sin");
        }

        private void AppendCos(object sender, RoutedEventArgs args)
        {
            AppendText("cos");
        }

        private void AppendTan(object sender, RoutedEventArgs args)
        {
            AppendText("tan");
        }

        private void AppendPow2(object sender, RoutedEventArgs args)
        {
            AppendText("^2");
        }

        private void AppendPow(object sender, RoutedEventArgs args)
        {
            AppendText("^");
        }

        private void AppendPi(object sender, RoutedEventArgs args)
        {
            AppendText("pi");
        }

        private void AppendE(object sender, RoutedEventArgs args)
        {
            AppendText("e");
        }

        private void AppendFoo(object sender, RoutedEventArgs args)
        {
            AppendText("foo");
        }

        private void AppendX(object sender, RoutedEventArgs args)
        {
            AppendText("x");
        }

        private void AppendT(object sender, RoutedEventArgs args)
        {
            AppendText("t");
        }

        private void AppendU(object sender, RoutedEventArgs args)
        {
            AppendText("u");
        }

        private void AppendV(object sender, RoutedEventArgs args)
        {
            AppendText("v");
        }

        private void Append0(object sender, RoutedEventArgs args)
        {
            AppendText("0");
        }

        private void Append1(object sender, RoutedEventArgs args)
        {
            AppendText("1");
        }

        private void Append2(object sender, RoutedEventArgs args)
        {
            AppendText("2");
        }

        private void Append3(object sender, RoutedEventArgs args)
        {
            AppendText("3");
        }

        private void Append4(object sender, RoutedEventArgs args)
        {
            AppendText("4");
        }

        private void Append5(object sender, RoutedEventArgs args)
        {
            AppendText("5");
        }

        private void Append6(object sender, RoutedEventArgs args)
        {
            AppendText("6");
        }

        private void Append7(object sender, RoutedEventArgs args)
        {
            AppendText("7");
        }

        private void Append8(object sender, RoutedEventArgs args)
        {
            AppendText("8");
        }

        private void Append9(object sender, RoutedEventArgs args)
        {
            AppendText("9");
        }

        private void AppendLParen(object sender, RoutedEventArgs args)
        {
            AppendText("(");
        }

        private void AppendRParen(object sender, RoutedEventArgs args)
        {
            AppendText(")");
        }

        private void AppendMult(object sender, RoutedEventArgs args)
        {
            AppendText("*");
        }

        private void AppendDiv(object sender, RoutedEventArgs args)
        {
            AppendText("/");
        }

        private void AppendAdd(object sender, RoutedEventArgs args)
        {
            AppendText("+");
        }

        private void AppendMinus(object sender, RoutedEventArgs args)
        {
            AppendText("-");
        }

        private void AppendDecimal(object sender, RoutedEventArgs args)
        {
            AppendText(".");
        }

        private void AppendNegate(object sender, RoutedEventArgs args)
        {
            if (Buffer[Buffer.Length - 1] != '-')
            {
                AppendText("-");
            }
            else
            {
                Buffer = Buffer.Substring(0, Buffer.Length - 1);
            }
        }

        private void AppendAns(object sender, RoutedEventArgs args)
        {
            AppendText(AnswerKey);
        }

        private void Off(object sender, RoutedEventArgs args)
        {
            Application.Current.Shutdown();
        }

        #endregion

        #region Memory Operations

        private void MemoryAppend(object sender, RoutedEventArgs args)
        {
            if (ComputeAnswer())
            {
                if (_lastAnswer is ConstantExpression)
                {
                    if (_memory == null)
                    {
                        _memory = _lastAnswer;
                    }
                    else
                    {
                        _memory = new AddExpression(_memory, _lastAnswer);
                        _memory = _memory.Simplify();
                    }
                    ScreenBuffer += _memory.ToString() + "\n";
                }
                else
                {
                    ScreenBuffer += "Cannot store this value in memory\n";
                }
            }
        }

        private void MemoryRecall(object sender, RoutedEventArgs args)
        {
            if (_memory != null)
            {
                AppendText(_memory.ToString());
            }
        }

        private void MemoryClear(object sender, RoutedEventArgs args)
        {
            _memory = null;
        }

        #endregion

        #region Fill in equation fields

        private void SpiralClicked(object sender, RoutedEventArgs args)
        {
            xt.Text = Settings.XtDefault;
            yt.Text = Settings.YtDefault;
            xMin2D.Text = Settings.XMin2DDefault;
            xMax2D.Text = Settings.XMax2DDefault;
            yMin2D.Text = Settings.YMin2DDefault;
            yMax2D.Text = Settings.YMax2DDefault;
            tMin2D.Text = Settings.Min2DDefault;
            tMax2D.Text = Settings.Max2DDefault;
            tStep2D.Text = Settings.Step2DDefault;
            ValidateOptions2D();
        }

        private void EllipseClicked(object sender, RoutedEventArgs args)
        {
            xt.Text = "4cos(t)";
            yt.Text = "3sin(t)";
            xMin2D.Text = Settings.XMin2DDefault;
            xMax2D.Text = Settings.XMax2DDefault;
            yMin2D.Text = Settings.YMin2DDefault;
            yMax2D.Text = Settings.YMax2DDefault;
            tMin2D.Text = "0";
            tMax2D.Text = "2pi";
            tStep2D.Text = "pi/16";
            ValidateOptions2D();
        }

        private void SphereClicked(object sender, RoutedEventArgs args)
        {
            fx.Text = Settings.FxDefault;
            fy.Text = Settings.FyDefault;
            fz.Text = Settings.FzDefault;
            uMin.Text = Settings.UMinDefault;
            uMax.Text = Settings.UMaxDefault;
            uGrid.Text = Settings.UGridDefault;
            vMin.Text = Settings.VMinDefault;
            vMax.Text = Settings.VMaxDefault;
            vGrid.Text = Settings.VGridDefault;
            ValidateOptions3D();
        }

        private void ConeClicked(object sender, RoutedEventArgs args)
        {
            fx.Text = ".6(1.5-v)cos(u)";
            fy.Text = "v";
            fz.Text = ".6(1.5-v)sin(-u)";
            uMin.Text = "-pi";
            uMax.Text = "pi";
            uGrid.Text = "24";
            vMin.Text = "0";
            vMax.Text = "1.5";
            vGrid.Text = "12";
            ValidateOptions3D();
        }

        private void TorusClicked(object sender, RoutedEventArgs args)
        {
            fx.Text = "-(1+.25cos(v))cos(u)";
            fy.Text = "(1+.25cos(v))sin(u)";
            fz.Text = "-.25sin(v)";
            uMin.Text = "-pi";
            uMax.Text = "pi";
            uGrid.Text = "48";
            vMin.Text = "0";
            vMax.Text = "2pi";
            vGrid.Text = "24";
            ValidateOptions3D();
        }

        #endregion

        #region Graphing logic

        private double CanvasWidth => ((FrameworkElement) screenCanvas.Parent).ActualWidth;

        private double CanvasHeight => ((FrameworkElement) screenCanvas.Parent).ActualHeight;

        private Size CanvasSize => ((UIElement) screenCanvas.Parent).RenderSize;

        private void Graph(object sender, RoutedEventArgs args)
        {
            try
            {
                if (function.Visibility == Visibility.Visible)
                {
                    GraphScene(false);
                    _lastRendered = Settings.Function;
                }
                else if (functions2D.Visibility == Visibility.Visible)
                {
                    GraphScene2D(false);
                    _lastRendered = Settings.Function2D;
                }
                else if (functions3D.Visibility == Visibility.Visible)
                {
                    GraphScene3D(false);
                    _lastRendered = Settings.Function3D;
                }
                else
                {
                    ScreenBuffer += "No active functions to graph\n";
                }
            }
            catch (FunctionParserException ex)
            {
                var message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "\n" + ex.InnerException.Message;
                }
                MessageBox.Show(message, "Failed to graph equation");
            }
        }

        private void GraphScene(bool legacy)
        {
            var exp = Parse(y.Text, Settings.Y, Settings.YReg);

            var width = CanvasWidth;
            var height = CanvasHeight;
            var offsetX = -XMin;
            var offsetY = YMax;
            var graphToCanvasX = width/(XMax - XMin);
            var graphToCanvasY = height/(YMax - YMin);

            var points = new PointCollection();
            for (var x = XMin; x < XMax; x += 1/graphToCanvasX)
            {
                VariableExpression.Define("x", x);

                // Translate the origin based on the max/min parameters (y axis is flipped), then scale to canvas.
                var xCanvas = (x + offsetX)*graphToCanvasX;
                var yCanvas = (offsetY - exp.Evaluate())*graphToCanvasY;

                points.Add(ClampedPoint(xCanvas, yCanvas));
            }
            VariableExpression.Undefine("x");

            screenCanvas.Children.Clear();
            _axisHelper = new DrawAxisHelper(screenCanvas, CanvasSize);
            _axisHelper.DrawAxes(XMin, XMax, YMin, YMax);


            var graphLine = new Polyline
            {
                Stroke = Brushes.Black,
                StrokeThickness = 1,
                Points = points
            };

            screenCanvas.Children.Add(graphLine);

            ShowScreenCanvas();
        }

        private void GraphScene2D(bool legacy)
        {
            var xExp = Parse(xt.Text, Settings.Xt, Settings.XtReg);
            var yExp = Parse(yt.Text, Settings.Yt, Settings.YtReg);

            var width = CanvasWidth;
            var height = CanvasHeight;
            var graphToCanvasX = width/(XMax2D - XMin2D);
            var graphToCanvasY = height/(YMax2D - YMin2D);

            // distance from origin of graph to origin of canvas
            var offsetX = -XMin2D;
            var offsetY = YMax2D;

            var points = new PointCollection();
            for (var t = Min2D; t <= Max2D + 0.000001; t += Step2D)
            {
                VariableExpression.Define("t", t);
                var xGraph = xExp.Evaluate();
                var yGraph = yExp.Evaluate();

                // Translate the origin based on the max/min parameters (y axis is flipped), then scale to canvas.
                var xCanvas = (xGraph + offsetX)*graphToCanvasX;
                var yCanvas = (offsetY - yGraph)*graphToCanvasY;

                points.Add(ClampedPoint(xCanvas, yCanvas));
            }
            VariableExpression.Undefine("t");

            screenCanvas.Children.Clear();
            _axisHelper = new DrawAxisHelper(screenCanvas, CanvasSize);
            _axisHelper.DrawAxes(XMin2D, XMax2D, YMin2D, YMax2D);


            var polyLine = new Polyline
            {
                Stroke = Brushes.Black,
                StrokeThickness = 1,
                Points = points
            };
            screenCanvas.Children.Add(polyLine);

            ShowScreenCanvas();
        }

        private Point ClampedPoint(double x, double y)
        {
            if (double.IsPositiveInfinity(x) || x > CanvasWidth*2)
            {
                x = CanvasWidth*2;
            }
            else if (double.IsNegativeInfinity(x) || x < -CanvasWidth)
            {
                x = -CanvasWidth;
            }
            else if (double.IsNaN(x))
            {
                x = -CanvasWidth;
            }
            if (double.IsPositiveInfinity(y) || y > CanvasHeight*2)
            {
                y = CanvasHeight*2;
            }
            else if (double.IsNegativeInfinity(y) || y < -CanvasHeight)
            {
                y = -CanvasHeight;
            }
            else if (double.IsNaN(x))
            {
                y = -CanvasHeight;
            }
            return new Point(x, y);
        }

        private void GraphScene3D(bool legacy)
        {
            // We do this so we can get good error information.
            // The values return by these calls are ignored.
            Parse(fx.Text, Settings.Fx, Settings.FxReg);
            Parse(fy.Text, Settings.Fy, Settings.FyReg);
            Parse(fz.Text, Settings.Fz, Settings.FzReg);

            var camera = new PerspectiveCamera
            {
                Position = new Point3D(0, 0, 5),
                LookDirection = new Vector3D(0, 0, -2),
                UpDirection = new Vector3D(0, 1, 0),
                NearPlaneDistance = 1,
                FarPlaneDistance = 100,
                FieldOfView = 45
            };

            Model3DGroup group = null;

            if (legacy)
            {
                var model = new FunctionWireframeModel(fx.Text, fy.Text, fz.Text, UMin, UMax, VMin, VMax);
                group = model.CreateWireframeModel(UGrid + 1, VGrid + 1);
            }
            else
            {
                group = new Model3DGroup();
                var mesh = new FunctionMesh(fx.Text, fy.Text, fz.Text, UMin, UMax, VMin, VMax);
                group.Children.Add(new GeometryModel3D(mesh.CreateMesh(UGrid + 1, VGrid + 1),
                    new DiffuseMaterial(Brushes.Blue)));
                group.Children.Add(new DirectionalLight(Colors.White, new Vector3D(-1, -1, -1)));
            }


            // Should draw axis here.

            // Save the transform added by the trackball;            
            if (_viewport.Children.Count > 0)
            {
                group.Transform = ((Model3DGroup) ((ModelVisual3D) _viewport.Children[0]).Content).Transform;
            }

            //<newcode>
            var sceneVisual = new ModelVisual3D {Content = @group};
            _viewport.Children.Clear();
            _viewport.Children.Add(sceneVisual);
            //</newcode>


            //viewport.Models = group;
            _viewport.Camera = camera;
            _viewport.Width = CanvasWidth;
            _viewport.Height = CanvasHeight;
            _viewport.ClipToBounds = true;

            screenCanvas.Children.Clear();
            screenCanvas.Children.Add(_viewport);
            ShowScreenCanvas();
        }

        private IExpression Parse(string equation, string labelName, string registryName)
        {
            try
            {
                var exp = FunctionParser.Parse(equation);
                Registry.SetValue(_regSaveBase, registryName, equation, RegistryValueKind.String);
                return exp;
            }
            catch (FunctionParserException ex)
            {
                throw new InvalidExpressionException("Error in equation: \"" + labelName + "\"", ex);
            }
        }

        #endregion

        #region Options

        // These will be verified by the options tab before the property is accessed in real code
        // An exception should never be thrown

        private double XMin
        {
            get
            {
                var exp = FunctionParser.Parse(xMin.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double XMax
        {
            get
            {
                var exp = FunctionParser.Parse(xMax.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double YMin
        {
            get
            {
                var exp = FunctionParser.Parse(yMin.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double YMax
        {
            get
            {
                var exp = FunctionParser.Parse(yMax.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        #endregion

        #region Options 2D

        // These will be verified by the options tab before the property is accessed in real code
        // An exception should never be thrown

        private double XMin2D
        {
            get
            {
                var exp = FunctionParser.Parse(xMin2D.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double XMax2D
        {
            get
            {
                var exp = FunctionParser.Parse(xMax2D.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double YMin2D
        {
            get
            {
                var exp = FunctionParser.Parse(yMin2D.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double YMax2D
        {
            get
            {
                var exp = FunctionParser.Parse(yMax2D.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double Min2D
        {
            get
            {
                var exp = FunctionParser.Parse(tMin2D.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double Max2D
        {
            get
            {
                var exp = FunctionParser.Parse(tMax2D.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double Step2D
        {
            get
            {
                var exp = FunctionParser.Parse(tStep2D.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        #endregion

        #region Options3D

        // These will be verified by the options tab before the property is accessed in real code
        // An exception should never be thrown

        private double UMin
        {
            get
            {
                var exp = FunctionParser.Parse(uMin.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double UMax
        {
            get
            {
                var exp = FunctionParser.Parse(uMax.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private int UGrid
        {
            get
            {
                var exp = FunctionParser.Parse(uGrid.Text).Simplify();
                return (int) ((ConstantExpression) exp).Value;
            }
        }

        private double VMin
        {
            get
            {
                var exp = FunctionParser.Parse(vMin.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private double VMax
        {
            get
            {
                var exp = FunctionParser.Parse(vMax.Text).Simplify();
                return ((ConstantExpression) exp).Value;
            }
        }

        private int VGrid
        {
            get
            {
                var exp = FunctionParser.Parse(vGrid.Text).Simplify();
                return (int) ((ConstantExpression) exp).Value;
            }
        }

        #endregion

        #region Selection/Zoom logic

        private void OnCanvasClickStart(object sender, MouseButtonEventArgs args)
        {
            switch (_lastRendered)
            {
                case Settings.Function:
                case Settings.Function2D:
                    _selectionStarted = true;
                    _selectionStart = args.GetPosition(screenCanvas);
                    selection.Width = 0;
                    selection.Height = 0;
                    selection.Visibility = Visibility.Visible;
                    break;

                case Settings.Function3D:
                    break;
            }
        }

        private void OnCanvasClickFinish(object sender, MouseButtonEventArgs args)
        {
            if (_selectionStarted)
            {
                var zoomIn = new Rect(_selectionStart, args.GetPosition(screenCanvas));
                selection.Visibility = Visibility.Collapsed;
                if (zoomIn.Width <= 1 || zoomIn.Height <= 1)
                {
                    return;
                }
                if (_lastRendered == Settings.Function)
                {
                    ZoomViewportTo(zoomIn);
                }
                else if (_lastRendered == Settings.Function2D)
                {
                    ZoomViewport2DTo(zoomIn);
                }
                _selectionStarted = false;
            }
        }

        private void OnCanvasMouseMove(object sender, MouseEventArgs args)
        {
            if (_selectionStarted)
            {
                var rect = new Rect(_selectionStart, args.GetPosition(screenCanvas));
                selection.RenderTransform = new TranslateTransform(rect.X, rect.Y);
                selection.Width = rect.Width;
                selection.Height = rect.Height;
            }
        }

        private void OnCanvasRightClick(object sender, MouseEventArgs args)
        {
            if (_selectionStarted)
            {
                _selectionStarted = false;
                selection.Visibility = Visibility.Collapsed;
            }
            else
            {
                var canvasSize = CanvasSize;
                var xBorder = canvasSize.Width/2;
                var yBorder = canvasSize.Height/2;

                var zoomOut = new Rect(-xBorder, -yBorder, xBorder*4, yBorder*4);
                switch (_lastRendered)
                {
                    case Settings.Function:
                        ZoomViewportTo(zoomOut);
                        break;
                    case Settings.Function2D:
                        ZoomViewport2DTo(zoomOut);
                        break;
                }
            }
        }

        private void ZoomViewportTo(Rect canvasSelection)
        {
            var canvasSize = CanvasSize;
            var selectionOffset = new Vector(canvasSelection.X, canvasSelection.Y);
            var selectionScale = new Vector(canvasSelection.Width/canvasSize.Width,
                canvasSelection.Height/canvasSize.Height);

            var graphSize = new Size(XMax - XMin, YMax - YMin);
            var canvasToGraphScale = new Vector(graphSize.Width/canvasSize.Width, graphSize.Height/canvasSize.Height);
            graphSize.Width *= selectionScale.X;
            graphSize.Height *= selectionScale.Y;
            var graphOffset = new Vector(selectionOffset.X*canvasToGraphScale.X, selectionOffset.Y*canvasToGraphScale.Y);
            var newViewport = new Rect(XMin + graphOffset.X, YMax - graphOffset.Y, graphSize.Width, graphSize.Height);
            xMin.Text = newViewport.Left.ToString(CultureInfo.InvariantCulture);
            xMax.Text = newViewport.Right.ToString(CultureInfo.InvariantCulture);
            yMax.Text = newViewport.Top.ToString(CultureInfo.InvariantCulture);
            yMin.Text = (newViewport.Top - graphSize.Height).ToString(CultureInfo.InvariantCulture);
            ValidateOptions();
            GraphScene(false);
        }

        private void ZoomViewport2DTo(Rect canvasSelection)
        {
            var canvasSize = CanvasSize;
            var selectionOffset = new Vector(canvasSelection.X, canvasSelection.Y);
            var selectionScale = new Vector(canvasSelection.Width/canvasSize.Width,
                canvasSelection.Height/canvasSize.Height);

            var graphSize = new Size(XMax2D - XMin2D, YMax2D - YMin2D);
            var canvasToGraphScale = new Vector(graphSize.Width/canvasSize.Width, graphSize.Height/canvasSize.Height);
            graphSize.Width *= selectionScale.X;
            graphSize.Height *= selectionScale.Y;
            var graphOffset = new Vector(selectionOffset.X*canvasToGraphScale.X, selectionOffset.Y*canvasToGraphScale.Y);
            var newViewport = new Rect(XMin2D + graphOffset.X, YMax2D - graphOffset.Y, graphSize.Width, graphSize.Height);
            xMin2D.Text = newViewport.Left.ToString(CultureInfo.InvariantCulture);
            xMax2D.Text = newViewport.Right.ToString(CultureInfo.InvariantCulture);
            yMax2D.Text = newViewport.Top.ToString(CultureInfo.InvariantCulture);
            yMin2D.Text = (newViewport.Top - graphSize.Height).ToString(CultureInfo.InvariantCulture);
            ValidateOptions2D();
            GraphScene2D(false);
        }

        #endregion
    }
}

<|start_filename|>Sample Applications/DataBindingDemo/User.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace DataBindingDemo
{
    public class User
    {
        public User(string name, int rating, DateTime memberSince)
        {
            Name = name;
            Rating = rating;
            MemberSince = memberSince;
        }

        #region Property Getters and Setters

        public string Name { get; }

        public int Rating { get; set; }

        public DateTime MemberSince { get; }

        #endregion
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/FocalLengthConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace PhotoViewerDemo
{
    /// <summary>
    ///     Converts a focal length from a decimal into a human-preferred string (e.g. 85 becomes 85mm)
    /// </summary>
    public class FocalLengthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return $"{value}mm";
            }
            return string.Empty;
        }

        public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}

<|start_filename|>Documents/Flow Content/TableRows/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Documents;

namespace TableRows
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public void AddRow(object sender, RoutedEventArgs e)
        {
            var row = new TableRow();
            trg1.Rows.Add(row);
            var para = new Paragraph();
            para.Inlines.Add("A new Row and Cell have been Added to the Table");
            var cell = new TableCell(para);
            row.Cells.Add(cell);
        }
    }
}

<|start_filename|>Elements/VisibiltyChanges/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace VisibiltyChanges
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ContentVis(object sender, RoutedEventArgs e)
        {
            tb1.Visibility = Visibility.Visible;
            txt1.Text = "Visibility is now set to Visible.";
        }

        private void ContentHid(object sender, RoutedEventArgs e)
        {
            tb1.Visibility = Visibility.Hidden;
            txt1.Text = "Visibility is now set to Hidden. Notice that the TextBox still occupies layout space.";
        }

        private void ContentCol(object sender, RoutedEventArgs e)
        {
            tb1.Visibility = Visibility.Collapsed;
            txt1.Text = "Visibility is now set to Collapsed. Notice that the TextBox no longer occupies layout space.";
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/KnownProperties.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//using System.Windows.Controls;
//using System.Windows.Media.Animation;
//using System.Windows.Media.Effects;
//using System.Windows.Controls.Primitives;
//using System.Windows;
//using System.Windows.Media;
//using System.Windows.Media.Media3D;
//using System.Windows.Documents;
//using System.Windows.Shapes;
//using System.Windows.Markup;
//using System.Windows.Input;
//using System.Windows.Data;
//using System.Windows.Navigation;
//using System.Xaml;
//using System.Reflection;
//using Microsoft.Windows.Themes;

namespace BamlTools
{
    class KnownProperty
    {
        public short BamlNumber { get; private set; }
        public string PropertyName { get; private set; }
        public string DeclaringTypeName { get; private set; }

        public KnownProperty(short bamlNumber, string declaringTypeName, string propertyName)
        {
            BamlNumber = bamlNumber;
            DeclaringTypeName = declaringTypeName;
            PropertyName = propertyName;
        }

        public string CreateMethodName
        {
            get { return "Create_BamlProperty_" + DeclaringTypeName + "_" + PropertyName; }
        }
    }

    class KnownProperties
    {
        public const short MaxDependencyProperty = 137;

        static public KnownProperty[] _knownProperties;

        static public KnownProperty[] Properties
        {
            get
            {
                if (_knownProperties == null)
                {
                    InitializeKnownProperties();
                }
                return _knownProperties;
            }
        }


        static private void InitializeKnownProperties()
        {
            _knownProperties = new KnownProperty[]
            {
                new KnownProperty(0, "ERROR 0", "ERROR 0"),
                new KnownProperty(1,  "AccessText",  "Text"),
                new KnownProperty(2,  "BeginStoryboard",  "Storyboard"),
                new KnownProperty(3,  "BitmapEffectGroup",  "Children"),
                new KnownProperty(4,  "Border",  "Background"),
                new KnownProperty(5,  "Border",  "BorderBrush"),
                new KnownProperty(6,  "Border",  "BorderThickness"),
                new KnownProperty(7,  "ButtonBase",  "Command"),
                new KnownProperty(8,  "ButtonBase",  "CommandParameter"),
                new KnownProperty(9,  "ButtonBase",  "CommandTarget"),
                new KnownProperty(10,  "ButtonBase",  "IsPressed"),
                new KnownProperty(11,  "ColumnDefinition",  "MaxWidth"),
                new KnownProperty(12,  "ColumnDefinition",  "MinWidth"),
                new KnownProperty(13,  "ColumnDefinition",  "Width"),
                new KnownProperty(14,  "ContentControl",  "Content"),
                new KnownProperty(15,  "ContentControl",  "ContentTemplate"),
                new KnownProperty(16,  "ContentControl",  "ContentTemplateSelector"),
                new KnownProperty(17,  "ContentControl",  "HasContent"),  // readonly
                new KnownProperty(18,  "ContentElement",  "Focusable"),
                new KnownProperty(19,  "ContentPresenter",  "Content"),
                new KnownProperty(20,  "ContentPresenter",  "ContentSource"),
                new KnownProperty(21,  "ContentPresenter",  "ContentTemplate"),
                new KnownProperty(22,  "ContentPresenter",  "ContentTemplateSelector"),
                new KnownProperty(23,  "ContentPresenter",  "RecognizesAccessKey"),
                new KnownProperty(24,  "Control",  "Background"),
                new KnownProperty(25,  "Control",  "BorderBrush"),
                new KnownProperty(26,  "Control",  "BorderThickness"),
                new KnownProperty(27,  "Control",  "FontFamily"),
                new KnownProperty(28,  "Control",  "FontSize"),
                new KnownProperty(29,  "Control",  "FontStretch"),
                new KnownProperty(30,  "Control",  "FontStyle"),
                new KnownProperty(31,  "Control",  "FontWeight"),
                new KnownProperty(32,  "Control",  "Foreground"),
                new KnownProperty(33,  "Control",  "HorizontalContentAlignment"),
                new KnownProperty(34,  "Control",  "IsTabStop"),
                new KnownProperty(35,  "Control",  "Padding"),
                new KnownProperty(36,  "Control",  "TabIndex"),
                new KnownProperty(37,  "Control",  "Template"),
                new KnownProperty(38,  "Control",  "VerticalContentAlignment"),
                new KnownProperty(39,  "DockPanel",  "Dock"),
                new KnownProperty(40,  "DockPanel",  "LastChildFill"),
                new KnownProperty(41,  "DocumentViewerBase",  "Document"),
                new KnownProperty(42,  "DrawingGroup",  "Children"),
                new KnownProperty(43,  "FlowDocumentReader",  "Document"),
                new KnownProperty(44,  "FlowDocumentScrollViewer",  "Document"),
                new KnownProperty(45,  "FrameworkContentElement",  "Style"),
                new KnownProperty(46,  "FrameworkElement",  "FlowDirection"),
                new KnownProperty(47,  "FrameworkElement",  "Height"),
                new KnownProperty(48,  "FrameworkElement",  "HorizontalAlignment"),
                new KnownProperty(49,  "FrameworkElement",  "Margin"),
                new KnownProperty(50,  "FrameworkElement",  "MaxHeight"),
                new KnownProperty(51,  "FrameworkElement",  "MaxWidth"),
                new KnownProperty(52,  "FrameworkElement",  "MinHeight"),
                new KnownProperty(53,  "FrameworkElement",  "MinWidth"),
                new KnownProperty(54,  "FrameworkElement",  "Name"),
                new KnownProperty(55,  "FrameworkElement",  "Style"),
                new KnownProperty(56,  "FrameworkElement",  "VerticalAlignment"),
                new KnownProperty(57,  "FrameworkElement",  "Width"),
                new KnownProperty(58,  "GeneralTransformGroup",  "Children"),
                new KnownProperty(59,  "GeometryGroup",  "Children"),
                new KnownProperty(60,  "GradientBrush",  "GradientStops"),
                new KnownProperty(61,  "Grid",  "Column"),
                new KnownProperty(62,  "Grid",  "ColumnSpan"),
                new KnownProperty(63,  "Grid",  "Row"),
                new KnownProperty(64,  "Grid",  "RowSpan"),
                new KnownProperty(65,  "GridViewColumn",  "Header"),
                new KnownProperty(66,  "HeaderedContentControl",  "HasHeader"),  // readonly 
                new KnownProperty(67,  "HeaderedContentControl",  "Header"),
                new KnownProperty(68,  "HeaderedContentControl",  "HeaderTemplate"),
                new KnownProperty(69,  "HeaderedContentControl",  "HeaderTemplateSelector"),
                new KnownProperty(70,  "HeaderedItemsControl",  "HasHeader"),  // readonly
                new KnownProperty(71,  "HeaderedItemsControl",  "Header"),
                new KnownProperty(72,  "HeaderedItemsControl",  "HeaderTemplate"),
                new KnownProperty(73,  "HeaderedItemsControl",  "HeaderTemplateSelector"),
                new KnownProperty(74,  "Hyperlink",  "NavigateUri"),
                new KnownProperty(75,  "Image",  "Source"),
                new KnownProperty(76,  "Image",  "Stretch"),
                new KnownProperty(77,  "ItemsControl",  "ItemContainerStyle"),
                new KnownProperty(78,  "ItemsControl",  "ItemContainerStyleSelector"),
                new KnownProperty(79,  "ItemsControl",  "ItemTemplate"),
                new KnownProperty(80,  "ItemsControl",  "ItemTemplateSelector"),
                new KnownProperty(81,  "ItemsControl",  "ItemsPanel"),
                new KnownProperty(82,  "ItemsControl",  "ItemsSource"),
                new KnownProperty(83,  "MaterialGroup",  "Children"),
                new KnownProperty(84,  "Model3DGroup",  "Children"),
                new KnownProperty(85,  "Page",  "Content"),
                new KnownProperty(86,  "Panel",  "Background"),
                new KnownProperty(87,  "Path",  "Data"),
                new KnownProperty(88,  "PathFigure",  "Segments"),
                new KnownProperty(89,  "PathGeometry",  "Figures"),
                new KnownProperty(90,  "Popup",  "Child"),
                new KnownProperty(91,  "Popup",  "IsOpen"),
                new KnownProperty(92,  "Popup",  "Placement"),
                new KnownProperty(93,  "Popup",  "PopupAnimation"),
                new KnownProperty(94,  "RowDefinition",  "Height"),
                new KnownProperty(95,  "RowDefinition",  "MaxHeight"),
                new KnownProperty(96,  "RowDefinition",  "MinHeight"),
                new KnownProperty(97,  "ScrollViewer",  "CanContentScroll"),
                new KnownProperty(98,  "ScrollViewer",  "HorizontalScrollBarVisibility"),
                new KnownProperty(99,  "ScrollViewer",  "VerticalScrollBarVisibility"),
                new KnownProperty(100,  "Shape",  "Fill"),
                new KnownProperty(101,  "Shape",  "Stroke"),
                new KnownProperty(102,  "Shape",  "StrokeThickness"),
                new KnownProperty(103,  "TextBlock",  "Background"),
                new KnownProperty(104,  "TextBlock",  "FontFamily"),
                new KnownProperty(105,  "TextBlock",  "FontSize"),
                new KnownProperty(106,  "TextBlock",  "FontStretch"),
                new KnownProperty(107,  "TextBlock",  "FontStyle"),
                new KnownProperty(108,  "TextBlock",  "FontWeight"),
                new KnownProperty(109,  "TextBlock",  "Foreground"),
                new KnownProperty(110,  "TextBlock",  "Text"),
                new KnownProperty(111,  "TextBlock",  "TextDecorations"),
                new KnownProperty(112,  "TextBlock",  "TextTrimming"),
                new KnownProperty(113,  "TextBlock",  "TextWrapping"),
                new KnownProperty(114,  "TextBox",  "Text"),
                new KnownProperty(115,  "TextElement",  "Background"),
                new KnownProperty(116,  "TextElement",  "FontFamily"),
                new KnownProperty(117,  "TextElement",  "FontSize"),
                new KnownProperty(118,  "TextElement",  "FontStretch"),
                new KnownProperty(119,  "TextElement",  "FontStyle"),
                new KnownProperty(120,  "TextElement",  "FontWeight"),
                new KnownProperty(121,  "TextElement",  "Foreground"),
                new KnownProperty(122,  "TimelineGroup",  "Children"),
                new KnownProperty(123,  "Track",  "IsDirectionReversed"),
                new KnownProperty(124,  "Track",  "Maximum"),
                new KnownProperty(125,  "Track",  "Minimum"),
                new KnownProperty(126,  "Track",  "Orientation"),
                new KnownProperty(127,  "Track",  "Value"),
                new KnownProperty(128,  "Track",  "ViewportSize"),
                new KnownProperty(129,  "Transform3DGroup",  "Children"),
                new KnownProperty(130,  "TransformGroup",  "Children"),
                new KnownProperty(131,  "UIElement",  "ClipToBounds"),
                new KnownProperty(132,  "UIElement",  "Focusable"),
                new KnownProperty(133,  "UIElement",  "IsEnabled"),
                new KnownProperty(134,  "UIElement",  "RenderTransform"),
                new KnownProperty(135,  "UIElement",  "Visibility"),
                new KnownProperty(136,  "Viewport3D",  "Children"),
                new KnownProperty(137,  "ERROR 137", "ERROR 137"),      // MaxDependencyProperty",
                new KnownProperty(138,  "AdornedElementPlaceholder",  "Child"),
                new KnownProperty(139,  "AdornerDecorator",  "Child"),
                new KnownProperty(140,  "AnchoredBlock",  "Blocks"),
                new KnownProperty(141,  "ArrayExtension",  "Items"),
                new KnownProperty(142,  "BlockUIContainer",  "Child"),
                new KnownProperty(143,  "Bold",  "Inlines"),
                new KnownProperty(144,  "BooleanAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(145,  "Border",  "Child"),
                new KnownProperty(146,  "BulletDecorator",  "Child"),
                new KnownProperty(147,  "Button",  "Content"),
                new KnownProperty(148,  "ButtonBase",  "Content"),
                new KnownProperty(149,  "ByteAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(150,  "Canvas",  "Children"),
                new KnownProperty(151,  "CharAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(152,  "CheckBox",  "Content"),
                new KnownProperty(153,  "ColorAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(154,  "ComboBox",  "Items"),
                new KnownProperty(155,  "ComboBoxItem",  "Content"),
                new KnownProperty(156,  "ContextMenu",  "Items"),
                new KnownProperty(157,  "ControlTemplate",  "VisualTree"),
                new KnownProperty(158,  "DataTemplate",  "VisualTree"),
                new KnownProperty(159,  "DataTrigger",  "Setters"),
                new KnownProperty(160,  "DecimalAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(161,  "Decorator",  "Child"),
                new KnownProperty(162,  "DockPanel",  "Children"),
                new KnownProperty(163,  "DocumentViewer",  "Document"),
                new KnownProperty(164,  "DoubleAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(165,  "EventTrigger",  "Actions"),
                new KnownProperty(166,  "Expander",  "Content"),
                new KnownProperty(167,  "Figure",  "Blocks"),
                new KnownProperty(168,  "FixedDocument",  "Pages"),
                new KnownProperty(169,  "FixedDocumentSequence",  "References"),
                new KnownProperty(170,  "FixedPage",  "Children"),
                new KnownProperty(171,  "Floater",  "Blocks"),
                new KnownProperty(172,  "FlowDocument",  "Blocks"),
                new KnownProperty(173,  "FlowDocumentPageViewer",  "Document"),
                new KnownProperty(174,  "FrameworkTemplate",  "VisualTree"),
                new KnownProperty(175,  "Grid",  "Children"),
                new KnownProperty(176,  "GridView",  "Columns"),
                new KnownProperty(177,  "GridViewColumnHeader",  "Content"),
                new KnownProperty(178,  "GroupBox",  "Content"),
                new KnownProperty(179,  "GroupItem",  "Content"),
                new KnownProperty(180,  "HeaderedContentControl",  "Content"),
                new KnownProperty(181,  "HeaderedItemsControl",  "Items"),
                new KnownProperty(182,  "HierarchicalDataTemplate",  "VisualTree"),
                new KnownProperty(183,  "Hyperlink",  "Inlines"),
                new KnownProperty(184,  "InkCanvas",  "Children"),
                new KnownProperty(185,  "InkPresenter",  "Child"),
                new KnownProperty(186,  "InlineUIContainer",  "Child"),
                new KnownProperty(187,  "InputScopeName",  "NameValue"),
                new KnownProperty(188,  "Int16AnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(189,  "Int32AnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(190,  "Int64AnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(191,  "Italic",  "Inlines"),
                new KnownProperty(192,  "ItemsControl",  "Items"),
                new KnownProperty(193,  "ItemsPanelTemplate",  "VisualTree"),
                new KnownProperty(194,  "Label",  "Content"),
                new KnownProperty(195,  "LinearGradientBrush",  "GradientStops"),
                new KnownProperty(196,  "List",  "ListItems"),
                new KnownProperty(197,  "ListBox",  "Items"),
                new KnownProperty(198,  "ListBoxItem",  "Content"),
                new KnownProperty(199,  "ListItem",  "Blocks"),
                new KnownProperty(200,  "ListView",  "Items"),
                new KnownProperty(201,  "ListViewItem",  "Content"),
                new KnownProperty(202,  "MatrixAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(203,  "Menu",  "Items"),
                new KnownProperty(204,  "MenuBase",  "Items"),
                new KnownProperty(205,  "MenuItem",  "Items"),
                new KnownProperty(206,  "ModelVisual3D",  "Children"),
                new KnownProperty(207,  "MultiBinding",  "Bindings"),
                new KnownProperty(208,  "MultiDataTrigger",  "Setters"),
                new KnownProperty(209,  "MultiTrigger",  "Setters"),
                new KnownProperty(210,  "ObjectAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(211,  "PageContent",  "Child"),
                new KnownProperty(212,  "PageFunctionBase",  "Content"),
                new KnownProperty(213,  "Panel",  "Children"),
                new KnownProperty(214,  "Paragraph",  "Inlines"),
                new KnownProperty(215,  "ParallelTimeline",  "Children"),
                new KnownProperty(216,  "Point3DAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(217,  "PointAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(218,  "PriorityBinding",  "Bindings"),
                new KnownProperty(219,  "QuaternionAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(220,  "RadialGradientBrush",  "GradientStops"),
                new KnownProperty(221,  "RadioButton",  "Content"),
                new KnownProperty(222,  "RectAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(223,  "RepeatButton",  "Content"),
                new KnownProperty(224,  "RichTextBox",  "Document"),
                new KnownProperty(225,  "Rotation3DAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(226,  "Run",  "Text"),
                new KnownProperty(227,  "ScrollViewer",  "Content"),
                new KnownProperty(228,  "Section",  "Blocks"),
                new KnownProperty(229,  "Selector",  "Items"),
                new KnownProperty(230,  "SingleAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(231,  "SizeAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(232,  "Span",  "Inlines"),
                new KnownProperty(233,  "StackPanel",  "Children"),
                new KnownProperty(234,  "StatusBar",  "Items"),
                new KnownProperty(235,  "StatusBarItem",  "Content"),
                new KnownProperty(236,  "Storyboard",  "Children"),
                new KnownProperty(237,  "StringAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(238,  "Style",  "Setters"),
                new KnownProperty(239,  "TabControl",  "Items"),
                new KnownProperty(240,  "TabItem",  "Content"),
                new KnownProperty(241,  "TabPanel",  "Children"),
                new KnownProperty(242,  "Table",  "RowGroups"),
                new KnownProperty(243,  "TableCell",  "Blocks"),
                new KnownProperty(244,  "TableRow",  "Cells"),
                new KnownProperty(245,  "TableRowGroup",  "Rows"),
                new KnownProperty(246,  "TextBlock",  "Inlines"),
                new KnownProperty(247,  "ThicknessAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(248,  "ToggleButton",  "Content"),
                new KnownProperty(249,  "ToolBar",  "Items"),
                new KnownProperty(250,  "ToolBarOverflowPanel",  "Children"),
                new KnownProperty(251,  "ToolBarPanel",  "Children"),
                new KnownProperty(252,  "ToolBarTray",  "ToolBars"),
                new KnownProperty(253,  "ToolTip",  "Content"),
                new KnownProperty(254,  "TreeView",  "Items"),
                new KnownProperty(255,  "TreeViewItem",  "Items"),
                new KnownProperty(256,  "Trigger",  "Setters"),
                new KnownProperty(257,  "Underline",  "Inlines"),
                new KnownProperty(258,  "UniformGrid",  "Children"),
                new KnownProperty(259,  "UserControl",  "Content"),
                new KnownProperty(260,  "Vector3DAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(261,  "VectorAnimationUsingKeyFrames",  "KeyFrames"),
                new KnownProperty(262,  "Viewbox",  "Child"),
                new KnownProperty(263,  "Viewport3DVisual",  "Children"),
                new KnownProperty(264,  "VirtualizingPanel",  "Children"),
                new KnownProperty(265,  "VirtualizingStackPanel",  "Children"),
                new KnownProperty(266,  "Window",  "Content"),
                new KnownProperty(267,  "WrapPanel",  "Children"),
                new KnownProperty(268,  "XmlDataProvider",  "XmlSerializer"),
            };
        }
    }
}


<|start_filename|>Graphics/AITCodec/cpp/aitencoder.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of AitEncoder
//----------------------------------------------------------------------------------------
#pragma once

#include "UnknownImpl.h"
extern const GUID CLSID_AitEncoder;

class AitFrameEncode : public BaseFrameEncode
{
public:
    AitFrameEncode(IWICImagingFactory *factory, IStream *pIStream, UINT num);
    ~AitFrameEncode();

    STDMETHOD(Commit)();
    STDMETHOD(GetMetadataQueryWriter)( 
        /* [out] */ IWICMetadataQueryWriter **ppIMetadataQueryWriter);

private:
};


class AitEncoder : public BaseEncoder
{
public:
    AitEncoder();
    ~AitEncoder();

    // IWICBitmapEncoder Interface
    STDMETHOD(Initialize)( 
        /* [in] */ IStream *pIStream,
        /* [in] */ WICBitmapEncoderCacheOption cacheOption);

    STDMETHOD(Commit)();

    STDMETHOD(GetMetadataQueryWriter)( 
        /* [out] */ IWICMetadataQueryWriter **ppIMetadataQueryWriter);

    //Additional function
    virtual BaseFrameEncode* CreateNewEncoderFrame(
    /* [in] */  IWICImagingFactory *pIFactory,
    /* [in] */ IStream *pIStream, 
    /* [in] */ UINT num);

private:   
};


<|start_filename|>Sample Applications/PhotoViewerDemo/ExposureTimeConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace PhotoViewerDemo
{
    /// <summary>
    ///     Converts an exposure time from a decimal (e.g. 0.0125) into a string (e.g. 1/80)
    /// </summary>
    public class ExposureTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

        {
            try
            {
                var exposure = (decimal) value;

                exposure = decimal.Round(1/exposure);
                return $"1/{exposure}";
            }
            catch (NullReferenceException)
            {
                return null;
            }
        }

        public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
        {
            var exposure = ((string) value).Substring(2);
            return (1/decimal.Parse(exposure));
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/basepixelformatconverter.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Declaration of BasePixelFormatConverter
//----------------------------------------------------------------------------------------
#pragma once

#include "UnknownImpl.h"

class BasePixelFormatConverter : public IWICFormatConverter
{
public:
    BasePixelFormatConverter();


    // IUnknown Interface
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv);
    STDMETHOD_(ULONG, AddRef)();
    STDMETHOD_(ULONG, Release)();


    // IWICFormatConverter Interface
    STDMETHOD(Initialize)( 
        /* [in] */ IWICBitmapSource *pISource,
        /* [in] */ REFWICPixelFormatGUID dstFormat,
        /* [in] */ WICBitmapDitherType dither,
        /* [in] */ IWICPalette *pIPalette,
        /* [in] */ double alphaThresholdPercent,
        /* [in] */ WICBitmapPaletteType paletteTranslate);

    STDMETHOD(CanConvert)( 
        /* [in] */ REFWICPixelFormatGUID srcPixelFormat,
        /* [in] */ REFWICPixelFormatGUID dstPixelFormat,
        /* [out] */ BOOL *pfCanConvert)=0;

    // IWICBitmapSource Interface
    STDMETHOD(GetSize)( 
        /* [out] */ UINT *puiWidth,
        /* [out] */ UINT *puiHeight);

    STDMETHOD(GetPixelFormat)( 
        /* [out] */ WICPixelFormatGUID *pPixelFormat);

    STDMETHOD(GetResolution)( 
        /* [out] */ double *pDpiX,
        /* [out] */ double *pDpiY);

    STDMETHOD(CopyPalette)( 
        /* [in] */ IWICPalette *pIPalette);

    STDMETHOD(CopyPixels)( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels)=0;

protected:
    IWICBitmapSource   *bitmapSource;
    WICPixelFormatGUID  destPixelFormat;
    GUID CLSID_This;

private:
    UnknownImpl         unknownImpl;
};



<|start_filename|>Application Management/ApplicationShutdown/App.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace ApplicationShutdown
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

        private void App_Exit(object sender, ExitEventArgs e)
        {
            Console.WriteLine(@"Exit");
        }
    }
}

<|start_filename|>Styles & Templates/AlternatingAppearanceOfItems/League.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;

namespace AlternatingAppearanceOfItems
{
    public class League
    {
        public League(string name)
        {
            Name = name;
            Divisions = new List<Division>();
        }

        public string Name { get; }
        public List<Division> Divisions { get; }
    }
}

<|start_filename|>Documents/Fixed Documents/DocumentMerge/RollupFixedPage.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Documents;

namespace DocumentMerge
{
    /// <summary>
    ///     Maintains data needed to generate a PageConent to be added to a RollUpDocument
    /// </summary>
    public class RollUpFixedPage
    {
        public RollUpFixedPage(FixedPage page)
        {
            FixedPage = page;
        }

        public RollUpFixedPage(Uri source, Uri baseUri)
        {
            Source = source;
            BaseUri = baseUri;
        }

        public FixedPage FixedPage { get; set; }
        public Uri BaseUri { get; set; }
        public Uri Source { get; set; }
    }
}

<|start_filename|>Animation/Per-FrameAnimation/ParticleEffects/ParticleEffectExamples.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Controls;

namespace PerFrameAnimation
{
    /// <summary>
    ///     Interaction logic for ParticleEffectExamples.xaml
    /// </summary>
    public partial class ParticleEffectExamples : Page
    {
    }
}

<|start_filename|>Input and Commands/HandlingEventOnCommand/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Input;

namespace HandlingEventOnCommand
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e)
        {
            string command, targetobj;
            command = ((RoutedCommand) e.Command).Name;
            targetobj = ((FrameworkElement) target).Name;
            MessageBox.Show("The " + command + " command has been invoked on target object " + targetobj);
        }

        private void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    }
}

<|start_filename|>Data Binding/ValidateItemsInItemsControl/Region.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace ValidateItemsInItemsControl
{
    public enum Region
    {
        Africa,
        Antartica,
        Australia,
        Asia,
        Europe,
        NorthAmerica,
        SouthAmerica
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/ColorRepresentation.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace PhotoViewerDemo
{
    public enum ColorRepresentation
    {
        SRgb,
        Uncalibrated
    }
}

<|start_filename|>Data Binding/Linq/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Linq
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly Tasks tasks = new Tasks();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var pri = int.Parse(((sender as ListBox).SelectedItem as ListBoxItem).Content.ToString());

            DataContext = from task in tasks
                where task.Priority == pri
                select task;
        }
    }
}

<|start_filename|>Data Binding/BindingToMethod/TempType.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace BindingToMethod
{
    public enum TempType
    {
        Celsius,
        Fahrenheit
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;

namespace StickyNotesDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private DispatcherTimer _alarmTimer;
        private DispatcherTimer _timerClock;
        private string[] _windowContents;

        public MainWindow()
        {
            InitializeComponent();
        }

        public int ArrayPos { get; set; }
        public object[] WindowArray { get; private set; }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            WindowArray = new object[100];

            _timerClock = new DispatcherTimer
            {
                Interval = new TimeSpan(0, 0, 4),
                IsEnabled = true
            };

            _alarmTimer = new DispatcherTimer
            {
                Interval = new TimeSpan(0, 30, 0),
                IsEnabled = true
            };
            _alarmTimer.Tick += AlarmTimer_Tick;

            LoadNotes();

            ContextMenuService.SetPlacement(AppWindow, PlacementMode.Bottom);

            AppWindow.MouseLeftButtonUp += MainWindow_MouseLeftButtonUp;
            AppWindow.Closing += MainWindow_Closing;
        }

        private void LoadNotes()
        {
            var count = 0;
            if (File.Exists("NotesFile"))
            {
                var fs = new FileStream("NotesFile", FileMode.Open);
                if (fs != null)
                {
                    int contentIndicator;
                    double height;
                    double width;
                    double x;
                    double y;
                    bool topmost;
                    int backgroundColorIndex;
                    int foregroundColorIndex;
                    DateTime alarmTime;
                    string loadRepeatNumber;

                    var reader = new StreamReader(fs);
                    var str = reader.ReadLine();
                    ExtractValues(out contentIndicator, str, out height, out width, out x, out y, out topmost,
                        out backgroundColorIndex,
                        out foregroundColorIndex, out alarmTime, out loadRepeatNumber);
                    AppWindow.Height = height;
                    AppWindow.Width = width;
                    AppWindow.Top = y;
                    AppWindow.Left = x;
                    AppWindow.Topmost = topmost;

                    count = contentIndicator;
                    for (var i = 0; i < count; i++)
                    {
                        var line = reader.ReadLine();

                        ExtractValues(out contentIndicator, line, out height, out width, out x, out y, out topmost,
                            out backgroundColorIndex, out foregroundColorIndex, out alarmTime, out loadRepeatNumber);

                        var filename = i.ToString();
                        filename = filename.Trim();

                        var w2 = new Window2
                        {
                            Title = "Sticky Note",
                            Tag = ArrayPos,
                            Height = height,
                            Width = width,
                            Left = x,
                            Top = y,
                            ShowInTaskbar = false,
                            Topmost = topmost,
                            TopmostWindow = topmost
                        };

                        if (w2.Topmost)
                        {
                            try
                            {
                                var m = LogicalTreeHelper.FindLogicalNode(w2, "AlwaysOnTop") as MenuItem;
                                m.IsChecked = true;
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (backgroundColorIndex > -1)
                        {
                            w2.Background = Window2.ChangeBackgroundColor(Dialog.ColorArray[backgroundColorIndex]);
                            w2.BackgroundColorIndex = backgroundColorIndex;
                        }
                        if (foregroundColorIndex > -1)
                        {
                            w2.Foreground = Dialog.ColorArrayForeground[foregroundColorIndex];
                            w2.ForegroundColorIndex = foregroundColorIndex;
                        }
                        w2.Alarm = alarmTime;
                        w2.RepetitionNumber = loadRepeatNumber.Contains("null") ? "null" : loadRepeatNumber;


                        CheckIfAlarmFires(w2);

                        WindowArray[ArrayPos] = w2;
                        ArrayPos++;

                        var noteFiles = new FileStream(filename, FileMode.Open);

                        var rtb = ((RichTextBox) ((StackPanel) (w2.Content)).Children[1]);
                        var tr = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
                        try
                        {
                            tr.Load(noteFiles, contentIndicator == 0 ? DataFormats.XamlPackage : DataFormats.Xaml);
                        }
                        catch (Exception)
                        {
                        }
                        noteFiles.Close();
                    }
                    fs.Close();
                }
            }
            for (var i = ++count; i < 100; i++)
            {
                if (File.Exists(i.ToString()))
                {
                    File.Delete(i.ToString());
                }
            }
        }

        private void ExtractValues(out int contentIndicator, string line, out double height, out double width,
            out double x,
            out double y, out bool topmost, out int backgroundColorIndex, out int foregroundColorIndex,
            out DateTime alarmTime,
            out string loadRepeatNumber)
        {
            var index = line.IndexOf('|');
            var firstToken = line.Substring(0, index);
            contentIndicator = int.Parse(firstToken);

            var tail = index + 1;
            index = line.IndexOf('|', tail);
            y = GetStoredValues(line, index, tail);

            tail = index + 1;
            index = line.IndexOf('|', tail);
            x = GetStoredValues(line, index, tail);

            tail = index + 1;
            index = line.IndexOf('|', tail);
            height = GetStoredValues(line, index, tail);

            tail = index + 1;
            index = line.IndexOf('|', tail);
            width = GetStoredValues(line, index, tail);

            tail = index + 1;
            index = line.IndexOf('|', tail);
            var token = line.Substring(tail, (index - tail));
            topmost = (token.Contains(bool.TrueString)) ? true : false;

            tail = index + 1;
            index = line.IndexOf('|', tail);
            token = line.Substring(tail, (index - tail));
            backgroundColorIndex = int.Parse(token);

            tail = index + 1;
            index = line.IndexOf('|', tail); //line.Length;
            token = line.Substring(tail, (index - tail));
            foregroundColorIndex = int.Parse(token);

            tail = index + 1;
            index = line.IndexOf(':', tail);
            token = line.Substring(tail, (index - tail));
            var hours = int.Parse(token);

            tail = index + 1;
            index = line.IndexOf(':', tail);
            token = line.Substring(tail, (index - tail));
            var minutes = int.Parse(token);

            tail = index + 1;
            index = line.IndexOf('|', tail);
            token = line.Substring(tail, (index - tail));
            var seconds = (int) double.Parse(token);

            tail = index + 1;
            index = line.IndexOf('/', tail);
            token = line.Substring(tail, (index - tail));
            var month = int.Parse(token);

            tail = index + 1;
            index = line.IndexOf('/', tail);
            token = line.Substring(tail, (index - tail));
            var day = int.Parse(token);

            tail = index + 1;
            index = line.IndexOf('|', tail);
            token = line.Substring(tail, (index - tail));
            var year = int.Parse(token);


            alarmTime = new DateTime(year, month, day, hours, minutes, seconds);

            tail = index + 1;
            index = line.Length;
            loadRepeatNumber = line.Substring(tail, (index - tail));
        }

        private double GetStoredValues(string line, int index, int tail)
        {
            var token = line.Substring(tail, (index - tail));
            return double.Parse(token);
        }

        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            var contentIndicator = new string[ArrayPos];

            var index = 0;

            for (var i = 0; i < ArrayPos; i++)
            {
                if (WindowArray[i] != null)
                {
                    var w = ((Window2) (WindowArray[i]));
                    var rtb = ((RichTextBox) (((StackPanel) (w.Content)).Children[1]));
                    var tr = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);

                    var mstream = new MemoryStream();
                    XamlWriter.Save(rtb.Document, mstream);
                    mstream.Seek(0, SeekOrigin.Begin);
                    var stringReader = new StreamReader(mstream);
                    var str = stringReader.ReadToEnd();
                    stringReader.Close();

                    var fs = new FileStream(index.ToString(), FileMode.Create);
                    var width = (w.ActualWidth > 50) ? (w.ActualWidth) : 200;
                    var height = (w.ActualHeight > 60) ? w.ActualHeight : 200;
                    if (str.Contains("payload"))
                    {
                        contentIndicator[index] = "0 |" + w.Top + "|" + w.Left + "|" +
                                                  height + "|" +
                                                  width + "|" + w.Topmost +
                                                  "|" + w.BackgroundColorIndex + "|" +
                                                  w.ForegroundColorIndex + "|" +
                                                  w.Alarm.TimeOfDay + "|" + w.Alarm.Date.ToShortDateString() +
                                                  "|" + w.RepetitionNumber;
                        tr.Save(fs, DataFormats.XamlPackage);
                    }
                    else
                    {
                        contentIndicator[index] = "1 |" + w.Top + "|" + w.Left + "|" +
                                                  height + "|" +
                                                  width + "|" + w.Topmost +
                                                  "|" + w.BackgroundColorIndex + "|" +
                                                  w.ForegroundColorIndex + "|" +
                                                  w.Alarm.TimeOfDay + "|" + w.Alarm.Date.ToShortDateString() +
                                                  "|" + w.RepetitionNumber;
                        tr.Save(fs, DataFormats.Xaml);
                    }
                    index++;
                    fs.Close();
                    ((Window2) (WindowArray[i])).Close();
                }
            }

            if (File.Exists("NotesFile"))
            {
                File.Delete("NotesFile");
            }
            var mainDataFile = new FileStream("NotesFile", FileMode.OpenOrCreate);
            var writer = new StreamWriter(mainDataFile);
            writer.WriteLine(index + "|" + AppWindow.Top + "|" + AppWindow.Left + "|" +
                             AppWindow.ActualHeight + "|" + AppWindow.ActualWidth + "|" +
                             AppWindow.Topmost + "|-1" + "|-1" + "|" + DateTime.Now.TimeOfDay +
                             "|" +
                             DateTime.Now.Date.ToShortDateString() + "|null");
            for (var i = 0; i < index; i++)
            {
                writer.WriteLine(contentIndicator[i]);
            }
            writer.Close();
            mainDataFile.Close();
        }

        private void AlarmTimer_Tick(object sender, EventArgs e)
        {
            var index = 0;
            _windowContents = new string[ArrayPos];
            for (var i = 0; i < ArrayPos; i++)
            {
                if (WindowArray[i] != null)
                {
                    var w = ((Window2) (WindowArray[i]));
                    StoreContents(index++);
                    CheckIfAlarmFires(w);
                }
            }

            WriteNotesFile(index);
        }

        private static void CheckIfAlarmFires(Window2 w)
        {
            var current = DateTime.Now;
            var m = LogicalTreeHelper.FindLogicalNode(w, "AlwaysOnTop") as MenuItem;
            var m1 = LogicalTreeHelper.FindLogicalNode(w, "alarm") as MenuItem;
            var m3 = LogicalTreeHelper.FindLogicalNode(w, "DismissAlarm") as MenuItem;
            var alarm = w.Alarm;

            var m2 =
                LogicalTreeHelper.FindLogicalNode(w, "AlarmIndicator") as Image;
            m2.Visibility = (alarm.CompareTo(DateTime.Now) >= 0) ? (Visibility.Visible) : (Visibility.Hidden);

            if (w.RepetitionNumber.Contains("null") == false)
            {
                if ((alarm.CompareTo(current) < 0) &&
                    (!(((current.TimeOfDay.Hours - alarm.TimeOfDay.Hours) < 8) &&
                       ((current.TimeOfDay.Hours - alarm.TimeOfDay.Hours) >= 0))
                     || !(current.Date.ToShortDateString().Contains(alarm.Date.ToShortDateString()))))
                {
                    var chArr = w.RepetitionNumber.ToCharArray(0, 1);
                    var val = w.RepetitionNumber.Substring(1);
                    var repetitionValue = int.Parse(val);
                    switch (chArr[0])
                    {
                        case 'W':
                            while (w.Alarm.Date.CompareTo(current.Date) < 0)
                            {
                                w.Alarm = w.Alarm.AddDays(7*repetitionValue);
                            }

                            break;

                        case 'D':
                            while (w.Alarm.Date.CompareTo(current.Date) < 0)
                            {
                                w.Alarm = w.Alarm.AddDays(repetitionValue);
                            }
                            break;

                        default:
                            break;
                    }
                    alarm = w.Alarm;
                }
            }

            if (alarm.Date == current.Date)
            {
                var temp1 = alarm;
                var temp2 = current;
                temp1 = temp1.AddMinutes(30);
                temp2 = temp2.AddMinutes(30);

                if ((temp2.CompareTo(alarm) >= 0) && (temp1.CompareTo(current) >= 0) && (w.AlarmDismissed == false))
                {
                    w.Topmost = true;
                    m.IsChecked = true;
                    m1.IsEnabled = true;
                    m3.IsEnabled = true;
                    m2.Visibility = Visibility.Visible;

                    w.BorderBrush = Brushes.Black;
                    w.BorderThickness = new Thickness(5);
                }
                else if (((current.TimeOfDay.Hours - alarm.TimeOfDay.Hours) < 8) &&
                         ((current.TimeOfDay.Hours - alarm.TimeOfDay.Hours) >= 0))
                {
                    w.Topmost = w.TopmostWindow;
                    m.IsChecked = w.Topmost;
                    m1.IsEnabled = (!w.RepetitionNumber.Contains("null"));
                    m2.Visibility = m1.IsEnabled ? (Visibility.Visible) : (Visibility.Hidden);
                    m3.IsEnabled = false;
                    w.BorderBrush = Brushes.Tomato;
                    w.BorderThickness = new Thickness(3);
                }
                else
                {
                    w.AlarmDismissed = false;
                    m3.IsEnabled = false;
                    m1.IsEnabled = (!w.RepetitionNumber.Contains("null"));
                    m2.Visibility = m1.IsEnabled ? (Visibility.Visible) : (Visibility.Hidden);
                }
            }
            else
            {
                w.Topmost = w.TopmostWindow;
                m.IsChecked = w.Topmost;
                m1.IsEnabled = (!w.RepetitionNumber.Contains("null"));
                m2.Visibility = m1.IsEnabled ? (Visibility.Visible) : (Visibility.Hidden);
                m3.IsEnabled = false;

                w.BorderBrush = Brushes.Transparent;
                w.BorderThickness = new Thickness(0);
            }
        }

        private void MainWindow_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var w2 = new Window2
            {
                Title = "Sticky Note",
                Tag = ArrayPos
            };
            WindowArray[ArrayPos] = w2;
            ArrayPos++;
        }

        private void StoreContents(int index)
        {
            var w = ((Window2) (WindowArray[index]));
            var rtb = ((RichTextBox) (((StackPanel) (w.Content)).Children[1]));
            var tr = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);

            var mstream = new MemoryStream();
            XamlWriter.Save(rtb.Document, mstream);
            mstream.Seek(0, SeekOrigin.Begin);
            var stringReader = new StreamReader(mstream);
            var str = stringReader.ReadToEnd();
            stringReader.Close();

            var fs = new FileStream(index.ToString(), FileMode.Create);
            var width = (w.ActualWidth > 50) ? (w.ActualWidth) : 200;
            var height = (w.ActualHeight > 60) ? w.ActualHeight : 200;
            if (str.Contains("payload"))
            {
                _windowContents[index] = "0 |" + w.Top + "|" + w.Left + "|" + height +
                                         "|" +
                                         width + "|" + w.Topmost +
                                         "|" + w.BackgroundColorIndex + "|" +
                                         w.ForegroundColorIndex + "|" +
                                         w.Alarm.TimeOfDay + "|" + w.Alarm.Date.ToShortDateString() +
                                         "|" + w.RepetitionNumber;
                tr.Save(fs, DataFormats.XamlPackage);
            }
            else
            {
                _windowContents[index] = "1 |" + w.Top + "|" + w.Left + "|" + height +
                                         "|" +
                                         width + "|" + w.Topmost +
                                         "|" + w.BackgroundColorIndex + "|" +
                                         w.ForegroundColorIndex + "|" +
                                         w.Alarm.TimeOfDay + "|" + w.Alarm.Date.ToShortDateString() +
                                         "|" + w.RepetitionNumber;
                tr.Save(fs, DataFormats.Xaml);
            }
            fs.Close();
        }

        private void WriteNotesFile(int index)
        {
            if (File.Exists("NotesFile"))
            {
                File.Delete("NotesFile");
            }
            var mainDataFile = new FileStream("NotesFile", FileMode.Create);
            var writer = new StreamWriter(mainDataFile);
            writer.WriteLine(index + "|" + AppWindow.Top + "|" + AppWindow.Left + "|" +
                             AppWindow.ActualHeight + "|" + AppWindow.ActualWidth + "|" +
                             AppWindow.Topmost + "|-1" + "|-1" + "|" + DateTime.Now.TimeOfDay +
                             "|" +
                             DateTime.Now.Date.ToShortDateString() + "|null");
            for (var i = 0; i < index; i++)
            {
                writer.WriteLine(_windowContents[i]);
            }
            writer.Close();
        }

        // Sample event handler:  
        private void CloseButtonClick(object sender, RoutedEventArgs e)
        {
            AppWindow.Close();
        }

        private void cb_Click(object sender, RoutedEventArgs e)
        {
            var cb = sender as CheckBox;
            AppWindow.Topmost = (cb.IsChecked == true) ? true : false;
            AppWindow.Focus();
        }

        private void l_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            cb.IsChecked = !cb.IsChecked;
            AppWindow.Topmost = (cb.IsChecked == true) ? true : false;
        }
    }
}

<|start_filename|>Windows/DialogBox/FindDialogBox.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;

// EventArgs
// Window, MessageBoxXxx, RoutedEventArgs
// TextBox, TextChangedEventArgs

// Regex

namespace DialogBox
{
    public partial class FindDialogBox : Window
    {
        // Text to search
        private readonly TextBox _textBoxToSearch;
        // Find results
        private MatchCollection _matches;
        private int _matchIndex;

        public FindDialogBox(TextBox textBoxToSearch)
        {
            InitializeComponent();

            _textBoxToSearch = textBoxToSearch;

            // If text box that's being searched is changed, reset search
            _textBoxToSearch.TextChanged += textBoxToSearch_TextChanged;
        }

        // Search results

        public int Index { get; set; }
        public int Length { get; set; }
        public event TextFoundEventHandler TextFound;

        protected virtual void OnTextFound()
        {
            var textFound = TextFound;
            textFound?.Invoke(this, EventArgs.Empty);
        }

        private void findNextButton_Click(object sender, RoutedEventArgs e)
        {
            // Find matches
            if (_matches == null)
            {
                var pattern = findWhatTextBox.Text;

                // Match whole word?
                if ((bool) matchWholeWordCheckBox.IsChecked) pattern = @"(?<=\W{0,1})" + pattern + @"(?=\W)";

                // Case sensitive
                if (!(bool) caseSensitiveCheckBox.IsChecked) pattern = "(?i)" + pattern;

                // Find matches
                _matches = Regex.Matches(_textBoxToSearch.Text, pattern);
                _matchIndex = 0;

                // Word not found?
                if (_matches.Count == 0)
                {
                    MessageBox.Show("'" + findWhatTextBox.Text + "' not found.", "Find");
                    _matches = null;
                    return;
                }
            }

            // Start at beginning of matches if the last find selected the last match
            if (_matchIndex == _matches.Count)
            {
                var result = MessageBox.Show("Nmore matches found. Start at beginning?", "Find",
                    MessageBoxButton.YesNo);
                if (result == MessageBoxResult.No) return;

                // Reset
                _matchIndex = 0;
            }

            // Return match details to client so it can select the text
            var match = _matches[_matchIndex];
            if (TextFound != null)
            {
                // Text found
                Index = match.Index;
                Length = match.Length;
                OnTextFound();
            }
            _matchIndex++;
        }

        private void textBoxToSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            ResetFind();
        }

        private void findWhatTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            ResetFind();
        }

        private void criteria_Click(object sender, RoutedEventArgs e)
        {
            ResetFind();
        }

        private void ResetFind()
        {
            findNextButton.IsEnabled = true;
            _matches = null;
        }

        private void closeButton_Click(object sender, RoutedEventArgs e)
        {
            // Close dialog box
            Close();
        }
    }
}

//</SnippetFindDialogCloseCODEBEHIND2>

<|start_filename|>Sample Applications/GraphingCalculatorDemo/TrackBall.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Media3D;

namespace GraphingCalculatorDemo
{
    public class Trackball
    {
        private Point3D _center;
        private bool _centered; // Have we already determined the rotation center?
        // The state of the trackball
        private bool _enabled;
        private Point _point; // Initial point of drag
        private Quaternion _rotation;
        private Quaternion _rotationDelta; // Change to rotation because of this drag
        private double _scale;
        private double _scaleDelta; // Change to scale because of this drag
        // The state of the current drag
        private bool _scaling; // Are we scaling?  NOTE otherwise we're rotating
        private List<Viewport3D> _servants;

        public Trackball()
        {
            Reset();
        }

        public List<Viewport3D> Servants
        {
            get { return _servants ?? (_servants = new List<Viewport3D>()); }
            set { _servants = value; }
        }

        public bool Enabled
        {
            get { return _enabled && (_servants != null) && (_servants.Count > 0); }
            set { _enabled = value; }
        }

        public void Attach(FrameworkElement element)
        {
            element.MouseMove += MouseMoveHandler;
            element.MouseLeftButtonDown += MouseDownHandler;
            element.MouseLeftButtonUp += MouseUpHandler;
        }

        public void Detach(FrameworkElement element)
        {
            element.MouseMove -= MouseMoveHandler;
            element.MouseLeftButtonDown -= MouseDownHandler;
            element.MouseLeftButtonUp -= MouseUpHandler;
        }

        // Updates the matrices of the slaves using the rotation quaternion.
        private void UpdateServants(Quaternion q, double s)
        {
            var rotation = new RotateTransform3D(); //IB: changed this


            var quatRotation = new QuaternionRotation3D(q);
            rotation.Rotation = quatRotation;
            //rotation.Rotation = new Rotation3D(q);
            rotation.CenterX = _center.X;
            rotation.CenterY = _center.Y;

            var scale = new ScaleTransform3D(new Vector3D(s, s, s));
            var rotateAndScale = new Transform3DCollection {scale, rotation};

            //IB: moved out of the constructor above


            if (_servants != null)
            {
                foreach (var i in _servants)
                {
                    // Note that we don't copy constantly here, we copy the first time someone tries to
                    // trackball a frozen Models, but we replace it with a ChangeableReference
                    // and so subsequent interactions go through without a copy.
                    /* mijacobs: commenting out
					if (i.Models.Transform.IsFrozen)
					{
						Model3DGroup mutableCopy = i.Models.Copy();
						//mutableCopy.StatusOfNextUse = UseStatus.ChangeableReference; IB: no longer necessary I need to architect this out if time permits
						i.Models = mutableCopy;
					}*/

                    var myTransformGroup = new Transform3DGroup {Children = rotateAndScale}; //IB: added transformGroup

                    // mijacobs old: i.Models.Transform = myTransformGroup;
                    ((Model3DGroup) ((ModelVisual3D) i.Children[0]).Content).Transform = myTransformGroup;
                }
            }
        }

        private void MouseMoveHandler(object sender, MouseEventArgs e)
        {
            if (!Enabled) return;
            e.Handled = true;

            var el = (UIElement) sender;
            if (el.IsMouseCaptured)
            {
                var delta = _point - e.MouseDevice.GetPosition(el);
                delta /= 2;
                // We can redefine this 2D mouse delta as a 3D mouse delta
                // where "into the screen" is Z
                var mouse = new Vector3D(delta.X, -delta.Y, 0);
                var axis = Vector3D.CrossProduct(mouse, new Vector3D(0, 0, 1));
                var len = axis.Length;
                if (len < 0.00001 || _scaling)
                    _rotationDelta = new Quaternion(new Vector3D(0, 0, 1), 0);
                else
                    _rotationDelta = new Quaternion(axis, len);
                var q = _rotationDelta*_rotation;
                _scaleDelta = _scaling ? Math.Exp(delta.Y/10) : 1;
                UpdateServants(q, _scale*_scaleDelta);
            }
        }

        private void MouseDownHandler(object sender, MouseButtonEventArgs e)
        {
            if (!Enabled) return;
            e.Handled = true;

            if (e.ClickCount == 2)
            {
                Reset();
                return;
            }

            var el = (UIElement) sender;
            _point = e.MouseDevice.GetPosition(el);
            // Initialize the center of rotation to the lookatpoint
            if (!_centered)
            {
                var camera = (ProjectionCamera) _servants[0].Camera;
                _center = (Point3D) camera.LookDirection;
                _centered = true;
            }
            _scaling = (e.RightButton == MouseButtonState.Pressed);

            el.CaptureMouse();
        }

        private void MouseUpHandler(object sender, MouseButtonEventArgs e)
        {
            if (!_enabled) return;
            e.Handled = true;

            // Stuff the current initial + delta into initial so when we next move we
            // start at the right place.
            _rotation = _rotationDelta*_rotation;
            _scale = _scaleDelta*_scale;
            var el = (UIElement) sender;
            el.ReleaseMouseCapture();
        }

        private void MouseDoubleClickHandler(object sender, MouseButtonEventArgs e)
        {
            Reset();
        }

        private void Reset()
        {
            _rotation = Quaternion.Identity;
            _scale = 1;
            // Clear delta too, because if reset is called because of a double click then the mouse
            // up handler will also be called and this way it won't do anything.
            _rotationDelta = Quaternion.Identity;
            _scaleDelta = 1;
            UpdateServants(_rotation, _scale);
        }
    }
}

<|start_filename|>Data Binding/SortFilter/Order.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;

namespace SortFilter
{
    public class Order : INotifyPropertyChanged
    {
        private int _customer;
        private DateTime _datefilled;
        private string _filled;
        private int _id;
        private string _name;
        private int _order;
        private DateTime _orderdate;

        public Order(int order, int customer, string name, int id, string filled, DateTime orderdate,
            DateTime datefilled)
        {
            OrderItem = order;
            Customer = customer;
            Name = name;
            Id = id;
            Filled = filled;
            OrderDate = orderdate;
            DateFilled = datefilled;
        }

        public Order(int order, int customer, string name, int id, string filled, DateTime orderdate)
        {
            OrderItem = order;
            Customer = customer;
            Name = name;
            Id = id;
            Filled = filled;
            OrderDate = orderdate;
        }

        public int OrderItem
        {
            get { return _order; }
            set
            {
                _order = value;
                OnPropertyChanged("OrderItem");
            }
        }

        public int Customer
        {
            get { return _customer; }
            set
            {
                _customer = value;
                OnPropertyChanged("Customer");
            }
        }

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        public int Id
        {
            get { return _id; }
            set
            {
                _id = value;
                OnPropertyChanged("Id");
            }
        }

        public string Filled
        {
            get { return _filled; }
            set
            {
                _filled = value;
                OnPropertyChanged("Filled");
            }
        }

        public DateTime OrderDate
        {
            get { return _orderdate; }
            set
            {
                _orderdate = value;
                OnPropertyChanged("OrderDate");
            }
        }

        public DateTime DateFilled
        {
            get { return _datefilled; }
            set
            {
                _datefilled = value;
                OnPropertyChanged("DateFilled");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string info)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/BamlNodeStreamReader.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Baml2006;
using System.Xaml;
using System.Xml;

namespace BamlTools
{
    public class BamlNodeStreamReader
    {
        private readonly Baml2006Reader _bamlReader;
        private readonly DiagnosticWriter _displayWriter;

        public BamlNodeStreamReader(Stream bamlStream, Assembly localAssembly)
        {
            XamlReaderSettings readerSettings = new XamlReaderSettings
            {
                LocalAssembly = localAssembly,
                ValuesMustBeString = true
            };
            _bamlReader = new Baml2006Reader(bamlStream, readerSettings);
            _displayWriter = new DiagnosticWriter(_bamlReader.SchemaContext);
        }

        public string OneBigString()
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                while (_bamlReader.Read())
                {
                    _displayWriter.WriteNode(_bamlReader);
                    sb.AppendLine(_displayWriter.CurrentIndentedNodeText);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.ToString());
            }
            return sb.ToString();
        }
    }

    public class BamlToXamlReader
    {
        private readonly Baml2006Reader _bamlReader;
        XamlXmlWriter _xamlWriter;

        public BamlToXamlReader(Stream bamlStream, Assembly localAssembly)
        {
            XamlReaderSettings readerSettings = new XamlReaderSettings
            {
                LocalAssembly = localAssembly,
                ValuesMustBeString = true
            };
            _bamlReader = new Baml2006Reader(bamlStream, readerSettings);
        }

        public string OneBigString()
        {
            StringBuilder sb = new StringBuilder();
            XmlWriterSettings xmlSettings = new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "  ",
                OmitXmlDeclaration = true
            };
            XmlWriter xmlWriter = XmlWriter.Create(sb, xmlSettings);

            _xamlWriter = new XamlXmlWriter(xmlWriter, _bamlReader.SchemaContext);
            while (_bamlReader.Read())
            {
                _xamlWriter.WriteNode(_bamlReader);
            }
            xmlWriter.Flush();
            xmlWriter.Close();
            return sb.ToString();
        }
    }
}


<|start_filename|>Data Binding/Colors/ByteToDoubleConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace Colors
{
    // Two-way conversion between byte and double (TypeConverter for double should provide this)

    public class ByteToDoubleConverter : IValueConverter
    {
        object IValueConverter.Convert(object o, Type type, object parameter, CultureInfo culture) => Convert.ChangeType(o, typeof(double));

        object IValueConverter.ConvertBack(object o, Type type, object parameter, CultureInfo culture)
        {
            var d = (double) o;
            return (d < 0.0)
                ? (byte) 0
                : (d > 255.0)
                    ? (byte) 255
                    : Convert.ChangeType(o, typeof (byte));
        }
    }
}

<|start_filename|>Speech and Media/UsingSpeech/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Speech.Synthesis;
using System.Windows;
using System.Windows.Controls;

namespace UsingSpeech
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly SpeechSynthesizer _speechSynthesizer = new SpeechSynthesizer();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void VolumeChanged(object sender, RoutedEventArgs args)
        {
            _speechSynthesizer.Volume = (int) ((Slider) args.OriginalSource).Value;
        }

        private void RateChanged(object sender, RoutedEventArgs args)
        {
            _speechSynthesizer.Rate = (int) ((Slider) args.OriginalSource).Value;
        }

        private void ButtonEchoOnClick(object sender, RoutedEventArgs args)
        {
            _speechSynthesizer.SpeakAsync(TextToDisplay.Text);
        }

        private void ButtonDateOnClick(object sender, RoutedEventArgs args)
        {
            _speechSynthesizer.SpeakAsync("Today is " + DateTime.Now.ToShortDateString());
        }

        private void ButtonTimeOnClick(object sender, RoutedEventArgs args)
        {
            _speechSynthesizer.SpeakAsync("The time is " + DateTime.Now.ToShortTimeString());
        }

        private void ButtonNameOnClick(object sender, RoutedEventArgs args)
        {
            _speechSynthesizer.SpeakAsync("My name is " + _speechSynthesizer.Voice.Name);
        }
    }
}

<|start_filename|>Input and Commands/TouchKeyboard/TouchKeyboardNotifier/TouchKeyboardAwareDecorator.cs<|end_filename|>
﻿// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;

namespace Microsoft.Windows.Input.TouchKeyboard
{
    /// <summary>
    /// A decorator that registers for and responds to touch keyboard events.
    /// 
    /// If the keyboard focused control is within the decorator and the control is occluded by the keyboard
    /// the decorator will appropriately shift the arrangement of the content such that the focused control
    /// is either snapped to the top of the decorator or snapped to the top of the occluded rectangle.
    /// 
    /// To use this, wrap either part or the entire content of a window in this decorator.  The content inside
    /// the decorator will then respond to the touch keyboard showing and hiding.
    /// </summary>
    /// <remarks>
    /// Known Issues:
    /// 
    ///     Popups will NOT move with their owning controls.  This includes tooltips, menus, dropdowns.  This is
    ///     an internal WPF issue and is beyond the scope of this class.
    ///     
    ///     Two decorators placed side by side in the visual tree might exhibit a strange look and feel.  This is
    ///     due to only the decorator with the focused element being shifted up.
    ///     
    ///     Partial trust applications cannot automatically invoke the touch keyboard or register for notifications.
    /// </remarks>
    public class TouchKeyboardAwareDecorator : Decorator
    {
        #region Member Variables

        /// <summary>
        /// If the touch keyboard is currently showing
        /// </summary>
        private bool _kbShowing = false;

        /// <summary>
        /// The rectangle occluded by the touch keyboard
        /// </summary>
        private static Rect _occludedRect = new Rect();

        /// <summary>
        /// The Y value that is being used to shift the decorator's content
        /// </summary>
        private double _currentShift = 0;

        /// <summary>
        /// The window being occluded by the touch keyboard
        /// </summary>
        private Window _occludedWindow = null;

        #endregion

        #region Constructor/Initialize

        public TouchKeyboardAwareDecorator()
            : base()
        {
        }

        /// <summary>
        /// When the decorator is initialized, subscribe to window load
        /// in order to have the HWND to subscribe to touch keyboard events.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            Window w = Window.GetWindow(this);

            if (w != null)
            {
                w.Loaded += ParentWindowLoaded;
            }
        }

        #endregion

        #region Overrides

        /// <summary>
        /// Overrides arrange so that we can alter the rectangle used for arranging the
        /// decorator's content.
        /// </summary>
        /// <param name="finalSize">The arrange size</param>
        /// <returns>The final arrangement size</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            UIElement child = Child;

            if (child != null)
            {
                // Get the Y shift that must be done to properly display the occluded control (if any)
                _currentShift = CalculateContentShift();

                // We need to modify the size we arrange into in order to account for the current shift value.
                // If we don't, any shift up will result in a bottom control that is clipped to the original
                // arrange size, much like a translate RenderTransform would do.
                finalSize = new Size(finalSize.Width, finalSize.Height + Math.Abs(_currentShift));

                // Arrange the child to the desired size, but with a shifted rect
                child.Arrange(new Rect(new Point(0, _currentShift), finalSize));
            }

            // Return the calculated size
            return finalSize;
        }

        #endregion

        #region Touch Keyboard Handling

        /// <summary>
        /// Subscribe to touch keyboard notifications.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParentWindowLoaded(object sender, RoutedEventArgs e)
        {
            Window w = sender as Window;

            if (w != null)
            {
                // Register the window for touch KB notifications
                TouchKeyboardEventManager.AddHandlers(w, HandleTouchKeyboardShowing, HandleTouchKeyboardHiding);

                // Also register for focus changes to detect situations where a shift has caused a clipped top/bottom control
                Keyboard.AddGotKeyboardFocusHandler(w, HandleKeyboardFocus);

                w.Loaded -= ParentWindowLoaded;
            }
        }

        /// <summary>
        /// This is used to detect scenarios where the KB is already showing and a shift has
        /// split a control either with the top of the decorator, or the top of the touch keyboard.
        /// If this control is focused, we then need to modify the shift to make it fully visible.
        /// 
        /// Marks arrange as dirty to trigger a new layout.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            _occludedWindow = sender as Window;

            // On a focus, we only want to update if the KB is showing.  Otherwise any
            // current arrangement is correct.
            if (_kbShowing)
            {
                InvalidateArrange();
            }
        }

        /// <summary>
        /// Stores state information about the touch keyboard and marks arrange as dirty to trigger a
        /// new layout.
        /// </summary>
        /// <param name="occludedWindow">The window for the touch keyboard</param>
        /// <param name="occludedRect">The screen rectangle being occluded by the touch keyboard</param>
        private void HandleTouchKeyboardShowing(Window occludedWindow, Rect occludedRect)
        {
            _kbShowing = true;
            _occludedRect = occludedRect;
            _occludedWindow = occludedWindow;

            InvalidateArrange();
        }

        /// <summary>
        /// Stores state information about the touch keyboard and marks arrange as dirty to trigger a
        /// new layout.
        /// </summary>
        /// <param name="occludedWindow">The window for the touch keyboard</param>
        /// <param name="occludedRect">The screen rectangle being occluded by the touch keyboard</param>
        private void HandleTouchKeyboardHiding(Window occludedWindow, Rect occludedRect)
        {
            _kbShowing = false;
            _occludedRect = occludedRect;
            _occludedWindow = occludedWindow;

            InvalidateArrange();
        }
        #endregion

        #region Utility

        /// <summary>
        /// The main math behind shifting the content of the decorator in response to occlusion
        /// by the touch keyboard.
        /// 
        /// The algorithm is as follows:
        /// 
        ///     Given a current layout with a current shift value
        /// 
        ///     If we should evaluate occlusion for the focused element
        ///         Start with the current shift as basis for new shift
        ///         Test difference between top of element vs top of decorator
        ///             If negative we are hiding part of it, modify shift downward to make it visible
        ///         Test difference between bottom of element vs top of touch keyboard
        ///             If negative we are hiding part of it, modify shift upward to make it visible
        ///                 If shift upward would occlude element by top of decorator, snap to top of decorator
        ///     If we should not evaluate occlusion (touch keyboard is hidden) shift by zero
        /// </summary>
        /// <returns>The calculated Y shift value</returns>
        private double CalculateContentShift()
        {
            double newShift = 0;

            FrameworkElement focusedElement = Keyboard.FocusedElement as FrameworkElement;

            // We should only calculate the shift if the KB is showing and both this 
            // decorator and the occluded window is an ancestor of the focused element.
            // This accounts for focusing on items in popups.
            if (_kbShowing
                && focusedElement != null
                && _occludedWindow == Window.GetWindow(focusedElement)
                && IsAncestorOf(focusedElement))
            {
                // If no work is to be done, we just keep the current shift.
                newShift = _currentShift;

                // The offset to the top of the focused element in window coordinates.
                // We use the decorator coordinates here since this directly influences the shift.
                double offsetTopToDecorator = focusedElement.TransformToVisual(this).Transform(new Point(0, 0)).Y;

                if (offsetTopToDecorator < 0)
                {
                    // Shift down an increment due to the top of the decorator occluding the focused control
                    newShift = _currentShift - offsetTopToDecorator;
                }
                else
                {
                    // The offset to the bottom of the focused element in screen coords.
                    // We use screen coordinates here since this is compared against the KB occluded rect.
                    double offsetBottomToDecorator = PointToScreen(focusedElement.TransformToVisual(this).Transform(new Point(0, focusedElement.RenderSize.Height))).Y;

                    // The different from the bottom of the occluded element to the KB top converted from screen coords
                    // since this will be added to the shift
                    double kbDiff = PointFromScreen(new Point(0, _occludedRect.Top - offsetBottomToDecorator)).Y;

                    if (kbDiff < 0)
                    {
                        // Shift up an increment due to the KB occluding the focused control
                        // Need to take into account the current shift since this control could be occluded due to
                        // a prior shift.  Also ensure we are not shifting the focused element out of the window by
                        // ensuring it does not shift passed the top offset.  If it does, snap to the top.
                        newShift = (offsetTopToDecorator + kbDiff < 0) ? -offsetTopToDecorator : _currentShift + kbDiff;
                    }
                }
            }

            return newShift;
        }

        #endregion
    }
}


<|start_filename|>Animation/AnimationExamples/SampleViewer.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace AnimationExamples
{
    public partial class SampleViewer : Page
    {
        private static readonly Uri PackUri = new Uri("pack://application:,,,/");
        private readonly DoubleAnimation _borderTranslateDoubleAnimation;
        private readonly DoubleAnimation _sampleGridOpacityAnimation;
        private readonly DoubleAnimation _sampleGridTranslateTransformAnimation;

        public SampleViewer()
        {
            InitializeComponent();


            var widthBinding = new Binding("ActualWidth") {Source = this};

            _sampleGridOpacityAnimation = new DoubleAnimation
            {
                To = 0,
                Duration = new Duration(TimeSpan.FromSeconds(1))
            };

            _sampleGridTranslateTransformAnimation = new DoubleAnimation {BeginTime = TimeSpan.FromSeconds(1)};

            BindingOperations.SetBinding(_sampleGridTranslateTransformAnimation, DoubleAnimation.ToProperty,
                widthBinding);
            _sampleGridTranslateTransformAnimation.Duration = new Duration(TimeSpan.FromSeconds(1));

            _borderTranslateDoubleAnimation = new DoubleAnimation
            {
                To = 0,
                Duration = new Duration(TimeSpan.FromSeconds(1)),
                BeginTime = TimeSpan.FromSeconds(2),
                FillBehavior = FillBehavior.HoldEnd
            };
            BindingOperations.SetBinding(_borderTranslateDoubleAnimation, DoubleAnimation.FromProperty, widthBinding);
        }

        private void SelectedSampleChanged(object sender, RoutedEventArgs args)
        {
            if (args.Source is RadioButton)
            {
                var theButton = (RadioButton) args.Source;
                var theFrame = (Frame) theButton.Content;

                if (theFrame.HasContent)
                {
                    var source = theFrame.CurrentSource;
                    if ((source != null) && !source.IsAbsoluteUri)
                    {
                        source = new Uri(PackUri, source);
                    }
                    SampleDisplayFrame.Source = source;

                    SampleDisplayBorder.Visibility = Visibility.Visible;
                }
            }
        }

        private void SampleDisplayFrameLoaded(object sender, EventArgs args)
        {
            SampleGrid.BeginAnimation(OpacityProperty, _sampleGridOpacityAnimation);
            SampleGridTranslateTransform.BeginAnimation(TranslateTransform.XProperty,
                _sampleGridTranslateTransformAnimation);
            SampleDisplayBorderTranslateTransform.BeginAnimation(TranslateTransform.XProperty,
                _borderTranslateDoubleAnimation);
            SampleDisplayBorder.Visibility = Visibility.Visible;
        }

        private void GalleryLoaded(object sender, RoutedEventArgs args)
        {
            SampleDisplayBorderTranslateTransform.X = ActualWidth;
            SampleDisplayBorder.Visibility = Visibility.Hidden;
        }

        private void PageSizeChanged(object sender, SizeChangedEventArgs args)
        {
            SampleDisplayBorderTranslateTransform.X = ActualWidth;
        }
    }
}

<|start_filename|>Animation/AnimationExamples/BackDoubleAnimation.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace AnimationExamples
{
    /// <summary>
    ///     BackDoubleAnimation: goes in the opposite direction first
    /// </summary>
    public class BackDoubleAnimation : DoubleAnimationBase
    {
        public enum EdgeBehaviorEnum
        {
            EaseIn,
            EaseOut,
            EaseInOut
        }

        public static readonly DependencyProperty EdgeBehaviorProperty =
            DependencyProperty.Register("EdgeBehavior", typeof (EdgeBehaviorEnum), typeof (BackDoubleAnimation),
                new PropertyMetadata(EdgeBehaviorEnum.EaseIn));

        public static readonly DependencyProperty AmplitudeProperty =
            DependencyProperty.Register("Amplitude", typeof (double), typeof (BackDoubleAnimation),
                new PropertyMetadata(4.0));

        public static readonly DependencyProperty SuppressionProperty =
            DependencyProperty.Register("Suppression", typeof (double), typeof (BackDoubleAnimation),
                new PropertyMetadata(2.0));

        public static readonly DependencyProperty FromProperty =
            DependencyProperty.Register("From",
                typeof (double?),
                typeof (BackDoubleAnimation),
                new PropertyMetadata(null));

        public static readonly DependencyProperty ToProperty =
            DependencyProperty.Register("To",
                typeof (double?),
                typeof (BackDoubleAnimation),
                new PropertyMetadata(null));

        /// <summary>
        ///     which side gets the effect
        /// </summary>
        public EdgeBehaviorEnum EdgeBehavior
        {
            get { return (EdgeBehaviorEnum) GetValue(EdgeBehaviorProperty); }
            set { SetValue(EdgeBehaviorProperty, value); }
        }

        /// <summary>
        ///     how much backwards motion is there in the effect
        /// </summary>
        public double Amplitude
        {
            get { return (double) GetValue(AmplitudeProperty); }
            set { SetValue(AmplitudeProperty, value); }
        }

        /// <summary>
        ///     how quickly the effect drops off vs. the entire timeline
        /// </summary>
        public double Suppression
        {
            get { return (double) GetValue(SuppressionProperty); }
            set { SetValue(SuppressionProperty, value); }
        }

        /// <summary>
        ///     Specifies the starting value of the animation.
        /// </summary>
        public double? From
        {
            get { return (double?) GetValue(FromProperty); }
            set { SetValue(FromProperty, value); }
        }

        /// <summary>
        ///     Specifies the ending value of the animation.
        /// </summary>
        public double? To
        {
            get { return (double?) GetValue(ToProperty); }
            set { SetValue(ToProperty, value); }
        }

        protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue,
            AnimationClock clock)
        {
            double returnValue;
            var start = From ?? defaultOriginValue;
            var delta = To - start ?? defaultOriginValue - start;
            switch (EdgeBehavior)
            {
                case EdgeBehaviorEnum.EaseIn:
                    returnValue = EaseIn(clock.CurrentProgress.Value, start, delta, Amplitude, Suppression);
                    break;
                case EdgeBehaviorEnum.EaseOut:
                    returnValue = EaseOut(clock.CurrentProgress.Value, start, delta, Amplitude, Suppression);
                    break;
                default:
                    returnValue = EaseInOut(clock.CurrentProgress.Value, start, delta, Amplitude, Suppression);
                    break;
            }
            return returnValue;
        }

        protected override Freezable CreateInstanceCore() => new BackDoubleAnimation();

        private static double EaseOut(double timeFraction, double start, double delta, double amplitude,
            double suppression)
        {
            var frequency = 0.5;

            // math magic: The sine gives us the right wave, the timeFraction * 0.5 (frequency) gives us only half 
            // of the full wave, the amplitude gives us the relative height of the peak, and the exponent makes the 
            // effect drop off more quickly by the "suppression" factor. 
            var returnValue = Math.Pow((timeFraction), suppression)
                              *amplitude*Math.Sin(2*Math.PI*timeFraction*frequency) + timeFraction;
            returnValue = (returnValue*delta);
            returnValue += start;
            return returnValue;
        }

        private static double EaseIn(double timeFraction, double start, double delta, double amplitude,
            double suppression)
        {
            const double frequency = 0.5;

            // math magic: The sine gives us the right wave, the timeFraction * 0.5 (frequency) gives us only half 
            // of the full wave (flipped by multiplying by -1 so that we go "backwards" first), the amplitude gives 
            // us the relative height of the peak, and the exponent makes the effect start later by the "suppression" 
            // factor. 
            var returnValue = Math.Pow((1 - timeFraction), suppression)
                              *amplitude*Math.Sin(2*Math.PI*timeFraction*frequency)*-1 + timeFraction;
            returnValue = (returnValue*delta);
            returnValue += start;
            return returnValue;
        }

        private static double EaseInOut(double timeFraction, double start, double delta, double amplitude,
            double suppression)
        {
            double returnValue;

            // we cut each effect in half by multiplying the time fraction by two and halving the distance.
            if (timeFraction <= 0.5)
            {
                return EaseIn(timeFraction*2, start, delta/2, amplitude, suppression);
            }
            returnValue = EaseOut((timeFraction - 0.5)*2, start, delta/2, amplitude, suppression);
            returnValue += (delta/2);
            return returnValue;
        }
    }
}

<|start_filename|>Sample Applications/CustomComboBox/DropList.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CustomComboBox
{
    class DropList : ContentControl
    {
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(DropList), new PropertyMetadata(null));

        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter", typeof(object), typeof(DropList), new PropertyMetadata(null));

        public string SubTitle
        {
            get { return (string)GetValue(SubTitleProperty); }
            set { SetValue(SubTitleProperty, value); }
        }

        public static readonly DependencyProperty SubTitleProperty =
            DependencyProperty.Register("SubTitle", typeof(string), typeof(DropList));

        public string DynamicText
        {
            get { return (string)GetValue(DynamicTextProperty); }
            set { SetValue(DynamicTextProperty, value); }
        }

        public static readonly DependencyProperty DynamicTextProperty =
            DependencyProperty.Register("DynamicText", typeof(string), typeof(DropList));


        public IEnumerable<object> ItemsSource
        {
            get { return (IEnumerable<object>)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(IEnumerable<object>), typeof(DropList));


        public string DisplayMemberPath
        {
            get { return (string)GetValue(DisplayMemberPathProperty); }
            set { SetValue(DisplayMemberPathProperty, value); }
        }

        public static readonly DependencyProperty DisplayMemberPathProperty =
            DependencyProperty.Register("DisplayMemberPath", typeof(string), typeof(DropList), new PropertyMetadata(null));

    }
}


<|start_filename|>Graphics/AITCodec/cpp/cmykpixelformatconverter.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of CmykPixelFormatConverter
//----------------------------------------------------------------------------------------
#include "precomp.hpp"

// The Cmyk format GUID {9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}
// {710194EC-F8B2-4b7a-94AD-945A7DCDEADB}
static const GUID GUID_TestPixelFormat32bppCmyk = 
{ 0x710194ec, 0xf8b2, 0x4b7a, { 0x94, 0xad, 0x94, 0x5a, 0x7d, 0xcd, 0xea, 0xdb } };

static const GUID CLSID_CmykPixelFormatConverter = 
{ 0xb312a459, 0x2a44, 0x4833, { 0xaa, 0x45, 0xf, 0x50, 0xbc, 0x66, 0x9a, 0x28 }};



CmykPixelFormatConverter::CmykPixelFormatConverter()
: BasePixelFormatConverter()
{}

STDMETHODIMP CmykPixelFormatConverter::CanConvert( 
        /* [in] */ REFWICPixelFormatGUID srcPixelFormat,
        /* [in] */ REFWICPixelFormatGUID dstPixelFormat,
        /* [out] */ BOOL *pfCanConvert)
{
    HRESULT result = E_INVALIDARG;

    if (NULL != pfCanConvert)
    {
        result = S_OK;

        // I can convert from Cmyk to RGB and back only
        if ((GUID_WICPixelFormat32bppBGRA == srcPixelFormat) &&
            (GUID_TestPixelFormat32bppCmyk == dstPixelFormat))
        {
            *pfCanConvert = TRUE;
        }
        else if ((GUID_TestPixelFormat32bppCmyk   == srcPixelFormat) &&
            (GUID_WICPixelFormat32bppBGRA == dstPixelFormat))
        {
            *pfCanConvert = TRUE;
        }
        else
        {
            *pfCanConvert = FALSE;
        }
    }
    return result;
}

STDMETHODIMP CmykPixelFormatConverter::CopyPixels( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels)
{
    HRESULT result = E_UNEXPECTED;

    if (NULL != bitmapSource)
    {
        //Do the actual conversion
        if (destPixelFormat == GUID_WICPixelFormat32bppBGRA)
        {
            //Convert back to canonical 32PARGB            
            result = ConvertCmykToRgb(prc, cbStride, cbPixelsSize, pbPixels);
        }
        else if (destPixelFormat == GUID_TestPixelFormat32bppCmyk)
        {
            //Convert to newly supported Cmyk
            result = ConvertRgbToCmyk(prc, cbStride, cbPixelsSize, pbPixels);
        }
    }
    return result;
}


    HRESULT CmykPixelFormatConverter::ConvertCmykToRgb( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels)
    {
        HRESULT result = S_OK;
        
        //Sanity check
        WICPixelFormatGUID srcPixelFormat;
        bitmapSource->GetPixelFormat(&srcPixelFormat);
        if (srcPixelFormat != GUID_TestPixelFormat32bppCmyk)
        {
             result = E_UNEXPECTED;                  
        }  

        UINT width, height;

        if (prc == NULL)
        {
            if (SUCCEEDED(result))
            {
                result = bitmapSource->GetSize(&width, &height);
            }
        }else
        {
            width = prc->Width;
            height = prc->Height;
        }
        
        if (SUCCEEDED(result))
        {        
            result = bitmapSource->CopyPixels(prc, cbStride, cbPixelsSize, pbPixels);
        }

        //Since the two formats have same number of bytes, we will do an inplace conversion
        //Loop on the data and do the conversion
        if (SUCCEEDED(result))
        {
            BYTE *curPos = NULL;
            curPos = pbPixels;
            for (int i = 0 ; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    float R, G ,B;
                    float C, M, Y, K;

                    K = *curPos / 100.0;
                    Y = *(curPos+1) / 100.0;
                    M = *(curPos+2) / 100.0;      
                    C = *(curPos+3) / 100.0;      

                    //Do the maths
                    C = C*(1 - K) + K;      
                    M = M*(1 - K) + K;      
                    Y = Y*(1 - K) + K;

                    R = 1 - C;
                    G = 1 - M;
                    B = 1 - Y;
                    
                    *curPos = (BYTE)(B*255);
                    *(curPos+1) = (BYTE)(G*255);
                    *(curPos+2) = (BYTE)(R*255);                       
                    *(curPos+3) = 255;                             

                    //Advance to next pixel
                    curPos = curPos + 4;
                }
                curPos += (cbStride - (width * 4));
            }
        }    
        return result;    
    }


    HRESULT CmykPixelFormatConverter::ConvertRgbToCmyk( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels)
    {
        HRESULT result = S_OK;
        
        //Sanity check
        WICPixelFormatGUID srcPixelFormat;
        bitmapSource->GetPixelFormat(&srcPixelFormat);
        if (srcPixelFormat != GUID_WICPixelFormat32bppBGRA)
        {
             result = E_UNEXPECTED;
             return result;
        }       

        if (SUCCEEDED(result))
        {
            result = bitmapSource->CopyPixels(prc, cbStride, cbPixelsSize, pbPixels);
        }
        //Since the two formats have same number of bytes, we will do an inplace conversion
        UINT width, height;
        if (prc == NULL)
        {
            if (SUCCEEDED(result))
            {
                result = bitmapSource->GetSize(&width, &height);
            }
        }else
        {
            width = prc->Width;
            height = prc->Height;
        }


        if (SUCCEEDED(result))
        {
            //Loop on the data and do the conversion
            BYTE *curPos = NULL;            
            curPos = pbPixels;
            for (int i = 0 ; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    float R, G ,B, A;
                    float C, M, Y, K;

                    
                    //Do the maths
                    A = *(curPos+3);
                    B = (*curPos)    * (A/255.0) / 255.0;
                    G = (*(curPos+1) * (A/255.0)) / 255.0;
                    R = (*(curPos+2) * (A/255.0)) / 255.0;      
                    

                    C = 1 - R;
                    M = 1 - G;
                    Y = 1 - B;
                    K = min(C,min(M, Y));
                    if (K >= 1)
                    {
                        C = 0;
                        M = 0;
                        Y = 0;                    
                    }
                    else
                    {
                    C = (C - K) / (1 - K);
                    M = (M - K) / (1 - K);
                    Y = (Y - K) / (1 - K);
                    }
     
                    *curPos = (BYTE)(K*100);
                    *(curPos+1) = (BYTE)(Y*100);
                    *(curPos+2) = (BYTE)(M*100);      
                    *(curPos+3) = (BYTE)(C*100);      
                       
                    //Advance to next pixel
                    curPos += 4;
                }
                curPos += (cbStride - (width * 4));
            }
        }
        return result;
       }

<|start_filename|>Data Binding/BindingToMethod/DoubleToString.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace BindingToMethod
{
    public class DoubleToString : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
            CultureInfo culture) => value?.ToString();

        public object ConvertBack(object value, Type targetType, object parameter,
            CultureInfo culture)
        {
            var strValue = value as string;
            if (strValue != null)
            {
                double result;
                var converted = double.TryParse(strValue, out result);
                if (converted)
                {
                    return result;
                }
            }
            return null;
        }
    }
}

<|start_filename|>Input and Commands/TouchKeyboard/TouchKBRegister/LotsOfStacking.xaml.cs<|end_filename|>
﻿using Microsoft.Windows.Input.TouchKeyboard;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace TouchKBRegister
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class LotsOfStacking : Window
    {
        public LotsOfStacking()
        {
            InitializeComponent();
        }
    }
}


<|start_filename|>Data Binding/DataBindingToStringFomat/ItemsForSale.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;

namespace DataBindingToStringFomat
{
    public class ItemsForSale : ObservableCollection<PurchaseItem>
    {
        public ItemsForSale()
        {
            Add((new PurchaseItem("Snowboard and bindings", 120, new DateTime(2009, 1, 1))));
            Add((new PurchaseItem("Inside C#, second edition", 10, new DateTime(2009, 2, 2))));
            Add((new PurchaseItem("Laptop - only 1 year old", 499.99, new DateTime(2009, 2, 28))));
            Add((new PurchaseItem("Set of 6 chairs", 120, new DateTime(2009, 2, 28))));
            Add((new PurchaseItem("My DVD Collection", 15, new DateTime(2009, 1, 1))));
            Add((new PurchaseItem("TV Drama Series", 39.985, new DateTime(2009, 1, 1))));
            Add((new PurchaseItem("Squash racket", 60, new DateTime(2009, 2, 28))));
        }
    }
}

<|start_filename|>Styles & Templates/FindingElementsInTemplates/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace FindingElementsInTemplates
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ControlTemplateFindElement(object sender, RoutedEventArgs e)
        {
            // Finding the grid that is generated by the ControlTemplate of the Button
            var gridInTemplate = (Grid) myButton1.Template.FindName("grid", myButton1);

            // Do something to the ControlTemplate-generated grid
            MessageBox.Show("The actual width of the grid in the ControlTemplate: "
                            + gridInTemplate.GetValue(ActualWidthProperty));
        }

        private void DataTemplateFindElement(object sender, RoutedEventArgs e)
        {
            // Getting the currently selected ListBoxItem
            // Note that the ListBox must have
            // IsSynchronizedWithCurrentItem set to True for this to work
            var myListBoxItem =
                (ListBoxItem) (myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));

            // Getting the ContentPresenter of myListBoxItem
            var myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

            // Finding textBlock from the DataTemplate that is set on that ContentPresenter
            var myDataTemplate = myContentPresenter.ContentTemplate;
            var myTextBlock = (TextBlock) myDataTemplate.FindName("textBlock", myContentPresenter);

            // Do something to the DataTemplate-generated TextBlock
            MessageBox.Show("The text of the TextBlock of the selected list item: "
                            + myTextBlock.Text);
        }

        private TChildItem FindVisualChild<TChildItem>(DependencyObject obj)
            where TChildItem : DependencyObject
        {
            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child is TChildItem)
                    return (TChildItem) child;
                var childOfChild = FindVisualChild<TChildItem>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
            return null;
        }
    }
}

<|start_filename|>Sample Applications/DataBindingDemo/DateConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace DataBindingDemo
{
    [ValueConversion(typeof (DateTime), typeof (string))]
    public class DateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var date = (DateTime) value;
            return date.ToShortDateString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var strValue = value.ToString();
            DateTime resultDateTime;
            if (DateTime.TryParse(strValue, out resultDateTime))
            {
                return resultDateTime;
            }
            return value;
        }
    }
}

<|start_filename|>Windows/WindowSizingOrder/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace WindowSizingOrder
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ShowWindowButton_Click(object sender, RoutedEventArgs e)
        {
            var sw = new SizingWindow();
            if (setWSCB.IsChecked == true)
                sw.WindowState = (WindowState) Enum.Parse(typeof (WindowState), wsLB.Text);
            if (setMinWidthCB.IsChecked == true)
                sw.MinWidth = double.Parse(minWidthTB.Text);
            if (setMinHeightCB.IsChecked == true)
                sw.MinHeight = double.Parse(minHeightTB.Text);
            if (setMaxWidthCB.IsChecked == true)
                sw.MaxWidth = double.Parse(maxWidthTB.Text);
            if (setMaxHeightCB.IsChecked == true)
                sw.MaxHeight = double.Parse(maxHeightTB.Text);
            if (setWidthCB.IsChecked == true)
                sw.Width = double.Parse(widthTB.Text);
            if (setHeightCB.IsChecked == true)
                sw.Height = double.Parse(heightTB.Text);
            if (setSTCCB.IsChecked == true)
                sw.SizeToContent = (SizeToContent) Enum.Parse(typeof (SizeToContent), stcLB.Text);
            sw.Show();
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/CannotDifferentiateException.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    [Serializable]
    public class CannotDifferentiateException : FunctionParserException
    {
        public CannotDifferentiateException(string msg) : base(msg)
        {
        }
    }
}

<|start_filename|>Sample Applications/DataBindingDemo/Bid.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DataBindingDemo
{
    public class Bid
    {
        public Bid(int amount, User bidder)
        {
            Amount = amount;
            Bidder = bidder;
        }

        #region Property Getters and Setters

        public int Amount { get; }

        public User Bidder { get; }

        #endregion
    }
}

<|start_filename|>Input and Commands/CaptureUnCaptureMouse/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace CaptureUnCaptureMouse
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _changeColorOnMouseWheel;
        private IInputElement _elementToCapture;
        //private fields
        private bool _enlargeOnMouseOver;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            // Set button1 as the first element to get Mouse Capture,
            // if the user does not specifiy a different Button.
            _elementToCapture = Button1;
        }

        private void OnCaptureMouseRequest(object sender, RoutedEventArgs e)
        {
            Mouse.Capture(_elementToCapture);
        }

        private void OnUnCaptureMouseRequest(object sender, RoutedEventArgs e)
        {
            // To release mouse capture, pass null to Mouse.Capture.
            Mouse.Capture(null);
        }

        // GotMouseCapture event handler
        // MouseEventArgs.source is the element that has mouse capture
        private void ButtonGotMouseCapture(object sender, MouseEventArgs e)
        {
            var source = e.Source as Button;

            if (source != null)
            {
                // Update the Label that displays the sample results.
                lblHasMouseCapture.Content = source.Name;
            }
            // Another way to get the element with Mouse Capture
            // is to use the static Mouse.Captured property.
            else
            {
                // Mouse.Capture returns an IInputElement.
                IInputElement captureElement;

                captureElement = Mouse.Captured;

                // Update the Label that displays the element with mouse capture.
                lblHasMouseCapture.Content = captureElement.ToString();
            }
        }

        private void ButtonLostMouseCapture(object sender, MouseEventArgs e)
        {
            var source = e.Source as Button;

            if (source != null)
            {
                lblHasMouseCapture.Content = "";
            }
        }

        //***********************************************************
        //The rest of these methods are event handlers and methods  
        //used by the sample to process sample information.
        //***********************************************************
        private void OnButtonMouseEnter(object sender, RoutedEventArgs e)
        {
            var source = e.Source as Button;

            if (_enlargeOnMouseOver)
            {
                if (source != null)
                {
                    source.Height += 15;
                    source.Width += 15;
                }
            }
        }

        private void ButtonMouseClick(object sender, RoutedEventArgs e)
        {
            var source = e.Source as Button;

            if (source != null)
            {
                lblMouseClick.Content = source.Name;
            }
        }

        private void ButtonPreviewMouseDown(object sender, MouseEventArgs e)
        {
            var source = e.Source as Button;

            if (source != null)
            {
                lblLastMouseDown.Content = source.Name;
            }
        }

        private void ButtonPreviewMouseUp(object sender, MouseEventArgs e)
        {
            var source = e.Source as Button;

            if (source != null)
            {
                lblLastMouseUp.Content = source.Name;
            }
        }

        private void OnButtonMouseLeave(object sender, RoutedEventArgs e)
        {
            var source = e.Source as Button;

            if (_enlargeOnMouseOver)
            {
                if (source != null)
                {
                    source.Height -= 15;
                    source.Width -= 15;
                }
            }
        }

        private void OnButtonMouseWheel(object sender, MouseWheelEventArgs e)
        {
            var source = e.Source as Button;

            if (_changeColorOnMouseWheel)
            {
                if (source != null)
                {
                    source.Background = source.Background == Brushes.AliceBlue ? Brushes.Gold : Brushes.AliceBlue;
                }
            }
        }

        private void OnRadioButtonSelected(object sender, RoutedEventArgs e)
        {
            var source = e.Source as RadioButton;

            if (source != null)
            {
                switch (source.Content.ToString())
                {
                    case "1":
                        _elementToCapture = Button1;
                        break;
                    case "2":
                        _elementToCapture = Button2;
                        break;
                    case "3":
                        _elementToCapture = Button3;
                        break;
                    case "4":
                        _elementToCapture = Button4;
                        break;
                }
            }
        }

        private void MouseOverChecked(object sender, RoutedEventArgs e)
        {
            _enlargeOnMouseOver = true;
        }

        private void MouseOverUnChecked(object sender, RoutedEventArgs e)
        {
            _enlargeOnMouseOver = false;
        }

        private void MouseWheelChecked(object sender, RoutedEventArgs e)
        {
            _changeColorOnMouseWheel = true;
        }

        private void MouseWheelUnChecked(object sender, RoutedEventArgs e)
        {
            _changeColorOnMouseWheel = false;
        }
    }
}

<|start_filename|>Accessibility/Highlighter/HighlightRectangle.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Drawing;
using System.Windows.Forms;

namespace Highlighter
{
    internal class HighlightRectangle
    {
        #region Constructor

        /// <summary>
        ///     Constructor.
        /// </summary>
        /// <remarks>
        ///     Creates each side of the highlight rectangle as a form, so that
        ///     drawing and erasing are handled automatically.
        /// </remarks>
        public HighlightRectangle()
        {
            // Construct the rectangle and set some values.
            _highlightShown = false;
            _highlightLineWidth = 3;
            _leftForm = new Form();
            _topForm = new Form();
            _rightForm = new Form();
            _bottomForm = new Form();
            Form[] forms = {_leftForm, _topForm, _rightForm, _bottomForm};
            foreach (var form in forms)
            {
                form.FormBorderStyle = FormBorderStyle.None;
                form.ShowInTaskbar = false;
                form.TopMost = true;
                form.Visible = false;
                form.Left = 0;
                form.Top = 0;
                form.Width = 1;
                form.Height = 1;
                form.BackColor = Color.Red;

                // Make it a tool window so it doesn't show up with Alt+Tab.
                var style = NativeMethods.GetWindowLong(
                    form.Handle, NativeMethods.GwlExstyle);
                NativeMethods.SetWindowLong(
                    form.Handle, NativeMethods.GwlExstyle,
                    style | NativeMethods.WsExToolwindow);
            }
        }

        #endregion

        #region Private Fields

        private bool _highlightShown;
        private readonly int _highlightLineWidth;
        private Rectangle _highlightLocation;

        private readonly Form _leftForm;
        private readonly Form _topForm;
        private readonly Form _rightForm;
        private readonly Form _bottomForm;

        #endregion

        #region Public Properties

        /// <summary>
        ///     Sets the visible state of the rectangle.
        /// </summary>
        /// <remarks>
        ///     The Layout method is called by using BeginInvoke, to prevent
        ///     cross-thread updates to the UI. This method can be called on
        ///     any form that belongs to the UI thread.
        /// </remarks>
        public bool Visible
        {
            set
            {
                if (_highlightShown != value)
                {
                    _highlightShown = value;
                    if (_highlightShown)
                    {
                        var mi = new MethodInvoker(Layout);
                        _leftForm.BeginInvoke(mi);
                        mi = ShowRectangle;
                        _leftForm.BeginInvoke(mi);
                    }
                    else
                    {
                        var mi = new MethodInvoker(HideRectangle);
                        _leftForm.BeginInvoke(mi);
                    }
                }
            }
        }

        /// <summary>
        ///     Sets the location of the highlight.
        /// </summary>
        public Rectangle Location
        {
            set
            {
                _highlightLocation = value;
                var mi = new MethodInvoker(Layout);
                _leftForm.BeginInvoke(mi);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        ///     Shows or hides the rectangle.
        /// </summary>
        /// <param name="show">true to show, false to hide.</param>
        private void Show(bool show)
        {
            if (show)
            {
                NativeMethods.ShowWindow(_leftForm.Handle, NativeMethods.SwShowna);
                NativeMethods.ShowWindow(_topForm.Handle, NativeMethods.SwShowna);
                NativeMethods.ShowWindow(_rightForm.Handle, NativeMethods.SwShowna);
                NativeMethods.ShowWindow(_bottomForm.Handle, NativeMethods.SwShowna);
            }
            else
            {
                _leftForm.Hide();
                _topForm.Hide();
                _rightForm.Hide();
                _bottomForm.Hide();
            }
        }

        /// <summary>
        ///     Shows the highlight.
        /// </summary>
        /// <remarks> Parameterless method for MethodInvoker.</remarks>
        private void ShowRectangle()
        {
            Show(true);
        }

        /// <summary>
        ///     Hides the highlight.
        /// </summary>
        /// <remarks> Parameterless method for MethodInvoker.</remarks>
        private void HideRectangle()
        {
            Show(false);
        }

        /// <summary>
        ///     Sets the position and size of the four forms that make up the rectangle.
        /// </summary>
        /// <remarks>
        ///     Use the Win32 SetWindowPosfunction so that SWP_NOACTIVATE can be set.
        ///     This ensures that the windows are shown without receiving the focus.
        /// </remarks>
        private void Layout()
        {
            // Use SetWindowPos instead of changing the location via form properties: 
            // this allows us to also specify HWND_TOPMOST. 
            // Using Form.TopMost = true to do this has the side-effect
            // of activating the rectangle windows, causing them to gain the focus.
            NativeMethods.SetWindowPos(_leftForm.Handle, NativeMethods.HwndTopmost,
                _highlightLocation.Left - _highlightLineWidth,
                _highlightLocation.Top,
                _highlightLineWidth, _highlightLocation.Height,
                NativeMethods.SwpNoactivate);
            NativeMethods.SetWindowPos(_topForm.Handle, NativeMethods.HwndTopmost,
                _highlightLocation.Left - _highlightLineWidth,
                _highlightLocation.Top - _highlightLineWidth,
                _highlightLocation.Width + 2*_highlightLineWidth,
                _highlightLineWidth,
                NativeMethods.SwpNoactivate);
            NativeMethods.SetWindowPos(_rightForm.Handle, NativeMethods.HwndTopmost,
                _highlightLocation.Left + _highlightLocation.Width,
                _highlightLocation.Top, _highlightLineWidth,
                _highlightLocation.Height,
                NativeMethods.SwpNoactivate);
            NativeMethods.SetWindowPos(_bottomForm.Handle, NativeMethods.HwndTopmost,
                _highlightLocation.Left - _highlightLineWidth,
                _highlightLocation.Top + _highlightLocation.Height,
                _highlightLocation.Width + 2*_highlightLineWidth,
                _highlightLineWidth,
                NativeMethods.SwpNoactivate);
        }

        #endregion
    } // class
} // namespace

<|start_filename|>Data Binding/ADODataSet/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows;

namespace ADODataSet
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string _appPath;
        private DataSet _myDataSet;

        public MainWindow()
        {
            InitializeComponent();
        }

        private string AppDataPath
        {
            get
            {
                if (string.IsNullOrEmpty(_appPath))
                {
                    _appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                }
                return _appPath;
            }
        }

        private void OnInit(object sender, EventArgs e)
        {
            var mdbFile = Path.Combine(AppDataPath, "BookData.mdb");
            string connString = $"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={mdbFile}";
            var conn = new OleDbConnection(connString);
            var adapter = new OleDbDataAdapter("SELECT * FROM BookTable;", conn);

            _myDataSet = new DataSet();
            adapter.Fill(_myDataSet, "BookTable");

            // myListBox is a ListBox control.
            // Set the DataContext of the ListBox to myDataSet
            myListBox.DataContext = _myDataSet;
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            var myDataTable = _myDataSet.Tables["BookTable"];
            var row = myDataTable.NewRow();

            row["Title"] = "Microsoft C# Language Specifications";
            row["ISBN"] = "0-7356-1448-2";
            row["NumPages"] = 431;
            myDataTable.Rows.Add(row);
        }
    }
}

<|start_filename|>Data Binding/DataTemplatingIntro/TaskListDataTemplateSelector.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace DataTemplatingIntro
{
    public class TaskListDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate
            SelectTemplate(object item, DependencyObject container)
        {
            if (item != null && item is Task)
            {
                var taskitem = (Task) item;
                var window = Application.Current.MainWindow;
                if (taskitem.Priority == 1)
                    return
                        window.FindResource("ImportantTaskTemplate") as DataTemplate;
                return
                    window.FindResource("MyTaskTemplate") as DataTemplate;
            }

            return null;
        }
    }
}

<|start_filename|>Animation/LocalAnimations/InteractiveAnimationExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace LocalAnimations
{
    // Create the demonstration.
    public class InteractiveAnimationExample : Page
    {
        private readonly Border _containerBorder;
        private readonly Ellipse _interactiveEllipse;
        private readonly TranslateTransform _interactiveTranslateTransform;

        public InteractiveAnimationExample()
        {
            WindowTitle = "Interactive Animation Example";
            var myPanel = new DockPanel {Margin = new Thickness(20.0)};

            _containerBorder = new Border
            {
                Background = Brushes.White,
                BorderBrush = Brushes.Black,
                BorderThickness = new Thickness(2.0),
                VerticalAlignment = VerticalAlignment.Stretch
            };

            _interactiveEllipse = new Ellipse
            {
                Fill = Brushes.Lime,
                Stroke = Brushes.Black,
                StrokeThickness = 2.0,
                Width = 25,
                Height = 25,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top
            };

            _interactiveTranslateTransform = new TranslateTransform();
            _interactiveEllipse.RenderTransform =
                _interactiveTranslateTransform;

            _containerBorder.MouseLeftButtonDown +=
                border_mouseLeftButtonDown;
            _containerBorder.MouseRightButtonDown +=
                border_mouseRightButtonDown;

            _containerBorder.Child = _interactiveEllipse;
            myPanel.Children.Add(_containerBorder);
            Content = myPanel;
        }

        // When the user left-clicks, use the 
        // SnapshotAndReplace HandoffBehavior when applying the animation.        
        private void border_mouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var clickPoint = Mouse.GetPosition(_containerBorder);

            // Set the target point so the center of the ellipse
            // ends up at the clicked point.
            var targetPoint = new Point
            {
                X = clickPoint.X - _interactiveEllipse.Width/2,
                Y = clickPoint.Y - _interactiveEllipse.Height/2
            };

            // Animate to the target point.
            var xAnimation =
                new DoubleAnimation(targetPoint.X,
                    new Duration(TimeSpan.FromSeconds(4)));
            _interactiveTranslateTransform.BeginAnimation(
                TranslateTransform.XProperty, xAnimation, HandoffBehavior.SnapshotAndReplace);

            var yAnimation =
                new DoubleAnimation(targetPoint.Y,
                    new Duration(TimeSpan.FromSeconds(4)));
            _interactiveTranslateTransform.BeginAnimation(
                TranslateTransform.YProperty, yAnimation, HandoffBehavior.SnapshotAndReplace);

            // Change the color of the ellipse.
            _interactiveEllipse.Fill = Brushes.Lime;
        }

        // When the user right-clicks, use the 
        // Compose HandoffBehavior when applying the animation.
        private void border_mouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Find the point where the use clicked.
            var clickPoint = Mouse.GetPosition(_containerBorder);

            // Set the target point so the center of the ellipse
            // ends up at the clicked point.
            var targetPoint = new Point
            {
                X = clickPoint.X - _interactiveEllipse.Width/2,
                Y = clickPoint.Y - _interactiveEllipse.Height/2
            };


            // Animate to the target point.
            var xAnimation =
                new DoubleAnimation(targetPoint.X,
                    new Duration(TimeSpan.FromSeconds(4)));
            _interactiveTranslateTransform.BeginAnimation(
                TranslateTransform.XProperty, xAnimation, HandoffBehavior.Compose);

            var yAnimation =
                new DoubleAnimation(targetPoint.Y,
                    new Duration(TimeSpan.FromSeconds(4)));
            _interactiveTranslateTransform.BeginAnimation(
                TranslateTransform.YProperty, yAnimation, HandoffBehavior.Compose);

            // Change the color of the ellipse.
            _interactiveEllipse.Fill = Brushes.Orange;
        }
    }
}

<|start_filename|>Windows/Wizard/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace Wizard
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void RunWizardButton_Click(object sender, RoutedEventArgs e)
        {
            var wizard = new WizardDialogBox();
            var showDialog = wizard.ShowDialog();
            var dialogResult = showDialog != null && (bool) showDialog;
            MessageBox.Show(
                dialogResult
                    ? $"{wizard.WizardData.DataItem1}\n{wizard.WizardData.DataItem2}\n{wizard.WizardData.DataItem3}"
                    : "Canceled.");
        }
    }
}

<|start_filename|>Documents/Fixed Documents/DocumentStructure/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;

namespace DocumentStructure
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region constructor

        // ------------------------ Window1 constructor -----------------------
        public MainWindow()
        {
            InitializeComponent();

            ShowPrompt("Click 'File | Open...' and select the file " +
                       "'Spec_withoutStructure.xps'.");
            ShowDescription(DescriptionString[0]);
        }

        #endregion constructor

        #region File|Exit

        // ------------------------------ OnExit ------------------------------
        /// <summary>
        ///     Handles the user File|Exit menu selection to
        ///     shutdown and exit the application.
        /// </summary>
        private void OnExit(object sender, EventArgs e)
        {
            Close(); // invokes OnClosed()
        } // end:OnExit()

        #endregion File|Exit

        #region File|Open...

        // ------------------------------ OnOpen ------------------------------
        /// <summary>
        ///     Handles the user "File | Open" menu operation.
        /// </summary>
        private void OnOpen(object target, ExecutedRoutedEventArgs args)
        {
            // Create a "File Open" dialog positioned to the
            // "Content\" folder containing the sample fixed document.
            var dialog = new OpenFileDialog
            {
                InitialDirectory = GetContentFolder(),
                CheckFileExists = true,
                Filter = "XPS Document files (*.xps)|*.xps|All (*.*)|*.*"
            };

            // Show the "File Open" dialog.  If the user picks a file and
            // clicks "OK", load and display the specified XPS document.
            if (dialog.ShowDialog() != true) return;

            // If the file is an XPS document, open it in the DocumentViewer.
            if (dialog.FileName.EndsWith(".xps"))
                OpenDocument(dialog.FileName);

            // If the file is a text document, show it in the desciption block.
            else if (dialog.FileName.EndsWith(".xaml")
                     || dialog.FileName.EndsWith(".xml")
                     || dialog.FileName.EndsWith(".txt"))
            {
                using (var sr = new StreamReader(dialog.FileName))
                {
                    ShowDescriptionTitle(Filename(dialog.FileName));
                    ShowDescription(sr.ReadToEnd(), TextWrapping.NoWrap);
                } // end:using StreamReader(flush and close)
                ShowPrompt("");
            }
        } // end:OnOpen()


        // --------------------------- OpenDocument ---------------------------
        /// <summary>
        ///     Opens a specified XPS document in given access mode.
        /// </summary>
        /// <param name="xpsFile">
        ///     The path and file name of the XPS document to open.
        /// </param>
        private bool OpenDocument(string xpsFile)
        {
            // Close the XpsDocument if it is currently open.
            if (_xpsDocument != null) CloseDocument();

            // Load and create an in-memory instance of the XPS document.
            ShowStatus("Opening '" + Filename(xpsFile) + "'.");
            _xpsDocument = new XpsDocument(xpsFile, FileAccess.Read);

            // Get the FixedDocumentSequence from the XPS document.
            var fds = _xpsDocument.GetFixedDocumentSequence();
            if (fds == null)
            {
                var msg = xpsFile +
                          "\n\nThe document package within the specified " +
                          "file does not contain a FixedDocumentSequence.";
                MessageBox.Show(msg, "Package Error");
                return false;
            }

            // Load the FixedDocumentSequence to the DocumentViewer control.
            DocViewer.Document = fds;

            var filename = Filename(xpsFile).ToLower();
            if (filename.Equals("spec_withoutstructure.xps"))
            {
                ShowPrompt("Click 'File | Open...' and select the file " +
                           "'Spec_withStructure.xps'.");
                ShowDescription(DescriptionString[2]);
            }
            else if (filename.Equals("spec_withstructure.xps"))
            {
                ShowPrompt("Click 'File | Add Structure...'.");
                ShowDescription(DescriptionString[3] + DescriptionString[4]);
            }
            else
            {
                ShowPrompt("");
            }

            _openedXpsFile = xpsFile;
            menuFileClose.IsEnabled = true;
            menuFilePrint.IsEnabled = true;
            descriptionBlockTitle.Text = "Description";
            Title = "DocumentStructure Sample - " + Filename(xpsFile);
            return true;
        } // OpenDocument()

        #endregion File|Open...

        #region File|Close

        // ----------------------------- OnClosed -----------------------------
        /// <summary>
        ///     Performs clean up when the application is closed.
        /// </summary>
        private void OnClosed(object sender, EventArgs e)
        {
            CloseDocument();
        } // end:OnClosed()


        // ----------------------------- OnClose ------------------------------
        /// <summary>
        ///     Handles the user "File | Close" menu operation
        ///     to close the currently open document.
        /// </summary>
        private void OnClose(object target, ExecutedRoutedEventArgs args)
        {
            CloseDocument();
        } // end:OnClose()


        // -------------------------- CloseDocument ---------------------------
        /// <summary>
        ///     Closes the document if its open.
        /// </summary>
        private void CloseDocument()
        {
            if (_xpsDocument != null)
            {
                ShowStatus("Closing '" + Filename(_openedXpsFile) + "'.");
                _xpsDocument.Close();
                _xpsDocument = null;
                _openedXpsFile = null;
                DocViewer.Document = null;
            }

            ShowPrompt("Click 'File | Open...' and select the file " +
                       "'Spec_withoutStructure.xps'.");
            ShowDescription(DescriptionString[0]);
            menuFilePrint.IsEnabled = false;
            menuFileClose.IsEnabled = false;
            Title = "DocumentStructure Sample";
        } // end:CloseDocument

        #endregion File|Close

        #region File|Add Structure...

        // -------------------------- OnAddStructure --------------------------
        /// <summary>
        ///     Handles the user File|Add Structure... menu option to
        ///     add structure elements to an unstructured XPS document.
        /// </summary>
        private void OnAddStructure(object sender, EventArgs e)
        {
            /*-----
            // Create a "File Open" dialog positioned to the
            // "Content\" folder containing the sample XPS documents.
            WinForms.OpenFileDialog openDialog = new WinForms.OpenFileDialog();
            openDialog.InitialDirectory = GetContentFolder();
            openDialog.Title = "Source Unstructured XPS Document";
            openDialog.CheckFileExists = true;
            openDialog.Filter = "XPS Documents " +
                "(*_withoutStructure.xps)|*_withoutStructure.xps|All (*.*)|*.*";

            // Show the "File Open" dialog.  If the user picks a file and
            // clicks "OK", set it as the XPS unstructured file.
            if (openDialog.ShowDialog() != true)  return;
            string xpsUnstructuredFile = openDialog.FileName;
            -----*/
            // For the sample, always use "Spec_withoutStructure.xps"
            // as the source unstructured document file.
            var xpsUnstructuredFile = GetContentFolder() +
                                      "\\Spec_withoutStructure.xps";

            // Create a "File Save" dialog positioned to the
            // "Content\" folder to write the new structured document to.
            var saveDialog = new SaveFileDialog
            {
                OverwritePrompt = false,
                InitialDirectory = GetContentFolder(),
                Title = "Save New Structured XPS Document As",
                Filter = "XPS Documents (*.xps)|*.xps|All (*.*)|*.*",
                FileName = GetContentFolder() + @"\Structured.xps"
            };

            // Set a default XPS document filename.

            // Show the "File Save" dialog.  If the user picks a file and
            // clicks "OK", set it as the target ouput XPS structured file.
            if (saveDialog.ShowDialog() != true) return;
            var xpsTargetFile = saveDialog.FileName;

            // Add the document structure resource elements
            // to create a new structured XPS document.
            AddDocumentStructure(xpsUnstructuredFile, // source unstructured doc
                FixedPageStructures, // structure definitions
                xpsTargetFile); // target structured doc
        } // end:OnAddStructure()


        // ----------------------- AddDocumentStructure -----------------------
        /// <summary>
        ///     Writes a structured XPS document given an unstructured document
        ///     and a file list of XAML document structure elements to add.
        /// </summary>
        /// <param name="xpsUnstructuredFile">
        ///     The path and filename of the unstructured XPS document.
        /// </param>
        /// <param name="xamlStructureFile">
        ///     A file list of XAML document structures to add.
        /// </param>
        /// <param name="xpsTargetFile">
        ///     The path and filename for the new structured
        ///     XPS document to write.
        /// </param>
        /// <remarks>
        ///     If xpsTargetFile exists, it is first deleted and
        ///     then a new structured XPS document written.
        /// </remarks>
        private void AddDocumentStructure(
            string xpsUnstructuredFile, // source unstructured document
            string[] xamlStructureFile, // structure definition resources
            string xpsTargetFile) // target structured XPS document
        {
            // Close the current document if one is open.
            CloseDocument();

            ShowStatus("\nCreating new structured XPS\n       " +
                       "document '" + Filename(xpsTargetFile) + "'.");

            // If the new target XPS file exists, prompt to confirm ok to replace.
            if (File.Exists(xpsTargetFile))
            {
                var result = MessageBox.Show("'" + xpsTargetFile +
                                             "' already exists.\nDo you want to delete and replace it?",
                    "Ok to replace '" + Filename(xpsTargetFile) + "'?",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result != MessageBoxResult.Yes) return;
                ShowStatus("   Deleting old '" +
                           Filename(xpsTargetFile) + "'.");
                File.Delete(xpsTargetFile);
            }

            ShowStatus("   Copying '" + Filename(xpsUnstructuredFile) +
                       "'\n       to '" + Filename(xpsTargetFile) + "'.");
            File.Copy(xpsUnstructuredFile, xpsTargetFile);

            ShowStatus("   Opening '" + Filename(xpsTargetFile) +
                       "'\n       (currently without structure).");
            XpsDocument xpsDocument = null;
            try
            {
                xpsDocument =
                    new XpsDocument(xpsTargetFile, FileAccess.ReadWrite);
            }
            catch (FileFormatException)
            {
                var msg = xpsUnstructuredFile + "\n\nThe specified file " +
                          "does not appear to be a valid XPS document.";
                MessageBox.Show(msg, "Invalid File Format",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                ShowStatus("   Invalid XPS document format.");
                return;
            }

            ShowStatus("   Getting FixedDocumentSequenceReader.");
            var fixedDocSeqReader =
                xpsDocument.FixedDocumentSequenceReader;

            ShowStatus("   Getting FixedDocumentReaders.");
            ICollection<IXpsFixedDocumentReader> fixedDocuments =
                fixedDocSeqReader.FixedDocuments;

            ShowStatus("   Getting FixedPageReaders.");
            var enumerator =
                fixedDocuments.GetEnumerator();
            enumerator.MoveNext();
            ICollection<IXpsFixedPageReader> fixedPages =
                enumerator.Current.FixedPages;


            // Add a document structure to each fixed page.
            var i = 0;
            foreach (var fixedPageReader in fixedPages)
            {
                XpsResource pageStructure;
                ShowStatus("   Adding page structure resource:\n       '" +
                           Filename(FixedPageStructures[i]) + "'");
                try
                {
                    // Add a new StoryFragment to hold the page structure.
                    pageStructure = fixedPageReader.AddStoryFragment();
                }
                catch (InvalidOperationException)
                {
                    MessageBox.Show(xpsUnstructuredFile +
                                    "\n\nDocument structure cannot be added.\n\n" +
                                    Filename(xpsUnstructuredFile) + " might already " +
                                    "contain an existing document structure.",
                        "Cannot Add Document Structure",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    break;
                }

                // Copy the page structure to the new StoryFragment.
                WriteResource(pageStructure, FixedPageStructures[i++]);
            }

            ShowStatus("   Saving and closing the new document.\n");
            xpsDocument.Close();

            // Open the new structured document.
            OpenDocument(xpsTargetFile);

            ShowDescription(DescriptionString[4] + DescriptionString[5]);
            ShowPrompt(DescriptionString[5]);
        } // end:AddDocumentStructure

        #endregion File|Add Structure...

        #region File|Print

        // ----------------------------- OnPrint ------------------------------
        /// <summary>
        ///     Handles the user "File | Print" menu operation.
        /// </summary>
        private void OnPrint(object target, ExecutedRoutedEventArgs args)
        {
            PrintDocument();
        } // end:OnClose()


        // -------------------------- PrintDocument ---------------------------
        /// <summary>
        ///     Prints the DocumentViewer's content and annotations.
        /// </summary>
        public void PrintDocument()
        {
            DocViewer?.Print();
        } // end:PrintDocument()

        #endregion File|Print

        #region Utilities

        // ------------------------- GetContentFolder -------------------------
        /// <summary>
        ///     Locates and returns the path to the "Content\" folder
        ///     containing the content files for the sample.
        /// </summary>
        /// <returns>
        ///     The path to the sample "Content\" folder.
        /// </returns>
        public string GetContentFolder()
        {
            // Get the path to the current directory and its length.
            var contentDir = Directory.GetCurrentDirectory();
            var dirLength = contentDir.Length;

            // If we're in "...\bin\debug", move up to the root.
            if (contentDir.ToLower().EndsWith(@"\bin\debug"))
                contentDir = contentDir.Remove(dirLength - 10, 10);

            // If we're in "...\bin\release", move up to the root.
            else if (contentDir.ToLower().EndsWith(@"\bin\release"))
                contentDir = contentDir.Remove(dirLength - 12, 12);

            // If there's a "Content" subfolder, that's what we want.
            if (Directory.Exists(contentDir + @"\Content"))
                contentDir = contentDir + @"\Content";

            // Return the "Content\" folder (or the "current"
            // directory if we're executing somewhere else).
            return contentDir;
        } // end:GetContentFolder()


        // -------------------------- WriteResource ---------------------------
        private void WriteResource(XpsResource resource, string filename)
        {
            WriteStream(resource.GetStream(), filename);
        }


        // --------------------------- WriteStream ----------------------------
        private void WriteStream(Stream stream, string filename)
        {
            var srcStream = new FileStream(
                filename, FileMode.Open, FileAccess.Read, FileShare.Read);

            var buf = new byte[65536];
            int bytesRead;

            do
            {
                bytesRead = srcStream.Read(buf, 0, 65536);
                stream.Write(buf, 0, bytesRead);
            } while (bytesRead > 0);

            srcStream.Close();
        } // end:WriteStream()


        // ------------------------- ShowPrompt(string) -----------------------
        /// <summary>
        ///     Writes a line of text to the prompt bar.
        /// </summary>
        /// <param name="prompt">
        ///     The line of text to write in the prompt bar.
        /// </param>
        public void ShowPrompt(string prompt)
        {
            promptBlock.Text = prompt;
        }


        // ---------------------------- ShowStatus ----------------------------
        /// <summary>
        ///     Adds a line of text to the statusBlock.
        /// </summary>
        /// <param name="status">
        ///     A line of text to add to the status TextBlock.
        /// </param>
        public void ShowStatus(string status)
        {
            statusBlock.Text += status + "\n";
        }


        // ------------------------- ShowDescription -------------------------
        /// <summary>
        ///     Displays a string of text to the description block.
        /// </summary>
        public void ShowDescription(string description)
        {
            descriptionBlock.Text = description;
            descriptionBlock.TextWrapping = TextWrapping.Wrap;
        }


        // ------------------------- ShowDescription -------------------------
        /// <summary>
        ///     Displays a string of text to the description block.
        /// </summary>
        public void ShowDescription(string description, TextWrapping wrapStyle)
        {
            descriptionBlock.Text = description;
            descriptionBlock.TextWrapping = wrapStyle;
        }


        // ----------------------- ShowDescriptionTitle -----------------------
        /// <summary>
        ///     Displays a string of text in the description title block.
        /// </summary>
        public void ShowDescriptionTitle(string title)
        {
            descriptionBlockTitle.Text = title;
        }


        // ------------------------------ Filename ----------------------------
        /// <summary>
        ///     Returns just the filename from a given path and filename.
        /// </summary>
        /// <param name="filepath">
        ///     A path and filename.
        /// </param>
        /// <returns>
        ///     The filename with extension.
        /// </returns>
        private static string Filename(string filepath)
        {
            // Locate the index of the last backslash.
            var slashIndex = filepath.LastIndexOf('\\');

            // If there is no backslash, return the original string.
            if (slashIndex < 0)
                return filepath;

            // Remove all the characters through the last backslash.
            return filepath.Remove(0, slashIndex + 1);
        }


        // ----------------------- DocViewer attribute ------------------------
        /// <summary>
        ///     Gets the current DocumentViewer.
        /// </summary>
        public DocumentViewer DocViewer => docViewer;

        #endregion Utilities

        #region Private Fields

        private string _openedXpsFile; // XPS document path & filename.
        private XpsDocument _xpsDocument; // current XpsDocument.

        // Document structure resource files.
        private static readonly string[] FixedPageStructures =
        {
            "FixedPage1_structure.xaml", // document structure elements, page 1
            "FixedPage2_structure.xaml" // document structure elements, page 2
        };

        // Description block text strings.
        private static readonly string[] DescriptionString =
        {
            //Step 0
            "The DocumentStructure example includes two sample XPS documents:\n" +
            "    1.  Spec_withoutStructure.xps\n" +
            "    2.  Spec_withStructure.xps\n\n" +
            "When you open each file note that the visual layout, " +
            "quality, and print output of both documents is exactly " +
            "the same - both documents fully conform to the open XML " +
            "Paper Specification (XPS).  Cutting and pasting information " +
            "from each document, however, is quite different.\n\nClick " +
            "'File | Open...', select the file " +
            "'Spec_withoutStructure.xps', and then click OK.",
            //Step 1
            "Click 'File | Open...', select the file " +
            "'Spec_withoutStructure.xps', and then click OK.",
            //Step 2
            "Within the 'Spec_withoutStructure.xps' document select a portion " +
            "of Table 1-1 and paste it into a blank Word or WordPad " +
            "document.  Notice that an XPS document without structure " +
            "elements pastes as plain text not as a formatted table.\n\n" +
            "Next click 'File | Open...' and select " +
            "'Spec_withStructure.xps'.",
            //Step 3
            "Select a portion of " +
            "Table 1-1 and paste it into the Word or WordPad document.  " +
            "Notice that a document with structure elements uses rich " +
            "text to paste the selection as styled table elements.\n\n" +
            "Next click 'File | Add Structure...'\n\n",
            //Step 4
            "The Add Structure process copies 'Spec_withoutStructure.xps' " +
            "to a new file and then programatically adds to the new " +
            "document the two structure elements contained in:\n    -  " +
            "FixedPage1_structure.xaml\n    -  FixedPage2_structure.xaml\n\n" +
            "The resulting new XPS document is equivalent " +
            "to 'Spec_withStructure.xps'.\n\n",
            //Step 5
            "Click 'File | Open...' and set 'Files of Type' to 'All' " +
            "to select a .xaml document structure resource file to view."
        };

        #endregion Private Fields
    }
}

<|start_filename|>Documents/Fixed Documents/DocumentMerge/PageItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Documents;
using System.Windows.Media;

namespace DocumentMerge
{
    internal class PageItem
    {
        public PageItem(PageContent pageContent)
        {
            PageContent = pageContent;
            FixedPage = PageContent.GetPageRoot(false);
            PageBrush = new VisualBrush(FixedPage);
        }

        public PageItem(PageItem pageItem)
        {
            PageContent = pageItem.PageContent;
            FixedPage = pageItem.FixedPage;
            PageBrush = new VisualBrush(FixedPage);
        }

        public Brush PageBrush { get; }
        public PageContent PageContent { get; }
        public FixedPage FixedPage { get; }

        #region private data

        #endregion private data
    }
}

<|start_filename|>Animation/AnimationExamples/Text/AnimatedParagraphExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace AnimationExamples
{
    public partial class AnimatedParagraphExample : Page
    {
        // Updates the center of the RotateTransform used to rotate
        // the TextBlock's characters.
        private void TextBlockSizeChanged(object sender, SizeChangedEventArgs args)
        {
            if (args != null && !args.NewSize.IsEmpty)
            {
                TextEffectRotateTransform.CenterX = args.NewSize.Width/2;
                TextEffectRotateTransform.CenterY = args.NewSize.Height/2;
            }
        }
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/Dialog.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace StickyNotesDemo
{
    public class Dialog : Window
    {
        public static Color[] ColorArray =
        {
            Colors.Silver, Colors.Violet, Colors.SkyBlue, Colors.LawnGreen, Colors.Yellow,
            Colors.OrangeRed, Colors.Purple, Colors.Red
        };

        public static SolidColorBrush[] ColorArrayForeground =
        {
            Brushes.Black, Brushes.Red, Brushes.Green, Brushes.Blue,
            Brushes.Brown, Brushes.DarkMagenta, Brushes.DarkSalmon, Brushes.Lime
        };

        private readonly TabControl _tabControl;

        public Dialog(DateTime noteAlarm, string loadedRepetition)
        {
            WindowStyle = WindowStyle.ToolWindow;
            Height = 350;
            Width = 600;
            Title = "Options";
            Background = Brushes.LemonChiffon;
            Alarm = noteAlarm;
            AlarmRepetition = loadedRepetition;

            var sp = new StackPanel();

            _tabControl = new TabControl
            {
                HorizontalContentAlignment = HorizontalAlignment.Left,
                Width = Width - 10,
                Height = Height - 60,
                Background = Brushes.Transparent
            };
            sp.Children.Add(_tabControl);

            var item1 = new TabItem();
            FirstTabColorSettings(item1);
            _tabControl.Items.Add(item1);

            var item2 = new TabItem();
            SecondTabMailSettings(item2);
            _tabControl.Items.Add(item2);

            var item3 = new TabItem();
            ThirdTabAlarmSettings(item3);
            _tabControl.Items.Add(item3);

            var ok = new Button
            {
                Content = "OK",
                HorizontalAlignment = HorizontalAlignment.Right
            };
            ok.Click += ok_Click;
            sp.Children.Add(ok);

            Content = sp;

            Show();

            SizeChanged += Dialog_SizeChanged;
        }

        public object[] PropertyArray { get; } = new object[10];
        public DateTime Alarm { get; private set; }
        public string AlarmRepetition { get; private set; } = "null";

        private void ThirdTabAlarmSettings(TabItem item)
        {
            item.Header = "Alarm Settings";
            var sp = new StackPanel {Background = Brushes.Transparent};


            var g = new Grid {Background = Brushes.Transparent};
            var rdef1 = new RowDefinition();
            var rdef2 = new RowDefinition();
            var rdef3 = new RowDefinition();
            g.RowDefinitions.Add(rdef1);
            g.RowDefinitions.Add(rdef2);
            g.RowDefinitions.Add(rdef3);

            var cd1 = new ColumnDefinition();
            var gdl = new GridLength(300);
            cd1.Width = gdl;
            var cd2 = new ColumnDefinition();
            g.ColumnDefinitions.Add(cd1);
            g.ColumnDefinitions.Add(cd2);


            var l1 = new Label
            {
                Background = sp.Background,
                Content = "Date (mm/dd/yyyy)"
            };


            var date = new TextBox
            {
                Text = "/2006",
                Name = "date"
            };
            //if (Alarm.CompareTo(DateTime.Now) >= 0)
            //{
            //    date.Text = Alarm.Date.ToShortDateString();
            //}

            if (AlarmRepetition.Contains("null"))
            {
                if ((Alarm.CompareTo(DateTime.Now) >= 0) ||
                    (((DateTime.Now.TimeOfDay.Hours - Alarm.TimeOfDay.Hours) < 8) &&
                     ((DateTime.Now.TimeOfDay.Hours - Alarm.TimeOfDay.Hours) >= 0)))
                {
                    date.Text = Alarm.Date.ToShortDateString();
                }
            }
            else
            {
                date.Text = Alarm.Date.ToShortDateString();
            }


            Grid.SetRow(l1, 0);
            Grid.SetColumn(l1, 0);
            Grid.SetRow(date, 0);
            Grid.SetColumn(date, 1);


            var l2 = new Label
            {
                Background = sp.Background,
                Content = "Time (hr:min:sec)"
            };

            var time = new TextBox
            {
                Text = "00:00:00",
                Name = "time"
            };

            if (AlarmRepetition.Contains("null"))
            {
                if ((Alarm.CompareTo(DateTime.Now) >= 0) ||
                    (((DateTime.Now.TimeOfDay.Hours - Alarm.TimeOfDay.Hours) < 8) &&
                     ((DateTime.Now.TimeOfDay.Hours - Alarm.TimeOfDay.Hours) >= 0)))
                {
                    time.Text = Alarm.TimeOfDay.ToString();
                }
            }
            else
            {
                time.Text = Alarm.TimeOfDay.ToString();
            }


            Grid.SetRow(l2, 1);
            Grid.SetColumn(l2, 0);
            Grid.SetRow(time, 1);
            Grid.SetColumn(time, 1);


            g.Children.Add(l1);
            g.Children.Add(date);
            g.Children.Add(l2);
            g.Children.Add(time);

            var l3 = new Label
            {
                Background = sp.Background,
                Content = "Repeat Every:"
            };

            var repeatNumber = new TextBox
            {
                Text = "0",
                Name = "repeat",
                MaxLength = 3
            };
            repeatNumber.TextChanged += repeatNumber_TextChanged;
            if (AlarmRepetition.Contains("null") == false)
            {
                repeatNumber.Text = AlarmRepetition.Substring(1);
            }

            var space = new Label
            {
                Background = sp.Background,
                Content = " "
            };

            var daysCheck = new CheckBox
            {
                IsChecked = false,
                VerticalAlignment = VerticalAlignment.Center,
                Name = "daysCheck"
            };
            daysCheck.Checked += daysCheck_Checked;


            var l4 = new Label
            {
                Background = sp.Background,
                Content = "Day(s)"
            };

            var space1 = new Label();
            space.Background = sp.Background;
            space.Content = " ";

            var weeksCheck = new CheckBox
            {
                IsChecked = false,
                VerticalAlignment = VerticalAlignment.Center,
                Name = "weeksCheck"
            };
            weeksCheck.Checked += weeksCheck_Checked;
            try
            {
                if (AlarmRepetition.Contains("null") == false)
                {
                    var charr = AlarmRepetition.ToCharArray(0, 1);
                    switch (charr[0])
                    {
                        case 'D':
                            daysCheck.IsChecked = true;
                            break;

                        case 'W':
                            weeksCheck.IsChecked = true;
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
            var l5 = new Label
            {
                Background = sp.Background,
                Content = "Week(s)"
            };

            var wp = new WrapPanel();
            wp.Children.Add(l3);
            wp.Children.Add(repeatNumber);
            wp.Children.Add(space);
            wp.Children.Add(daysCheck);
            wp.Children.Add(l4);
            wp.Children.Add(space1);
            wp.Children.Add(weeksCheck);
            wp.Children.Add(l5);


            var status = new Label
            {
                Background = sp.Background,
                Name = "statusThirdTab"
            };

            sp.Children.Add(g);
            sp.Children.Add(wp);
            sp.Children.Add(status);

            item.Content = sp;
        }

        private void repeatNumber_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                var l = LogicalTreeHelper.FindLogicalNode(this, "statusThirdTab") as Label;
                l.Content = "";
                var str = (sender as TextBox)?.Text;
                var charArr = str.ToCharArray();
                var val = charArr.All(t => (t >= '0') && (t <= '9'));
                if (val == false)
                {
                    l.Content = "Input should consist of only numbers";
                    l.Foreground = Brushes.Red;
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }

        private void daysCheck_Checked(object sender, RoutedEventArgs e)
        {
            var weeksCheck = LogicalTreeHelper.FindLogicalNode(this, "weeksCheck") as CheckBox;
            weeksCheck.IsChecked = false;
        }

        private void weeksCheck_Checked(object sender, RoutedEventArgs e)
        {
            var daysCheck = LogicalTreeHelper.FindLogicalNode(this, "daysCheck") as CheckBox;
            daysCheck.IsChecked = false;
        }

        private void SecondTabMailSettings(TabItem item)
        {
            item.Header = "Mail Settings";
            var item2Panel = new StackPanel();

            var l1 = new Label
            {
                Content = "SMTP Mail Server:",
                Background = Brushes.Transparent
            };

            var server = new TextBox
            {
                ToolTip = "smtp.gmail.com/smtp.mail.yahoo.com/smtp.aol.com/...",
                Name = "server"
            };

            var l2 = new Label
            {
                Content = "Mail Account",
                Background = Brushes.Transparent
            };

            var account = new TextBox
            {
                ToolTip = "Something like: <EMAIL>",
                Name = "account"
            };

            var l3 = new Label
            {
                Content = "Mail Account",
                Background = Brushes.Transparent
            };

            var port = new TextBox
            {
                ToolTip = "Port used: Usually 25",
                Text = "25",
                Name = "port"
            };

            var wp = new WrapPanel();
            var l4 = new Label
            {
                Content = "Use SSL",
                ToolTip = "Check if SMTP server uses SSL. (gmail uses, Yahoo/aol dont)",
                Background = Brushes.Transparent
            };

            var cb = new CheckBox
            {
                ToolTip = "Check if SMTP server uses SSL. (gmail uses, Yahoo/aol dont)",
                VerticalAlignment = VerticalAlignment.Center,
                Name = "sslCheck"
            };

            wp.Children.Add(l4);
            wp.Children.Add(cb);

            var l5 = new Label
            {
                Content = "",
                Background = Brushes.Transparent,
                Name = "status"
            };

            item2Panel.Children.Add(l1);
            item2Panel.Children.Add(server);
            item2Panel.Children.Add(l2);
            item2Panel.Children.Add(account);
            item2Panel.Children.Add(l3);
            item2Panel.Children.Add(port);
            item2Panel.Children.Add(wp);
            item2Panel.Children.Add(l5);


            item.Content = item2Panel;
        }

        private void FirstTabColorSettings(TabItem item)
        {
            item.Header = "Color Settings";
            var item1Panel = new StackPanel();
            var l1 = new Label
            {
                Content = "Background Color:",
                Background = Brushes.Transparent
            };

            var combo = new ComboBox();
            InitializeComboBox(combo);
            combo.SelectionChanged += combo_SelectionChanged;

            var l2 = new Label
            {
                Content = "Foreground Color:",
                Background = Brushes.Transparent
            };

            var combo1 = new ComboBox();
            InitializeComboBox1(combo1);
            combo1.SelectionChanged += combo1_SelectionChanged;

            item1Panel.Children.Add(l1);
            item1Panel.Children.Add(combo);
            item1Panel.Children.Add(l2);
            item1Panel.Children.Add(combo1);
            item1Panel.Background = Brushes.Transparent;

            item.Content = item1Panel;
        }

        private void combo1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = sender as ComboBox;
            var comboItem = cb.SelectedItem as ComboBoxItem;
            PropertyArray[(int) PropNames.ForegroundColor] = comboItem?.Tag;
        }

        private void ok_Click(object sender, RoutedEventArgs e)
        {
            var server = LogicalTreeHelper.FindLogicalNode(this, "server") as TextBox;
            var account = LogicalTreeHelper.FindLogicalNode(this, "account") as TextBox;
            var date = LogicalTreeHelper.FindLogicalNode(this, "date") as TextBox;
            var time = LogicalTreeHelper.FindLogicalNode(this, "time") as TextBox;
            var repeatNumber = LogicalTreeHelper.FindLogicalNode(this, "repeat") as TextBox;
            var daysCheck = LogicalTreeHelper.FindLogicalNode(this, "daysCheck") as CheckBox;
            var weeksCheck = LogicalTreeHelper.FindLogicalNode(this, "weeksCheck") as CheckBox;

            var str = (daysCheck.IsChecked == true) ? "D" : "";
            str += (weeksCheck.IsChecked == true) ? "W" : "";
            if (str != string.Empty)
            {
                str += repeatNumber.Text;
            }
            else
            {
                str = "null";
            }

            if ((date.Text != string.Empty) && (date.Text != "/2006") &&
                (!(date.Text.Contains(Alarm.Date.ToShortDateString()))
                 || !(AlarmRepetition.Contains(str)) ||
                 !(Alarm.TimeOfDay.ToString().Contains(time.Text))))
            {
                var dateString = date.Text;
                var arr = new int[3];
                var timeString = time.Text;
                var arr1 = new int[3];

                var tail = 0;
                var head = dateString.IndexOf('/');
                head = (head >= 0) ? head : 0;

                try
                {
                    for (var i = 0; i < 3; i++)
                    {
                        head = (i == (arr.Length - 1)) ? (dateString.Length) : head;
                        arr[i] = int.Parse(dateString.Substring(tail, head - tail));
                        if (head == dateString.Length)
                        {
                            break;
                        }
                        tail = head + 1;
                        head = dateString.IndexOf('/', tail);
                    }
                    tail = 0;
                    head = timeString.IndexOf(':');
                    head = (head >= 0) ? head : 0;
                    for (var i = 0; i < 3; i++)
                    {
                        head = (i == (arr1.Length - 1)) ? (timeString.Length) : head;
                        arr1[i] = int.Parse(timeString.Substring(tail, head - tail));
                        if (head == timeString.Length)
                        {
                            break;
                        }
                        tail = head + 1;
                        head = timeString.IndexOf(':', tail);
                    }

                    var dt = new DateTime(arr[2], arr[0], arr[1], arr1[0], arr1[1], arr1[2]);
                    if (dt.CompareTo(DateTime.Now) >= 0)
                    {
                        Alarm = dt;
                        PropertyArray[(int) PropNames.Alarm] = dt;
                        if (repeatNumber.Text != string.Empty)
                        {
                            AlarmRepetition = (daysCheck.IsChecked == true) ? "D" : "";
                            AlarmRepetition += (weeksCheck.IsChecked == true) ? "W" : "";
                            if (AlarmRepetition != string.Empty)
                            {
                                AlarmRepetition += repeatNumber.Text;
                            }
                            else
                            {
                                AlarmRepetition = "null";
                            }
                        }
                        Tag = "OK";
                        Close();
                    }
                    else
                    {
                        Title = "AlarmSettings Error";
                        var l = LogicalTreeHelper.FindLogicalNode(this, "statusThirdTab") as Label;
                        l.Content = "Alarm can be set if the event is after Current time";
                        l.Foreground = Brushes.Red;
                    }
                }
                catch (Exception e1)
                {
                    var l = LogicalTreeHelper.FindLogicalNode(this, "statusThirdTab") as Label;
                    l.Content = e1.Message;
                    l.Foreground = Brushes.Red;
                    Title = "AlarmSettings Error";
                }
            }
            else
            {
                if (((server.Text == string.Empty) && (account.Text == string.Empty)) ||
                    ((server.Text != string.Empty) && (account.Text != string.Empty)))
                {
                    if (((server.Text != string.Empty) && (account.Text != string.Empty)))
                    {
                        var port = LogicalTreeHelper.FindLogicalNode(this, "port") as TextBox;
                        var cb = LogicalTreeHelper.FindLogicalNode(this, "sslCheck") as CheckBox;


                        var fs = new FileStream("MailServerInfo", FileMode.OpenOrCreate);
                        var writer = new StreamWriter(fs);
                        writer.WriteLine(server.Text);
                        writer.WriteLine(account.Text);
                        port.Text = (port.Text != string.Empty) ? port.Text : "25";
                        writer.WriteLine(port.Text);
                        var check = (cb.IsChecked == true) ? "true" : "false";
                        writer.WriteLine(check);

                        writer.Close();
                        fs.Close();
                    }
                    Tag = "OK";
                    Close();
                }
                else
                {
                    Title = "Mail settings are incomplete";
                    server.Background = account.Background = Window2.ChangeBackgroundColor(Colors.Red);
                    var status = LogicalTreeHelper.FindLogicalNode(this, "status") as Label;
                    status.Content = "Fill in highlighted fields";
                    status.Foreground = Brushes.Red;
                }
            }
        }

        private void InitializeComboBox1(ComboBox combo)
        {
            for (var i = 0; i < ColorArrayForeground.Length; i++)
            {
                var c = ColorArrayForeground[i];
                var comboItem = new ComboBoxItem();
                var l = new Label
                {
                    Foreground = c,
                    MinHeight = 20,
                    MinWidth = 20
                };
                comboItem.Background = l.Background = c;
                comboItem.Tag = i;
                comboItem.Content = l;
                combo.Items.Add(comboItem);
            }
        }

        private void InitializeComboBox(ComboBox combo)
        {
            for (var i = 0; i < ColorArray.Length; i++)
            {
                var c = ColorArray[i];
                var comboItem = new ComboBoxItem();
                var l = new Label
                {
                    Background = Window2.ChangeBackgroundColor(c),
                    MinHeight = 20,
                    MinWidth = 20
                };
                comboItem.Background = Window2.ChangeBackgroundColor(c);
                comboItem.Tag = i;
                comboItem.Content = l;
                combo.Items.Add(comboItem);
            }
        }

        private void Dialog_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            _tabControl.Width = ActualWidth;
            _tabControl.Height = (ActualHeight > 60) ? (ActualHeight - 60) : _tabControl.Height;
        }

        private void combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = sender as ComboBox;
            var comboItem = cb.SelectedItem as ComboBoxItem;
            PropertyArray[(int) PropNames.BackgroundColor] = comboItem.Tag;
        }
    }
}

<|start_filename|>Windows/Wizard/WizardPage2.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Navigation;

namespace Wizard
{
    public partial class WizardPage2 : PageFunction<WizardResult>
    {
        public WizardPage2(WizardData wizardData)
        {
            InitializeComponent();

            // Bind wizard state to UI
            DataContext = wizardData;
        }

        private void backButton_Click(object sender, RoutedEventArgs e)
        {
            // Go to previous wizard page
            NavigationService?.GoBack();
        }

        private void nextButton_Click(object sender, RoutedEventArgs e)
        {
            // Go to next wizard page
            var wizardPage3 = new WizardPage3((WizardData) DataContext);
            wizardPage3.Return += wizardPage_Return;
            NavigationService?.Navigate(wizardPage3);
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            // Cancel the wizard and don't return any data
            OnReturn(new ReturnEventArgs<WizardResult>(WizardResult.Canceled));
        }

        public void wizardPage_Return(object sender, ReturnEventArgs<WizardResult> e)
        {
            // If returning, wizard was completed (finished or canceled),
            // so continue returning to calling page
            OnReturn(e);
        }
    }
}

<|start_filename|>Data Binding/ValidateItemsInItemsControl/ServiceRep.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace ValidateItemsInItemsControl
{
    public class ServiceRep
    {
        public ServiceRep()
        {
        }

        public ServiceRep(string name, Region area)
        {
            Name = name;
            Area = area;
        }

        public string Name { get; set; }
        public Region Area { get; set; }

        public override string ToString() => Name + " - " + Area;
    }
}

<|start_filename|>Getting Started/Concepts/samps/controlprops_samp.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ControlProperties //needs to match the .xaml page
{
    public partial class Page1 : Page
    {
        private FontFamily _ffamily;
        private double _fsize;
        // Begin inserting any c# code-behind content here. These methods handle events in XAML files and can be ported from samples. Access modifiers may need to be updated.


        private string _str;
        private ToolTip _ttp;
        // This function checks the language filter settings to see which code to filter and also grays out tabs with no content
        public void CheckLang(object sender, EventArgs e)
        {
            if (xcsharpCheck.Content == null) // grays out xaml + c# tab
            {
                xamlcsharp.Background = Brushes.Gainsboro;
                xamlcsharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlcsharp, true);
                _ttp.Content = "This sample is not available in XAML + C#.";
                xamlcsharp.ToolTip = (_ttp);
                xamlcsharp.IsEnabled = false;
            }
            else if (xcsharpCheck.Content != null)
            {
                xamlcsharp.IsEnabled = true;
            }

            if (xvbCheck.Content == null) // grays out xaml + vb tab
            {
                xamlvb.Background = Brushes.Gainsboro;
                xamlvb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlvb, true);
                _ttp.Content = "This sample is not available in XAML + Visual Basic.NET";
                xamlvb.ToolTip = (_ttp);
                xamlvb.IsEnabled = false;
            }
            else if (xvbCheck.Content != null)
            {
                xamlvb.IsEnabled = true;
            }

            if (xaml.Content == null) // grays out xaml
            {
                xaml.IsEnabled = false;
                xaml.Background = Brushes.Gainsboro;
                xaml.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xaml, true);
                _ttp.Content = "This sample is not available in XAML.";
                xaml.ToolTip = (_ttp);
            }
            else if (xaml.Content != null)
            {
                xaml.IsEnabled = true;
            }

            if (csharp.Content == null) // grays out c#
            {
                csharp.IsEnabled = false;
                csharp.Background = Brushes.Gainsboro;
                csharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(csharp, true);
                _ttp.Content = "This sample is not available in C#.";
                csharp.ToolTip = (_ttp);
            }
            else if (csharp.Content != null)
            {
                csharp.IsEnabled = true;
            }

            if (vb.Content == null) // grays out vb
            {
                vb.IsEnabled = false;
                vb.Background = Brushes.Gainsboro;
                vb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(vb, true);
                _ttp.Content = "This sample is not available in Visual Basic.NET.";
                vb.ToolTip = (_ttp);
            }
            else if (vb.Content != null)
            {
                vb.IsEnabled = true;
            }

            if (managedcpp.Content == null) // grays out cpp
            {
                managedcpp.IsEnabled = false;
                managedcpp.Background = Brushes.Gainsboro;
                managedcpp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(managedcpp, true);
                _ttp.Content = "This sample is not available in Managed C++.";
                managedcpp.ToolTip = (_ttp);
            }
            else if (managedcpp.Content != null)
            {
                managedcpp.IsEnabled = true;
            }
            if (Welcome.Page1.MyDouble == 1) // XAML only
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 2) // CSharp
            {
                csharp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 3) // Visual Basic
            {
                vb.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 4) // Managed CPP
            {
                managedcpp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 5) // No Filter
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Visible;
                vb.Visibility = Visibility.Visible;
                managedcpp.Visibility = Visibility.Visible;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Visible;
            }
            else if (Welcome.Page1.MyDouble == 6) // XAML + CSharp
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 7) // XAML + VB
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Visible;
            }
        }

        // To use PaneLoaded put Loaded="PaneLoaded" in root element of .xaml file.
        // private void PaneLoaded(object sender, EventArgs e) {}
        // Sample event handler:  
        private void ChangeBackground(object sender, RoutedEventArgs e)
        {
            if (btn.Background == Brushes.Red)
            {
                btn.Background = new LinearGradientBrush(Colors.LightBlue, Colors.SlateBlue, 90);
                btn.Content = "Background";
            }
            else
            {
                btn.Background = Brushes.Red;
                btn.Content = "Control background changes from red to a blue gradient.";
            }
        }

        private void ChangeForeground(object sender, RoutedEventArgs e)
        {
            if (btn1.Foreground == Brushes.Green)
            {
                btn1.Foreground = Brushes.Black;
                btn1.Content = "Foreground";
            }
            else
            {
                btn1.Foreground = Brushes.Green;
                btn1.Content = "Control foreground(text) changes from black to green.";
            }
        }

        private void ChangeFontFamily(object sender, RoutedEventArgs e)
        {
            _ffamily = btn2.FontFamily;
            _str = _ffamily.ToString();
            if (_str == ("Arial Black"))
            {
                btn2.FontFamily = new FontFamily("Arial");
                btn2.Content = "FontFamily";
            }
            else
            {
                btn2.FontFamily = new FontFamily("Arial Black");
                btn2.Content = "Control font family changes from Arial to Arial Black.";
            }
        }

        private void ChangeFontSize(object sender, RoutedEventArgs e)
        {
            _fsize = btn3.FontSize;
            if (_fsize == 16.0)
            {
                btn3.FontSize = 10.0;
                btn3.Content = "FontSize";
            }
            else
            {
                btn3.FontSize = 16.0;
                btn3.Content = "Control font size changes from 10 to 16.";
            }
        }

        private void ChangeFontStyle(object sender, RoutedEventArgs e)
        {
            if (btn4.FontStyle == FontStyles.Italic)
            {
                btn4.FontStyle = FontStyles.Normal;
                btn4.Content = "FontStyle";
            }
            else
            {
                btn4.FontStyle = FontStyles.Italic;
                btn4.Content = "Control font style changes from Normal to Italic.";
            }
        }

        private void ChangeFontWeight(object sender, RoutedEventArgs e)
        {
            if (btn5.FontWeight == FontWeights.Bold)
            {
                btn5.FontWeight = FontWeights.Normal;
                btn5.Content = "FontWeight";
            }
            else
            {
                btn5.FontWeight = FontWeights.Bold;
                btn5.Content = "Control font weight changes from Normal to Bold.";
            }
        }

        private void ChangeBorderBrush(object sender, RoutedEventArgs e)
        {
            _str = ((btn6.BorderBrush).ToString());
            if (btn6.BorderBrush == Brushes.Red)
            {
                btn6.BorderBrush = Brushes.Black;
                btn6.Content = "BorderBrush";
            }
            else
            {
                btn6.BorderBrush = Brushes.Red;
                btn6.Content = "Control border brush changes from red to black.";
            }
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/BamlResource.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Reflection;

namespace BamlTools
{
    public class BamlResource
    {
        string _bamlName;
        Stream _stream;
        Assembly _assembly;

        public BamlResource(string bamlName, Stream stream, Assembly assembly)
        {
            _bamlName = bamlName;
            _stream = stream;
            _assembly = assembly;
        }

        public static int SortCompare(BamlResource a, BamlResource b)
        {
            return String.Compare(a.BamlName, b.BamlName);
        }

        public string BamlName
        {
            get { return _bamlName; }
        }

        public Stream Stream
        {
            get { return _stream; }
        }

        public Assembly Assembly
        {
            get { return _assembly; }
        }

        public bool IsBaml
        {
            get { return _bamlName.EndsWith(".baml", StringComparison.InvariantCultureIgnoreCase); }
        }
    }
}


<|start_filename|>Animation/CustomAnimation/CircleAnimation.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace CustomAnimation
{
    /// <summary>
    ///     CircleAnimation: calculates polar coordinates as a function of time.
    ///     Use two of these (XDirection and YDirection) to move an element in an elliptical manner
    /// </summary>
    public class CircleAnimation : DoubleAnimationBase
    {
        public enum DirectionEnum
        {
            XDirection,
            YDirection
        }

        public static readonly DependencyProperty DirectionProperty =
            DependencyProperty.Register("Direction", typeof (DirectionEnum), typeof (CircleAnimation),
                new PropertyMetadata(DirectionEnum.XDirection));

        public static readonly DependencyProperty RadiusProperty =
            DependencyProperty.Register("Radius", typeof (double), typeof (CircleAnimation),
                new PropertyMetadata((double) 10));

        /// <summary>
        ///     distance from origin to polar coordinate
        /// </summary>
        public double Radius
        {
            get { return (double) GetValue(RadiusProperty); }
            set
            {
                if (value > 0.0)
                {
                    SetValue(RadiusProperty, value);
                }
                else
                {
                    throw new ArgumentException("a radius of " + value + " is not allowed!");
                }
            }
        }

        /// <summary>
        ///     are we measuring in the X or Y direction?
        /// </summary>
        public DirectionEnum Direction
        {
            get { return (DirectionEnum) GetValue(DirectionProperty); }
            set { SetValue(DirectionProperty, value); }
        }

        protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue,
            AnimationClock clock)
        {
            var time = clock.CurrentProgress.Value;

            // math magic: calculate new coordinates using polar coordinate equations. This requires two 
            // animations to be wired up in order to move in a circle, since we don't make any assumptions
            // about what we're animating (e.g. a TranslateTransform). 
            var returnValue = Direction == DirectionEnum.XDirection
                ? Math.Cos(2*Math.PI*time)
                : Math.Sin(2*Math.PI*time);

            // Need to add the defaultOriginValue so that composition works.
            return returnValue*Radius + defaultOriginValue;
        }

        protected override Freezable CreateInstanceCore() => new CircleAnimation();
    }
}

<|start_filename|>Styles & Templates/AlternatingAppearanceOfItems/Place.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace AlternatingAppearanceOfItems
{
    public class Place
    {
        public Place()
        {
            CityName = "";
            State = "";
        }

        public Place(string name, string state)
        {
            CityName = name;
            State = state;
        }

        public string CityName { get; set; }
        public string State { get; set; }
    }
}

<|start_filename|>Windows/WindowSizingOrder/SizingWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace WindowSizingOrder
{
    /// <summary>
    ///     Interaction logic for SizingWindow.xaml
    /// </summary>
    public partial class SizingWindow : Window
    {
        public SizingWindow()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Windows/SaveWindowState/POINT.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;

namespace SaveWindowState
{
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public struct Point
    {
        public int X;
        public int Y;

        public Point(int x, int y)
        {
            X = x;
            Y = y;
        }
    }
}

<|start_filename|>Data Binding/BindConversion/MyData.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;

namespace BindConversion
{
    public class MyData : INotifyPropertyChanged
    {
        private DateTime _thedate;

        public MyData()
        {
            _thedate = DateTime.Now;
        }

        public DateTime TheDate
        {
            get { return _thedate; }
            set
            {
                _thedate = value;
                OnPropertyChanged("TheDate");
            }
        }

        // Declare event
        public event PropertyChangedEventHandler PropertyChanged;
        // OnPropertyChanged method to update property value in binding
        private void OnPropertyChanged(string info)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
        }
    }
}

<|start_filename|>Accessibility/FindText/FindTextClient/SearchWindow.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Text;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using Application = System.Windows.Forms.Application;

namespace FindTextClient
{
    /// --------------------------------------------------------------------
    /// <summary>
    ///     Interaction logic for client and target
    /// </summary>
    /// --------------------------------------------------------------------
    public class SearchWindow
    {
        #region Expand Selection

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the expand to enclosing unit item selected event.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void ExpandToTextUnit_Change(
            object sender, SelectionChangedEventArgs e)
        {
            var cb = (ComboBox) sender;

            // Expand the target selection to the selected text unit.
            var selectionRanges =
                _targetTextPattern.GetSelection();
            foreach (var textRange in selectionRanges)
            {
                switch (cb.SelectedValue.ToString())
                {
                    case "None":
                        textRange.MoveEndpointByRange(
                            TextPatternRangeEndpoint.End,
                            textRange,
                            TextPatternRangeEndpoint.Start);
                        break;
                    case "Character":
                        textRange.ExpandToEnclosingUnit(TextUnit.Character);
                        break;
                    case "Format":
                        textRange.ExpandToEnclosingUnit(TextUnit.Format);
                        break;
                    case "Word":
                        textRange.ExpandToEnclosingUnit(TextUnit.Word);
                        break;
                    case "Line":
                        textRange.ExpandToEnclosingUnit(TextUnit.Line);
                        break;
                    case "Paragraph":
                        textRange.ExpandToEnclosingUnit(TextUnit.Paragraph);
                        break;
                    case "Page":
                        textRange.ExpandToEnclosingUnit(TextUnit.Page);
                        break;
                    case "Document":
                        textRange.ExpandToEnclosingUnit(TextUnit.Document);
                        break;
                }
                textRange.Select();
                // The WPF target doesn't show selected text as highlighted unless
                // the window has focus.
                _targetWindow.SetFocus();
            }
        }

        #endregion Expand Highlight

        #region Member Variables

        // Client application window.
        private readonly Window _clientWindow;
        // Container for all client controls.
        private readonly DockPanel _clientDockPanel;
        // Target application window.
        private AutomationElement _targetWindow;
        // Target text control.
        private AutomationElement _targetDocument;
        // Text pattern obtained from the target text control.
        private TextPattern _targetTextPattern;
        // Text range for entire target text control. 
        private TextPatternRange _documentRange;
        // Text range for current selection in target text control.
        private TextPatternRange _searchRange;
        // Target applications based on underlying framework.
        private readonly Button _startWpfTargetButton;
        private readonly Button _startW32TargetButton;
        private readonly string _wpfTarget;
        private readonly string _w32Target;
        // Find the target text control.
        private readonly Button _findEditButton;
        // Display target status.
        private readonly Label _targetResult;
        // Layout grid for client controls.
        private readonly Grid _infoGrid;
        // String to search for in the target text control.
        private readonly TextBox _searchString;
        // Depending on the location of the selection in the target text
        // control, the client can search forward or backward for the 
        // search string.
        private readonly Button _searchBackwardButton;
        private readonly Button _searchForwardButton;
        // Direction of search.
        private bool _searchBackward;
        // Expand the target text selection by the specified text unit.
        private readonly ComboBox _expandHighlight;
        // Move the target text selection by the specified text unit. 
        private readonly ComboBox _navigateTarget;
        private TextUnit _navigationUnit;
        // Display the target text selection and attributes.
        private readonly Label _targetSelectionLabel;
        private readonly Label _targetSelectionAttributeLabel;
        private readonly TextBox _targetSelection;
        private readonly TextBox _targetSelectionAttributes;
        // Display target text selection details such as child and enclosing unit.
        private readonly TextBox _targetSelectionDetails;
        // Delegates for updating the client UI based on target application events.
        private delegate void TextChangeDelegate(string message);

        private delegate void SelectionChangeDelegate();

        private delegate void ProviderCloseDelegate();

        // Target applications.
        private enum TargetApplication
        {
            FlowDocument,
            WordPad
        }

        // Search and navigation directions.
        private enum TraversalDirection
        {
            Backward,
            Forward
        }

        #endregion Member Variables

        #region Client Setup

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The class constructor.
        /// </summary>
        /// <remarks>
        ///     Initialize the WPF client application.
        /// </remarks>
        /// --------------------------------------------------------------------
        public SearchWindow()
        {
            // Specify the target applications.
            _wpfTarget =
                Application.StartupPath + "\\FindText.exe";
            _w32Target = "WordPad.exe";

            // Initialize search direction. 
            // Search direction buttons are enabled or disabled based on this value.
            _searchBackward = false;

            // Layout the client controls.
            try
            {
                // Specs for Window.
                double clientHeight = 600;
                double clientWidth = 550;

                // Specs for TextBox.
                var maxSearchLines = 1;
                var maxSearchLength = 25;

                // Specs for Buttons.
                double buttonWidth = 140;

                // Instantiate the client window and set location and size.
                _clientWindow = new Window
                {
                    Height = clientHeight,
                    Width = clientWidth,
                    Left = SystemParameters.WorkArea.Location.X + 50,
                    Top = SystemParameters.WorkArea.Location.Y + 50,
                    Title = "Find Text",
                    WindowStyle = WindowStyle.ToolWindow
                };

                // Create a dock panel to hold all controls.
                _clientDockPanel = new DockPanel
                {
                    Margin = new Thickness(10),
                    LastChildFill = true
                };

                // Add the start target buttons.
                _startWpfTargetButton = new Button
                {
                    Width = buttonWidth,
                    Content = "Start _FlowDocument (WPF)",
                    Tag = TargetApplication.FlowDocument
                };
                _startWpfTargetButton.Click +=
                    StartTargetApplication_Click;
                _startW32TargetButton = new Button
                {
                    Width = buttonWidth,
                    Content = "Start _WordPad (Win32)",
                    Tag = TargetApplication.WordPad
                };
                _startW32TargetButton.Click +=
                    StartTargetApplication_Click;
                DockPanel.SetDock(_startWpfTargetButton, Dock.Top);
                DockPanel.SetDock(_startW32TargetButton, Dock.Top);
                _clientDockPanel.Children.Add(_startWpfTargetButton);
                _clientDockPanel.Children.Add(_startW32TargetButton);

                // Add the find text control button.
                _findEditButton = new Button
                {
                    Width = buttonWidth,
                    Content = "_Find text provider"
                };
                _findEditButton.Click +=
                    FindTextProvider_Click;
                _findEditButton.Visibility = Visibility.Collapsed;
                DockPanel.SetDock(_findEditButton, Dock.Top);
                _clientDockPanel.Children.Add(_findEditButton);

                // Add the target status label.
                _targetResult = new Label
                {
                    Content = "",
                    BorderThickness = new Thickness(1),
                    BorderBrush = Brushes.Black,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Margin = new Thickness(0, 0, 0, 10),
                    Visibility = Visibility.Hidden
                };
                DockPanel.SetDock(_targetResult, Dock.Top);
                _clientDockPanel.Children.Add(_targetResult);

                // Add the client control layout grid.
                _infoGrid = new Grid
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Top,
                    ShowGridLines = false,
                    Visibility = Visibility.Collapsed,
                    MinWidth = 400
                };
                // Define the columns.
                var colDef1 = new ColumnDefinition();
                var colDef2 = new ColumnDefinition();
                _infoGrid.ColumnDefinitions.Add(colDef1);
                _infoGrid.ColumnDefinitions.Add(colDef2);
                // Define the rows.
                var rowDef1 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef2 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef3 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef4 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef5 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef6 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef7 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef8 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef9 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef10 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                var rowDef11 = new RowDefinition {Height = new GridLength(1, GridUnitType.Auto)};
                _infoGrid.RowDefinitions.Add(rowDef1);
                _infoGrid.RowDefinitions.Add(rowDef2);
                _infoGrid.RowDefinitions.Add(rowDef3);
                _infoGrid.RowDefinitions.Add(rowDef4);
                _infoGrid.RowDefinitions.Add(rowDef5);
                _infoGrid.RowDefinitions.Add(rowDef6);
                _infoGrid.RowDefinitions.Add(rowDef7);
                _infoGrid.RowDefinitions.Add(rowDef8);
                _infoGrid.RowDefinitions.Add(rowDef9);
                _infoGrid.RowDefinitions.Add(rowDef10);
                _infoGrid.RowDefinitions.Add(rowDef11);

                // Define the content of the cells.
                // Row 1 - Search string details.
                _searchString = new TextBox
                {
                    Name = "SearchString",
                    MaxLines = maxSearchLines,
                    MaxLength = maxSearchLength,
                    Width = 200
                };
                //searchString.Height = 25;
                _searchString.TextChanged +=
                    SearchString_Change;
                _searchString.IsEnabled = false;
                Grid.SetRow(_searchString, 0);
                Grid.SetColumn(_searchString, 1);
                var searchLabel = new Label
                {
                    Target = _searchString,
                    Content = "_Search for: ",
                    VerticalAlignment = VerticalAlignment.Center
                };
                Grid.SetRow(searchLabel, 0);
                Grid.SetColumn(searchLabel, 0);
                _infoGrid.Children.Add(searchLabel);
                _infoGrid.Children.Add(_searchString);

                // Row 2 - Search direction buttons.
                _searchBackwardButton = new Button
                {
                    Width = buttonWidth,
                    Content = "Search _Backward",
                    Tag = TraversalDirection.Backward
                };
                //searchBackwardButton.Height = buttonHeight;
                _searchBackwardButton.Click +=
                    SearchDirection_Click;
                _searchBackwardButton.Margin = new Thickness(0, 0, 0, 10);
                _searchBackwardButton.IsEnabled = false;
                Grid.SetRow(_searchBackwardButton, 1);
                Grid.SetColumn(_searchBackwardButton, 0);
                _searchForwardButton = new Button
                {
                    Width = buttonWidth,
                    Content = "Search _Forward",
                    Tag = TraversalDirection.Forward
                };
                //searchForwardButton.Height = buttonHeight;
                _searchForwardButton.Click +=
                    SearchDirection_Click;
                _searchForwardButton.Margin = new Thickness(0, 0, 0, 10);
                _searchForwardButton.IsEnabled = false;
                Grid.SetRow(_searchForwardButton, 1);
                Grid.SetColumn(_searchForwardButton, 1);
                _infoGrid.Children.Add(_searchBackwardButton);
                _infoGrid.Children.Add(_searchForwardButton);

                // Row 3 - Target selection.
                _targetSelectionLabel = new Label
                {
                    Target = _targetSelection,
                    Content = "Currently selected:"
                };
                Grid.SetRow(_targetSelectionLabel, 2);
                Grid.SetColumn(_targetSelectionLabel, 0);
                Grid.SetColumnSpan(_targetSelectionLabel, 2);
                _infoGrid.Children.Add(_targetSelectionLabel);
                // Row 4.
                _targetSelection = new TextBox
                {
                    TextWrapping = TextWrapping.Wrap,
                    MaxWidth = 400,
                    Height = 100,
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    IsReadOnly = true,
                    Margin = new Thickness(0, 0, 0, 0)
                };
                Grid.SetRow(_targetSelection, 3);
                Grid.SetColumn(_targetSelection, 0);
                Grid.SetColumnSpan(_targetSelection, 2);
                _infoGrid.Children.Add(_targetSelection);

                // Row 5 - Target selection attributes.
                _targetSelectionAttributeLabel = new Label
                {
                    Target = _targetSelection,
                    Content = "Attribute values: "
                };
                Grid.SetRow(_targetSelectionAttributeLabel, 4);
                Grid.SetColumn(_targetSelectionAttributeLabel, 0);
                Grid.SetColumnSpan(_targetSelectionAttributeLabel, 2);
                _infoGrid.Children.Add(_targetSelectionAttributeLabel);
                // Row 6.
                _targetSelectionAttributes = new TextBox
                {
                    TextWrapping = TextWrapping.Wrap,
                    MaxWidth = 400,
                    Height = 100,
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    IsReadOnly = true,
                    Margin = new Thickness(0, 0, 0, 10)
                };
                Grid.SetRow(_targetSelectionAttributes, 5);
                Grid.SetColumn(_targetSelectionAttributes, 0);
                Grid.SetColumnSpan(_targetSelectionAttributes, 2);
                _infoGrid.Children.Add(_targetSelectionAttributes);

                // Row 7 - Navigate target details.
                _navigateTarget = new ComboBox {Width = buttonWidth};
                _navigateTarget.Items.Add(TextUnit.Character);
                _navigateTarget.Items.Add(TextUnit.Format);
                _navigateTarget.Items.Add(TextUnit.Word);
                _navigateTarget.Items.Add(TextUnit.Line);
                _navigateTarget.Items.Add(TextUnit.Paragraph);
                _navigateTarget.Items.Add(TextUnit.Page);
                _navigateTarget.SelectedIndex = 0;
                _navigateTarget.SelectionChanged +=
                    NavigationUnit_Change;
                Grid.SetRow(_navigateTarget, 6);
                Grid.SetColumn(_navigateTarget, 1);
                var navigateLabel = new Label
                {
                    Target = _navigateTarget,
                    Content = "_Navigate target by text unit of: ",
                    VerticalAlignment = VerticalAlignment.Center
                };
                Grid.SetRow(navigateLabel, 6);
                Grid.SetColumn(navigateLabel, 0);
                _infoGrid.Children.Add(navigateLabel);
                _infoGrid.Children.Add(_navigateTarget);

                // Row 8 - Navigate target direction buttons.
                var navigateBackwardButton = new Button
                {
                    Width = buttonWidth,
                    Content = "_Backward",
                    Tag = TraversalDirection.Backward
                };
                navigateBackwardButton.Click += Navigate_Click;
                navigateBackwardButton.Margin = new Thickness(0, 0, 0, 10);
                Grid.SetRow(navigateBackwardButton, 7);
                Grid.SetColumn(navigateBackwardButton, 0);
                var navigateForwardButton = new Button
                {
                    Width = buttonWidth,
                    Content = "_Forward",
                    Tag = TraversalDirection.Forward
                };
                navigateForwardButton.Click += Navigate_Click;
                navigateForwardButton.Margin = new Thickness(0, 0, 0, 10);
                Grid.SetRow(navigateForwardButton, 7);
                Grid.SetColumn(navigateForwardButton, 1);
                _infoGrid.Children.Add(navigateBackwardButton);
                _infoGrid.Children.Add(navigateForwardButton);

                // Row 9 - Expand the target selection controls.
                _expandHighlight = new ComboBox {Width = buttonWidth};
                _expandHighlight.Items.Add("");
                _expandHighlight.Items.Add("None");
                _expandHighlight.Items.Add(TextUnit.Character);
                _expandHighlight.Items.Add(TextUnit.Format);
                _expandHighlight.Items.Add(TextUnit.Word);
                _expandHighlight.Items.Add(TextUnit.Line);
                _expandHighlight.Items.Add(TextUnit.Paragraph);
                _expandHighlight.Items.Add(TextUnit.Page);
                _expandHighlight.Items.Add(TextUnit.Document);
                _expandHighlight.SelectedIndex = 0;
                _expandHighlight.SelectionChanged +=
                    ExpandToTextUnit_Change;
                _expandHighlight.Margin = new Thickness(0, 0, 0, 10);
                Grid.SetRow(_expandHighlight, 8);
                Grid.SetColumn(_expandHighlight, 1);
                var expandLabel = new Label
                {
                    Target = _expandHighlight,
                    Content = "_Expand selection to text unit of: ",
                    VerticalAlignment = VerticalAlignment.Center,
                    Margin = new Thickness(0, 0, 0, 10)
                };
                Grid.SetRow(expandLabel, 8);
                Grid.SetColumn(expandLabel, 0);
                _infoGrid.Children.Add(expandLabel);
                _infoGrid.Children.Add(_expandHighlight);

                // Row 10 - target selection details such as child elements 
                //         and enclosing unit.
                _targetSelectionDetails = new TextBox
                {
                    Height = 100,
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    IsReadOnly = true
                };
                Grid.SetRow(_targetSelectionDetails, 9);
                Grid.SetColumn(_targetSelectionDetails, 0);
                Grid.SetColumnSpan(_targetSelectionDetails, 2);
                _infoGrid.Children.Add(_targetSelectionDetails);

                // Row 11 - get the child elements and the enclosing unit 
                //         of the target selection.
                var getChildren = new Button
                {
                    Width = buttonWidth,
                    Content = "Get children of selection"
                };
                getChildren.Click += GetChildren_Click;
                Grid.SetRow(getChildren, 10);
                Grid.SetColumn(getChildren, 0);
                var getEnclosingElement = new Button
                {
                    Width = buttonWidth,
                    Content = "Get enclosing element"
                };
                getEnclosingElement.Click += GetEnclosingElement_Click;
                Grid.SetRow(getEnclosingElement, 10);
                Grid.SetColumn(getEnclosingElement, 1);
                _infoGrid.Children.Add(getChildren);
                _infoGrid.Children.Add(getEnclosingElement);

                // Add the grid to the dock panel.
                DockPanel.SetDock(_infoGrid, Dock.Top);
                _clientDockPanel.Children.Add(_infoGrid);

                // Add the dock panel to the window.
                _clientWindow.Content = _clientDockPanel;
                _clientWindow.Show();
            }
                // Do we successfully create the client app?
            catch (InvalidOperationException)
            {
                // TODO: error handling.
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the Start Application button click.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Starts the application that we are going to use for as our
        ///     root element for this sample.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void StartTargetApplication_Click(object sender, RoutedEventArgs e)
        {
            var targetOption = (Button) sender;

            // Start the target selected by the user.
            _targetWindow =
                StartApp((TargetApplication) targetOption.Tag == TargetApplication.WordPad ? _w32Target : _wpfTarget);

            // Target is not available.
            Debug.Assert(_targetWindow != null);

            // Set a listener for the window closed event on the target.
            Automation.AddAutomationEventHandler(
                WindowPattern.WindowClosedEvent,
                _targetWindow, TreeScope.Element, OnTargetClose);

            // Set size and position of target.
            // Since the target is started and manipulated from the client 
            // and both windows show UI changes this section of code just
            // ensures neither window obscures the other.
            var targetTransformPattern =
                _targetWindow.GetCurrentPattern(TransformPattern.Pattern)
                    as TransformPattern;
            targetTransformPattern?.Resize(_clientWindow.Width, _clientWindow.Height);
            targetTransformPattern.Move(
                _clientWindow.Left + _clientWindow.Width + 25, _clientWindow.Top);

            // Set visibility of client controls.
            _startWpfTargetButton.Visibility = Visibility.Collapsed;
            _startW32TargetButton.Visibility = Visibility.Collapsed;
            _findEditButton.Visibility = Visibility.Visible;
            _targetResult.Visibility = Visibility.Visible;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Starts the target application.
        /// </summary>
        /// <param name="app">
        ///     The application to start.
        /// </param>
        /// <returns>The automation element for the app main window.</returns>
        /// <remarks>
        ///     Three WPF documents, a rich text document, and a plain text document
        ///     are provided in the Content folder of the TextProvider project.
        /// </remarks>
        /// --------------------------------------------------------------------
        private AutomationElement StartApp(string app)
        {
            // Start application.
            var p = Process.Start(app);

            // Give the target application some time to start.
            // For Win32 applications, WaitForInputIdle can be used instead.
            // Another alternative is to listen for WindowOpened events.
            // Otherwise, an ArgumentException results when you try to
            // retrieve an automation element from the window handle.
            Thread.Sleep(2000);

            _targetResult.Content =
                _wpfTarget +
                " started. \n\nPlease load a document into the target " +
                "application and click the 'Find edit control' button above. " +
                "\n\nNOTE: Documents can be found in the 'Content' folder of the FindText project.";
            _targetResult.Background = Brushes.LightGreen;

            // Return the automation element for the app main window.
            return (AutomationElement.FromHandle(p.MainWindowHandle));
        }

        #endregion Client Setup

        #region Target Text Info

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Finds the text control in our target.
        /// </summary>
        /// <param name="src">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Initializes the TextPattern object and event handlers.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void FindTextProvider_Click(object src, RoutedEventArgs e)
        {
            // Set up the conditions for finding the text control.
            var documentControl = new PropertyCondition(
                AutomationElement.ControlTypeProperty,
                ControlType.Document);
            var textPatternAvailable = new PropertyCondition(
                AutomationElement.IsTextPatternAvailableProperty, true);
            var findControl =
                new AndCondition(documentControl, textPatternAvailable);

            // Get the Automation Element for the first text control found.
            // For the purposes of this sample it is sufficient to find the 
            // first text control. In other cases there may be multiple text
            // controls to sort through.
            _targetDocument =
                _targetWindow.FindFirst(TreeScope.Descendants, findControl);

            // Didn't find a text control.
            if (_targetDocument == null)
            {
                _targetResult.Content =
                    _wpfTarget +
                    " does not contain a Document control type.";
                _targetResult.Background = Brushes.Salmon;
                _startWpfTargetButton.IsEnabled = false;
                return;
            }

            // Get required control patterns 
            _targetTextPattern =
                _targetDocument.GetCurrentPattern(
                    TextPattern.Pattern) as TextPattern;

            // Didn't find a text control that supports TextPattern.
            if (_targetTextPattern == null)
            {
                _targetResult.Content =
                    _wpfTarget +
                    " does not contain an element that supports TextPattern.";
                _targetResult.Background = Brushes.Salmon;
                _startWpfTargetButton.IsEnabled = false;
                return;
            }

            // Text control is available so display the client controls.
            _infoGrid.Visibility = Visibility.Visible;

            _targetResult.Content =
                "Text provider found.";
            _targetResult.Background = Brushes.LightGreen;

            // Initialize the document range for the text of the document.
            _documentRange = _targetTextPattern.DocumentRange;

            // Initialize the client's search buttons.
            if (_targetTextPattern.DocumentRange.GetText(1).Length > 0)
            {
                _searchForwardButton.IsEnabled = true;
            }
            // Initialize the client's search TextBox.
            _searchString.IsEnabled = true;

            // Check if the text control supports text selection
            if (_targetTextPattern.SupportedTextSelection ==
                SupportedTextSelection.None)
            {
                _targetResult.Content = "Unable to select text.";
                _targetResult.Background = Brushes.Salmon;
                return;
            }

            // Edit control found so remove the find button from the client.
            _findEditButton.Visibility = Visibility.Collapsed;

            // Initialize the client with the current target selection, if any.
            NotifySelectionChanged();

            // Search starts at beginning of doc and goes forward
            _searchBackward = false;

            // Initialize a text changed listener.
            // An instance of TextPatternRange will become invalid if 
            // one of the following occurs:
            // 1) The text in the provider changes via some user activity.
            // 2) ValuePattern.SetValue is used to programatically change 
            // the value of the text in the provider.
            // The only way the client application can detect if the text 
            // has changed (to ensure that the ranges are still valid), 
            // is by setting a listener for the TextChanged event of 
            // the TextPattern. If this event is raised, the client needs 
            // to update the targetDocumentRange member data to ensure the 
            // user is working with the updated text. 
            // Clients must always anticipate the possibility that the text 
            // can change underneath them.
            Automation.AddAutomationEventHandler(
                TextPattern.TextChangedEvent,
                _targetDocument,
                TreeScope.Element,
                TextChanged);

            // Initialize a selection changed listener.
            // The target selection is reflected in the client.
            Automation.AddAutomationEventHandler(
                TextPattern.TextSelectionChangedEvent,
                _targetDocument,
                TreeScope.Element,
                OnTextSelectionChange);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Gets the enclosing element of the target selection.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void GetEnclosingElement_Click(object sender, RoutedEventArgs e)
        {
            // Obtain the enclosing element.
            AutomationElement enclosingElement;
            try
            {
                enclosingElement = _searchRange.GetEnclosingElement();
            }
            catch (ElementNotAvailableException)
            {
                // TODO: error handling.
                return;
            }

            // Assemble the information about the enclosing element.
            var enclosingElementInformation = new StringBuilder();
            enclosingElementInformation.Append(
                "Enclosing element:\t").AppendLine(
                    enclosingElement.Current.ControlType.ProgrammaticName);

            // The WPF target doesn't show selected text as highlighted unless
            // the window has focus.
            _targetWindow.SetFocus();

            // Display the enclosing element information in the client.
            _targetSelectionDetails.Text = enclosingElementInformation.ToString();

            // Is the enclosing element the entire document?
            // If so, select the document.
            if (enclosingElement == _targetDocument)
            {
                _documentRange = _targetTextPattern.DocumentRange;
                _documentRange.Select();
                return;
            }
            // Otherwise, select the range from the child element.
            var childRange =
                _documentRange.TextPattern.RangeFromChild(enclosingElement);
            childRange.Select();
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Gets the children of the target selection.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void GetChildren_Click(object sender, RoutedEventArgs e)
        {
            // Obtain an array of child elements.
            AutomationElement[] textProviderChildren;
            try
            {
                textProviderChildren = _searchRange.GetChildren();
            }
            catch (ElementNotAvailableException)
            {
                // TODO: error handling.
                return;
            }

            // Assemble the information about the enclosing element.
            var childInformation = new StringBuilder();
            childInformation.Append(textProviderChildren.Length)
                .AppendLine(" child element(s).");

            // Iterate through the collection of child elements and obtain
            // information of interest about each.
            for (var i = 0; i < textProviderChildren.Length; i++)
            {
                childInformation.Append("Child").Append(i).AppendLine(":");
                // Obtain the name of the child control.
                childInformation.Append("\tName:\t")
                    .AppendLine(textProviderChildren[i].Current.Name);
                // Obtain the control type.
                childInformation.Append("\tControl Type:\t")
                    .AppendLine(textProviderChildren[i].Current.ControlType.ProgrammaticName);

                // Obtain the supported control patterns.
                // NOTE: For the purposes of this sample we use GetSupportedPatterns(). 
                // However, the use of GetSupportedPatterns() is strongly discouraged 
                // as it calls GetCurrentPattern() internally on every known pattern. 
                // It is therefore much more efficient to use GetCurrentPattern() for 
                // the specific patterns you are interested in.
                var childPatterns =
                    textProviderChildren[i].GetSupportedPatterns();
                childInformation.AppendLine("\tSupported Control Patterns:");
                if (childPatterns.Length <= 0)
                {
                    childInformation.AppendLine("\t\t\tNone");
                }
                else
                {
                    foreach (var pattern in childPatterns)
                    {
                        childInformation.Append("\t\t\t")
                            .AppendLine(pattern.ProgrammaticName);
                    }
                }

                // Obtain the child elements, if any, of the child control.
                var childRange =
                    _documentRange.TextPattern.RangeFromChild(textProviderChildren[i]);
                var childRangeChildren =
                    childRange.GetChildren();
                childInformation.Append("\tChildren: \t").Append(childRangeChildren.Length).AppendLine();
            }
            // Display the information about the child controls.
            _targetSelectionDetails.Text = childInformation.ToString();
        }

        #endregion Target Text Info

        #region Search Target

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles changes to the search text in the client.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Reset all controls if user changes search text
        /// </remarks>
        /// --------------------------------------------------------------------
        private void SearchString_Change(object sender, TextChangedEventArgs e)
        {
            var startPoints = _documentRange.CompareEndpoints(
                TextPatternRangeEndpoint.Start,
                _searchRange,
                TextPatternRangeEndpoint.Start);
            var endPoints = _documentRange.CompareEndpoints(
                TextPatternRangeEndpoint.End,
                _searchRange,
                TextPatternRangeEndpoint.End);

            // If the starting endpoints of the document range and the search
            // range are equivalent then we can search forward only since the 
            // search range is at the start of the document.
            if (startPoints == 0)
            {
                _searchForwardButton.IsEnabled = true;
                _searchBackwardButton.IsEnabled = false;
            }
            // If the ending endpoints of the document range and the search
            // range are identical then we can search backward only since the 
            // search range is at the end of the document.
            else if (endPoints == 0)
            {
                _searchForwardButton.IsEnabled = false;
                _searchBackwardButton.IsEnabled = true;
            }
            // Otherwise we can search both directions.
            else
            {
                _searchForwardButton.IsEnabled = true;
                _searchBackwardButton.IsEnabled = true;
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the Search button click.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>Find the text specified in the text box.</remarks>
        /// --------------------------------------------------------------------
        private void SearchDirection_Click(object sender, RoutedEventArgs e)
        {
            var searchDirection = (Button) sender;

            // Are we searching backward through the text control?
            _searchBackward =
                ((TraversalDirection) searchDirection.Tag == TraversalDirection.Backward);

            // Check if search text entered
            if (_searchString.Text.Trim() == "")
            {
                _targetResult.Content = "No search criteria.";
                _targetResult.Background = Brushes.Salmon;
                return;
            }

            // Does target range support text selection?
            if (_targetTextPattern.SupportedTextSelection ==
                SupportedTextSelection.None)
            {
                _targetResult.Content = "Unable to select text.";
                _targetResult.Background = Brushes.Salmon;
                return;
            }
            // Does target range support multiple selections?
            if (_targetTextPattern.SupportedTextSelection ==
                SupportedTextSelection.Multiple)
            {
                _targetResult.Content = "Multiple selections present.";
                _targetResult.Background = Brushes.Salmon;
                return;
            }

            // Clone the document range since we modify the endpoints 
            // as we search.
            var documentRangeClone = _documentRange.Clone();

            // Move the cloned document range endpoints to enable the 
            // selection of the next matching text range.
            var selectionRange =
                _targetTextPattern.GetSelection();
            if (selectionRange[0] != null)
            {
                if (_searchBackward)
                {
                    documentRangeClone.MoveEndpointByRange(
                        TextPatternRangeEndpoint.End,
                        selectionRange[0],
                        TextPatternRangeEndpoint.Start);
                }
                else
                {
                    documentRangeClone.MoveEndpointByRange(
                        TextPatternRangeEndpoint.Start,
                        selectionRange[0],
                        TextPatternRangeEndpoint.End);
                }
            }

            // Find the text specified in the Search textbox.
            // Clone the search range since we need to modify it.
            var searchRangeClone = _searchRange.Clone();
            // backward = false? -- search forward, otherwise backward.
            // ignoreCase = false? -- search is case sensitive.
            _searchRange =
                documentRangeClone.FindText(
                    _searchString.Text, _searchBackward, false);

            // Search unsuccessful.
            if (_searchRange == null)
            {
                // Search string not found at all.
                if (documentRangeClone.CompareEndpoints(
                    TextPatternRangeEndpoint.Start,
                    searchRangeClone,
                    TextPatternRangeEndpoint.Start) == 0)
                {
                    _targetResult.Content = "Text not found.";
                    _targetResult.Background = Brushes.Wheat;
                    _searchBackwardButton.IsEnabled = false;
                    _searchForwardButton.IsEnabled = false;
                }
                // End of document (either the start or end of the document 
                // range depending on search direction) was reached before 
                // finding another occurence of the search string.
                else
                {
                    _targetResult.Content = "End of document reached.";
                    _targetResult.Background = Brushes.Wheat;
                    if (!_searchBackward)
                    {
                        searchRangeClone.MoveEndpointByRange(
                            TextPatternRangeEndpoint.Start,
                            _documentRange,
                            TextPatternRangeEndpoint.End);
                        _searchBackwardButton.IsEnabled = true;
                        _searchForwardButton.IsEnabled = false;
                    }
                    else
                    {
                        searchRangeClone.MoveEndpointByRange(
                            TextPatternRangeEndpoint.End,
                            _documentRange,
                            TextPatternRangeEndpoint.Start);
                        _searchBackwardButton.IsEnabled = false;
                        _searchForwardButton.IsEnabled = true;
                    }
                }
                _searchRange = searchRangeClone;
            }
            // The search string was found.
            else
            {
                _targetResult.Content = "Text found.";
                _targetResult.Background = Brushes.LightGreen;
            }

            _searchRange.Select();
            // Scroll the selection into view and align with top of viewport
            _searchRange.ScrollIntoView(true);
            // The WPF target doesn't show selected text as highlighted unless
            // the window has focus.
            _targetWindow.SetFocus();
        }

        #endregion Search Target

        #region Target Navigation

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the navigation item selected event.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void NavigationUnit_Change(object sender, SelectionChangedEventArgs e)
        {
            var cb = (ComboBox) sender;
            _navigationUnit = (TextUnit) cb.SelectedValue;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the Navigate button click event.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void Navigate_Click(object sender, RoutedEventArgs e)
        {
            var moveSelection = (Button) sender;

            // Which direction is the user searching through the text control?
            var navDirection =
                ((TraversalDirection) moveSelection.Tag == TraversalDirection.Forward) ? 1 : -1;

            // Obtain the ranges to move.
            var selectionRanges =
                _targetTextPattern.GetSelection();

            // Iterate throught the ranges for a text control that supports
            // multiple selections and move the selections the specified text
            // unit and direction.
            foreach (var textRange in selectionRanges)
            {
                textRange.Move(_navigationUnit, navDirection);
                textRange.Select();
            }
            // The WPF target doesn't show selected text as highlighted unless
            // the window has focus.
            _targetDocument.SetFocus();
        }

        #endregion Target Navigation

        #region Target Listeners

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the text changed event in the target.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Since the events are happening on a different thread than the
        ///     client we need to use a Dispatcher delegate to handle them.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void TextChanged(object sender, AutomationEventArgs e)
        {
            _clientWindow.Dispatcher.BeginInvoke(
                DispatcherPriority.Send,
                new TextChangeDelegate(NotifyTextChanged),
                "Text changed, range reset.\n");
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The delegate for the target text changed event.
        /// </summary>
        /// <param name="arg">null argument</param>
        /// <returns>A null object.</returns>
        /// --------------------------------------------------------------------
        private void NotifyTextChanged(string message)
        {
            // Notify the user of the text changed event. 
            _targetSelectionLabel.Content = message;
            // Re-initialize the document range for the text of the document
            // since we don't know the extent of the changes. For example, a 
            // change in the font color attribute, such as on a hyperlink 
            // mouseover, raises this event but doesn't change the content of 
            // the text control.
            _documentRange = _targetTextPattern.DocumentRange;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the text selection changed event in the target.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Since the events are happening on a different thread than the
        ///     client we need to use a Dispatcher delegate to handle them.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void OnTextSelectionChange(object sender, AutomationEventArgs e)
        {
            _clientWindow.Dispatcher.BeginInvoke(
                DispatcherPriority.Send,
                new SelectionChangeDelegate(NotifySelectionChanged));
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The delegate for the target text selection changed event.
        /// </summary>
        /// <param name="arg">null argument</param>
        /// <returns>A null object.</returns>
        /// --------------------------------------------------------------------
        private void NotifySelectionChanged()
        {
            // Get the array of disjoint selections.
            var selectionRanges =
                _targetTextPattern.GetSelection();
            // Update the current search range.
            // For the purposes of this sample only the first selection
            // range will be echoed in the client.
            _searchRange = selectionRanges[0];
            // For performance and security reasons we'll limit 
            // the length of the string retrieved to 100 characters.
            // Alternatively, GetText(-1) will retrieve all selected text.
            var selectedText = _searchRange.GetText(100);
            _targetSelectionLabel.Content =
                "Currently selected (100 character maximum): " +
                selectedText.Length + " characters.";

            // Report target selection details.
            DisplaySelectedTextWithAttributes(selectedText);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Display the target selection with attribute details in client.
        /// </summary>
        /// <param name="selectedText">The current target selection.</param>
        /// --------------------------------------------------------------------
        private void DisplaySelectedTextWithAttributes(string selectedText)
        {
            _targetSelection.Text = selectedText;
            // We're only interested in the FontNameAttribute for the purposes 
            // of this sample.
            _targetSelectionAttributes.Text =
                ParseTextRangeByAttribute(
                    selectedText, TextPattern.FontNameAttribute);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Parse the target selection based on the text attribute of interest.
        /// </summary>
        /// <param name="selectedText">The current target selection.</param>
        /// <param name="automationTextAttribute">
        ///     The text attribute of interest.
        /// </param>
        /// <returns>
        ///     A string representing the requested attribute details.
        /// </returns>
        /// --------------------------------------------------------------------
        private string ParseTextRangeByAttribute(
            string selectedText,
            AutomationTextAttribute automationTextAttribute)
        {
            var attributeDetails = new StringBuilder();
            // Initialize the current attribute value.
            var attributeValue = "";
            // Make a copy of the text range.
            var searchRangeClone = _searchRange.Clone();
            // Collapse the range to the starting endpoint.
            searchRangeClone.Move(TextUnit.Character, -1);
            // Iterate through the range character by character.
            for (var x = 1; x <= selectedText.Length; x++)
            {
                searchRangeClone.Move(TextUnit.Character, 1);
                // Get the attribute value of the current character.
                var newAttributeValue =
                    searchRangeClone.GetAttributeValue(automationTextAttribute).ToString();
                // If the new attribute value is not equal to the old then report 
                // the new value along with its location within the range.
                if (newAttributeValue != attributeValue)
                {
                    attributeDetails.Append(automationTextAttribute.ProgrammaticName)
                        .Append(":\n<")
                        .Append(newAttributeValue)
                        .Append("> at text range position ")
                        .AppendLine(x.ToString());
                    attributeValue = newAttributeValue;
                }
            }
            return attributeDetails.ToString();
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles the window closed event in the target.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void OnTargetClose(object sender, AutomationEventArgs e)
        {
            _clientWindow.Dispatcher.BeginInvoke(
                DispatcherPriority.Send,
                new ProviderCloseDelegate(CloseApp));
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The delegate for the window closed event in the target.
        /// </summary>
        /// <param name="arg">null argument</param>
        /// <returns>A null object.</returns>
        /// --------------------------------------------------------------------
        private void CloseApp()
        {
            // Close the client window when the target window is closed.
            _clientWindow.Close();
        }

        #endregion Target Listeners
    }
}

<|start_filename|>Application Management/ExceptionHandlingSecondaryWorkerThread/App.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace ExceptionHandlingSecondaryWorkerThread
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // Display exception message
            var sb = new StringBuilder();
            sb.AppendFormat("{0}\n", e.Exception.InnerException.Message);
            sb.AppendFormat("{0}\n", e.Exception.Message);
            sb.AppendFormat("Exception handled on main UI thread {0}.", e.Dispatcher.Thread.ManagedThreadId);
            MessageBox.Show(sb.ToString());

            // Keep application running in the face of this exception
            e.Handled = true;
        }
    }
}

<|start_filename|>Getting Started/Concepts/welcome.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Controls;

namespace Welcome
{
    public partial class Page1 : Page
    {
        public static double MyDouble;
    }
}

<|start_filename|>Sample Applications/VideoViewerDemo/MyVideos.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;
using System.IO;
using System.Windows;

// ObserverableCollection
// DirectoryInfo

// MessageBox

namespace VideoViewerDemo
{
    // MyVideos is a collection of MyVideo objects
    // This class has a Directory string property
    // The Update() method takes all .wmv files from the specified directory
    // and adds them as MyVideo objects into the collection
    public class MyVideos : ObservableCollection<MyVideo>
    {
        private DirectoryInfo _directory;

        public MyVideos()
        {
        }

        public MyVideos(string directory)
        {
            Directory = directory;
        }

        public string Directory
        {
            set
            {
                // Don't set path if directory is invalid
                if (!System.IO.Directory.Exists(value))
                {
                    MessageBox.Show("No Such Directory");
                }

                _directory = new DirectoryInfo(value);

                Update();
            }
            get { return _directory.FullName; }
        }

        private void Update()
        {
            // Don't update if no directory to get files from
            if (_directory == null) return;

            // Remove all MyVideo objects from this collection
            Clear();

            // Create MyVideo objects
            foreach (var f in _directory.GetFiles("*.wmv"))
            {
                Add(new MyVideo(f.FullName, f.Name));
            }
        }
    }

    // MyVideo class
    // Properties: VideoTitle and Source
}

<|start_filename|>Input and Commands/MousePointer/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace MousePointer
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // raised when mouse cursor enters the area occupied by the element
        private void OnMouseEnterHandler(object sender, MouseEventArgs e)
        {
            border1.Background = Brushes.Red;
        }

        // raised when mouse cursor leaves the area occupied by the element
        private void OnMouseLeaveHandler(object sender, MouseEventArgs e)
        {
            border1.Background = Brushes.White;
        }
    }
}

<|start_filename|>Documents/Fixed Documents/DocumentSerialization/HtmlXmlConverter/htmlschema.cs<|end_filename|>
//---------------------------------------------------------------------------
// 
// File: HtmlSchema.cs
//
// Copyright (C) Microsoft Corporation.  All rights reserved.
//
// Description: Static information about HTML structure
//
//---------------------------------------------------------------------------

namespace DocumentSerialization
{
    using System.Diagnostics;
    using System.Collections;

    /// <summary>
    /// HtmlSchema class
    /// maintains static information about HTML structure
    /// can be used by HtmlParser to check conditions under which an element starts or ends, etc.
    /// </summary>
    internal class HtmlSchema
    {
        // ---------------------------------------------------------------------
        //
        // Constructors
        //
        // ---------------------------------------------------------------------

        #region Constructors

        /// <summary>
        /// static constructor, initializes the ArrayLists
        /// that hold the elements in various sub-components of the schema
        /// e.g _htmlEmptyElements, etc.
        /// </summary>
        static HtmlSchema()
        {
            // initializes the list of all html elements
            InitializeInlineElements();

            InitializeBlockElements();

            InitializeOtherOpenableElements();

            // initialize empty elements list
            InitializeEmptyElements();

            // initialize list of elements closing on the outer element end
            InitializeElementsClosingOnParentElementEnd();

            // initalize list of elements that close when a new element starts
            InitializeElementsClosingOnNewElementStart();

            // Initialize character entities
            InitializeHtmlCharacterEntities();
        }

        #endregion Constructors;

        // ---------------------------------------------------------------------
        //
        // Internal Methods
        //
        // ---------------------------------------------------------------------

        #region Internal Methods

        /// <summary>
        /// returns true when xmlElementName corresponds to empty element 
        /// </summary>
        /// <param name="xmlElementName">
        /// string representing name to test
        /// </param>
        internal static bool IsEmptyElement(string xmlElementName) => _htmlEmptyElements.Contains(xmlElementName.ToLower());

        /// <summary>
        /// returns true if xmlElementName represents a block formattinng element.
        /// It used in an algorithm of transferring inline elements over block elements
        /// in HtmlParser
        /// </summary>
        /// <param name="xmlElementName"></param>
        /// <returns></returns>
        internal static bool IsBlockElement(string xmlElementName) => _htmlBlockElements.Contains(xmlElementName);

        /// <summary>
        /// returns true if the xmlElementName represents an inline formatting element
        /// </summary>
        /// <param name="xmlElementName"></param>
        /// <returns></returns>
        internal static bool IsInlineElement(string xmlElementName) => _htmlInlineElements.Contains(xmlElementName);

        /// <summary>
        /// It is a list of known html elements which we
        /// want to allow to produce bt HTML parser,
        /// but don'tt want to act as inline, block or no-scope.
        /// Presence in this list will allow to open
        /// elements during html parsing, and adding the
        /// to a tree produced by html parser.
        /// </summary>
        internal static bool IsKnownOpenableElement(string xmlElementName) => _htmlOtherOpenableElements.Contains(xmlElementName);

        /// <summary>
        /// returns true when xmlElementName closes when the outer element closes
        /// this is true of elements with optional start tags
        /// </summary>
        /// <param name="xmlElementName">
        /// string representing name to test
        /// </param>
        internal static bool ClosesOnParentElementEnd(string xmlElementName) => _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower());

        /// <summary>
        /// returns true if the current element closes when the new element, whose name has just been read, starts
        /// </summary>
        /// <param name="currentElementName">
        /// string representing current element name
        /// </param>
        /// <param name="elementName"></param>
        /// string representing name of the next element that will start
        internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName)
        {
            Debug.Assert(currentElementName == currentElementName.ToLower());
            switch (currentElementName)
            {
                case "colgroup":
                    return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
                case "dd":
                    return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
                case "dt":
                    return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
                case "li":
                    return _htmlElementsClosingLI.Contains(nextElementName);
                case "p":
                    return HtmlSchema.IsBlockElement(nextElementName);
                case "tbody":
                    return _htmlElementsClosingTbody.Contains(nextElementName);
                case "tfoot":
                    return _htmlElementsClosingTfoot.Contains(nextElementName);
                case "thead":
                    return _htmlElementsClosingThead.Contains(nextElementName);
                case "tr":
                    return _htmlElementsClosingTR.Contains(nextElementName);
                case "td":
                    return _htmlElementsClosingTD.Contains(nextElementName);
                case "th":
                    return _htmlElementsClosingTH.Contains(nextElementName);
            }
            return false;
        }

        /// <summary>
        /// returns true if the string passed as argument is an Html entity name
        /// </summary>
        /// <param name="entityName">
        /// string to be tested for Html entity name 
        /// </param>
        internal static bool IsEntity(string entityName)
        {
            // we do not convert entity strings to lowercase because these names are case-sensitive
            if (_htmlCharacterEntities.Contains(entityName))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name
        /// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise 
        /// </summary>
        /// <param name="entityName">
        /// string representing entity name whose character value is desired
        /// </param>
        internal static char EntityCharacterValue(string entityName)
        {
            if (_htmlCharacterEntities.Contains(entityName))
            {
                return (char) _htmlCharacterEntities[entityName];
            }
            else
            {
                return (char)0;
            }
        }

        #endregion Internal Methods

        
        // ---------------------------------------------------------------------
        //
        //  Internal Properties
        //
        // ---------------------------------------------------------------------

        #region Internal Properties

        #endregion Internal Indexers


        // ---------------------------------------------------------------------
        //
        // Private Methods
        //
        // ---------------------------------------------------------------------


        #region Private Methods

        private static void InitializeInlineElements()
        {
            _htmlInlineElements = new ArrayList();
            _htmlInlineElements.Add("a");
            _htmlInlineElements.Add("abbr");
            _htmlInlineElements.Add("acronym");
            _htmlInlineElements.Add("address");
            _htmlInlineElements.Add("b");
            _htmlInlineElements.Add("bdo"); // ???
            _htmlInlineElements.Add("big");
            _htmlInlineElements.Add("button");
            _htmlInlineElements.Add("code");
            _htmlInlineElements.Add("del"); // deleted text
            _htmlInlineElements.Add("dfn");
            _htmlInlineElements.Add("em");
            _htmlInlineElements.Add("font");
            _htmlInlineElements.Add("i");
            _htmlInlineElements.Add("ins"); // inserted text
            _htmlInlineElements.Add("kbd"); // text to entered by a user
            _htmlInlineElements.Add("label");
            _htmlInlineElements.Add("legend"); // ???
            _htmlInlineElements.Add("q"); // short inline quotation
            _htmlInlineElements.Add("s"); // strike-through text style
            _htmlInlineElements.Add("samp"); // Specifies a code sample
            _htmlInlineElements.Add("small");
            _htmlInlineElements.Add("span");
            _htmlInlineElements.Add("strike");
            _htmlInlineElements.Add("strong");
            _htmlInlineElements.Add("sub");
            _htmlInlineElements.Add("sup");
            _htmlInlineElements.Add("u");
            _htmlInlineElements.Add("var"); // indicates an instance of a program variable
        }

        private static void InitializeBlockElements()
        {
            _htmlBlockElements = new ArrayList();

            _htmlBlockElements.Add("blockquote");
            _htmlBlockElements.Add("body");
            _htmlBlockElements.Add("caption");
            _htmlBlockElements.Add("center");
            _htmlBlockElements.Add("cite");
            _htmlBlockElements.Add("dd");
            _htmlBlockElements.Add("dir"); // TODO: treat as UL element
            _htmlBlockElements.Add("div");
            _htmlBlockElements.Add("dl");
            _htmlBlockElements.Add("dt");
            _htmlBlockElements.Add("form"); // Not a block according to XHTML spec
            _htmlBlockElements.Add("h1");
            _htmlBlockElements.Add("h2");
            _htmlBlockElements.Add("h3");
            _htmlBlockElements.Add("h4");
            _htmlBlockElements.Add("h5");
            _htmlBlockElements.Add("h6");
            _htmlBlockElements.Add("html");
            _htmlBlockElements.Add("li");
            _htmlBlockElements.Add("menu"); // TODO: treat as UL element
            _htmlBlockElements.Add("ol");
            _htmlBlockElements.Add("p");
            _htmlBlockElements.Add("pre"); // Renders text in a fixed-width font
            _htmlBlockElements.Add("table");
            _htmlBlockElements.Add("tbody");
            _htmlBlockElements.Add("td");
            _htmlBlockElements.Add("textarea");
            _htmlBlockElements.Add("tfoot");
            _htmlBlockElements.Add("th");
            _htmlBlockElements.Add("thead");
            _htmlBlockElements.Add("tr");
            _htmlBlockElements.Add("tt");
            _htmlBlockElements.Add("ul");
        }

        /// <summary>
        /// initializes _htmlEmptyElements with empty elements in HTML 4 spec at
        /// http://www.w3.org/TR/REC-html40/index/elements.html
        /// </summary>
        private static void InitializeEmptyElements()
        {
            // Build a list of empty (no-scope) elements 
            // (element not requiring closing tags, and not accepting any content)
            _htmlEmptyElements = new ArrayList();
            _htmlEmptyElements.Add("area");
            _htmlEmptyElements.Add("base");
            _htmlEmptyElements.Add("basefont");
            _htmlEmptyElements.Add("br");
            _htmlEmptyElements.Add("col");
            _htmlEmptyElements.Add("frame");
            _htmlEmptyElements.Add("hr");
            _htmlEmptyElements.Add("img");
            _htmlEmptyElements.Add("input");
            _htmlEmptyElements.Add("isindex");
            _htmlEmptyElements.Add("link");
            _htmlEmptyElements.Add("meta");
            _htmlEmptyElements.Add("param");
        }
        
        private static void InitializeOtherOpenableElements()
        {
            // It is a list of known html elements which we
            // want to allow to produce bt HTML parser,
            // but don'tt want to act as inline, block or no-scope.
            // Presence in this list will allow to open
            // elements during html parsing, and adding the
            // to a tree produced by html parser.
            _htmlOtherOpenableElements = new ArrayList();
            _htmlOtherOpenableElements.Add("applet");
            _htmlOtherOpenableElements.Add("base");
            _htmlOtherOpenableElements.Add("basefont");
            _htmlOtherOpenableElements.Add("colgroup");
            _htmlOtherOpenableElements.Add("fieldset");
            //_htmlOtherOpenableElements.Add("form"); --> treated as block
            _htmlOtherOpenableElements.Add("frameset");
            _htmlOtherOpenableElements.Add("head");
            _htmlOtherOpenableElements.Add("iframe");
            _htmlOtherOpenableElements.Add("map");
            _htmlOtherOpenableElements.Add("noframes");
            _htmlOtherOpenableElements.Add("noscript");
            _htmlOtherOpenableElements.Add("object");
            _htmlOtherOpenableElements.Add("optgroup");
            _htmlOtherOpenableElements.Add("option");
            _htmlOtherOpenableElements.Add("script");
            _htmlOtherOpenableElements.Add("select");
            _htmlOtherOpenableElements.Add("style");
            _htmlOtherOpenableElements.Add("title");
        }

        /// <summary>
        /// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional
        /// we assume that for any element for which closing tags are optional, the element closes when it's outer element
        /// (in which it is nested) does
        /// </summary>
        private static void InitializeElementsClosingOnParentElementEnd()
        {
            _htmlElementsClosingOnParentElementEnd = new ArrayList();
            _htmlElementsClosingOnParentElementEnd.Add("body");
            _htmlElementsClosingOnParentElementEnd.Add("colgroup");
            _htmlElementsClosingOnParentElementEnd.Add("dd");
            _htmlElementsClosingOnParentElementEnd.Add("dt");
            _htmlElementsClosingOnParentElementEnd.Add("head");
            _htmlElementsClosingOnParentElementEnd.Add("html");
            _htmlElementsClosingOnParentElementEnd.Add("li");
            _htmlElementsClosingOnParentElementEnd.Add("p");
            _htmlElementsClosingOnParentElementEnd.Add("tbody");
            _htmlElementsClosingOnParentElementEnd.Add("td");
            _htmlElementsClosingOnParentElementEnd.Add("tfoot");
            _htmlElementsClosingOnParentElementEnd.Add("thead");
            _htmlElementsClosingOnParentElementEnd.Add("th");
            _htmlElementsClosingOnParentElementEnd.Add("tr");
        }

        private static void InitializeElementsClosingOnNewElementStart()
        {
            _htmlElementsClosingColgroup = new ArrayList();
            _htmlElementsClosingColgroup.Add("colgroup");
            _htmlElementsClosingColgroup.Add("tr");
            _htmlElementsClosingColgroup.Add("thead");
            _htmlElementsClosingColgroup.Add("tfoot");
            _htmlElementsClosingColgroup.Add("tbody");

            _htmlElementsClosingDD = new ArrayList();
            _htmlElementsClosingDD.Add("dd");
            _htmlElementsClosingDD.Add("dt");
            // TODO: dd may end in other cases as well - if a new "p" starts, etc.
            // TODO: these are the basic "legal" cases but there may be more recovery

            _htmlElementsClosingDT = new ArrayList();
            _htmlElementsClosingDD.Add("dd");
            _htmlElementsClosingDD.Add("dt");
            // TODO: dd may end in other cases as well - if a new "p" starts, etc.
            // TODO: these are the basic "legal" cases but there may be more recovery

            _htmlElementsClosingLI = new ArrayList();
            _htmlElementsClosingLI.Add("li");
            // TODO: more complex recovery

            _htmlElementsClosingTbody = new ArrayList();
            _htmlElementsClosingTbody.Add("tbody");
            _htmlElementsClosingTbody.Add("thead");
            _htmlElementsClosingTbody.Add("tfoot");
            // TODO: more complex recovery

            _htmlElementsClosingTR = new ArrayList();
            // NOTE: tr should not really close on a new thead
            // because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional
            // and thead can't come after tbody
            // however, if we do encounter this, it's probably best to end the row and ignore thead or treat
            // it as part of the table
            _htmlElementsClosingTR.Add("thead");
            _htmlElementsClosingTR.Add("tfoot");
            _htmlElementsClosingTR.Add("tbody");
            _htmlElementsClosingTR.Add("tr");
            // TODO: more complex recovery

            _htmlElementsClosingTD = new ArrayList();
            _htmlElementsClosingTD.Add("td");
            _htmlElementsClosingTD.Add("th");
            _htmlElementsClosingTD.Add("tr");
            _htmlElementsClosingTD.Add("tbody");
            _htmlElementsClosingTD.Add("tfoot");
            _htmlElementsClosingTD.Add("thead");
            // TODO: more complex recovery

            _htmlElementsClosingTH = new ArrayList();
            _htmlElementsClosingTH.Add("td");
            _htmlElementsClosingTH.Add("th");
            _htmlElementsClosingTH.Add("tr");
            _htmlElementsClosingTH.Add("tbody");
            _htmlElementsClosingTH.Add("tfoot");
            _htmlElementsClosingTH.Add("thead");
            // TODO: more complex recovery

            _htmlElementsClosingThead = new ArrayList();
            _htmlElementsClosingThead.Add("tbody");
            _htmlElementsClosingThead.Add("tfoot");
            // TODO: more complex recovery

            _htmlElementsClosingTfoot = new ArrayList();
            _htmlElementsClosingTfoot.Add("tbody");
            // although thead comes before tfoot, we add it because if it is found the tfoot should close
            // and some recovery processing be done on thead
            _htmlElementsClosingTfoot.Add("thead");
            // TODO: more complex recovery
        }

        /// <summary>
        /// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names
        /// </summary>
        private static void InitializeHtmlCharacterEntities()
        {
            _htmlCharacterEntities = new Hashtable();
            _htmlCharacterEntities["Aacute"] = (char)193;
            _htmlCharacterEntities["aacute"] = (char)225;
            _htmlCharacterEntities["Acirc"] = (char)194;
            _htmlCharacterEntities["acirc"] = (char)226;
            _htmlCharacterEntities["acute"] = (char)180;
            _htmlCharacterEntities["AElig"] = (char)198;
            _htmlCharacterEntities["aelig"] = (char)230;
            _htmlCharacterEntities["Agrave"] = (char)192;
            _htmlCharacterEntities["agrave"] = (char)224;
            _htmlCharacterEntities["alefsym"] = (char)8501;
            _htmlCharacterEntities["Alpha"] = (char)913;
            _htmlCharacterEntities["alpha"] = (char)945;
            _htmlCharacterEntities["amp"] = (char)38;
            _htmlCharacterEntities["and"] = (char)8743;
            _htmlCharacterEntities["ang"] = (char)8736;
            _htmlCharacterEntities["Aring"] = (char)197;
            _htmlCharacterEntities["aring"] = (char)229;
            _htmlCharacterEntities["asymp"] = (char)8776;
            _htmlCharacterEntities["Atilde"] = (char)195;
            _htmlCharacterEntities["atilde"] = (char)227;
            _htmlCharacterEntities["Auml"] = (char)196;
            _htmlCharacterEntities["auml"] = (char)228;
            _htmlCharacterEntities["bdquo"] = (char)8222;
            _htmlCharacterEntities["Beta"] = (char)914;
            _htmlCharacterEntities["beta"] = (char)946;
            _htmlCharacterEntities["brvbar"] = (char)166;
            _htmlCharacterEntities["bull"] = (char)8226;
            _htmlCharacterEntities["cap"] = (char)8745;
            _htmlCharacterEntities["Ccedil"] = (char)199;
            _htmlCharacterEntities["ccedil"] = (char)231;
            _htmlCharacterEntities["cent"] = (char)162;
            _htmlCharacterEntities["Chi"] = (char)935;
            _htmlCharacterEntities["chi"] = (char)967;
            _htmlCharacterEntities["circ"] = (char)710;
            _htmlCharacterEntities["clubs"] = (char)9827;
            _htmlCharacterEntities["cong"] = (char)8773;
            _htmlCharacterEntities["copy"] = (char)169;
            _htmlCharacterEntities["crarr"] = (char)8629;
            _htmlCharacterEntities["cup"] = (char)8746;
            _htmlCharacterEntities["curren"] = (char)164;
            _htmlCharacterEntities["dagger"] = (char)8224;
            _htmlCharacterEntities["Dagger"] = (char)8225;
            _htmlCharacterEntities["darr"] = (char)8595;
            _htmlCharacterEntities["dArr"] = (char)8659;
            _htmlCharacterEntities["deg"] = (char)176;
            _htmlCharacterEntities["Delta"] = (char)916;
            _htmlCharacterEntities["delta"] = (char)948;
            _htmlCharacterEntities["diams"] = (char)9830;
            _htmlCharacterEntities["divide"] = (char)247;
            _htmlCharacterEntities["Eacute"] = (char)201;
            _htmlCharacterEntities["eacute"] = (char)233;
            _htmlCharacterEntities["Ecirc"] = (char)202;
            _htmlCharacterEntities["ecirc"] = (char)234;
            _htmlCharacterEntities["Egrave"] = (char)200;
            _htmlCharacterEntities["egrave"] = (char)232;
            _htmlCharacterEntities["empty"] = (char)8709;
            _htmlCharacterEntities["emsp"] = (char)8195;
            _htmlCharacterEntities["ensp"] = (char)8194;
            _htmlCharacterEntities["Epsilon"] = (char)917;
            _htmlCharacterEntities["epsilon"] = (char)949;
            _htmlCharacterEntities["equiv"] = (char)8801;
            _htmlCharacterEntities["Eta"] = (char)919;
            _htmlCharacterEntities["eta"] = (char)951;
            _htmlCharacterEntities["ETH"] = (char)208;
            _htmlCharacterEntities["eth"] = (char)240;
            _htmlCharacterEntities["Euml"] = (char)203;
            _htmlCharacterEntities["euml"] = (char)235;
            _htmlCharacterEntities["euro"] = (char)8364;
            _htmlCharacterEntities["exist"] = (char)8707;
            _htmlCharacterEntities["fnof"] = (char)402;
            _htmlCharacterEntities["forall"] = (char)8704;
            _htmlCharacterEntities["frac12"] = (char)189;
            _htmlCharacterEntities["frac14"] = (char)188;
            _htmlCharacterEntities["frac34"] = (char)190;
            _htmlCharacterEntities["frasl"] = (char)8260;
            _htmlCharacterEntities["Gamma"] = (char)915;
            _htmlCharacterEntities["gamma"] = (char)947;
            _htmlCharacterEntities["ge"] = (char)8805;
            _htmlCharacterEntities["gt"] = (char)62;
            _htmlCharacterEntities["harr"] = (char)8596;
            _htmlCharacterEntities["hArr"] = (char)8660;
            _htmlCharacterEntities["hearts"] = (char)9829;
            _htmlCharacterEntities["hellip"] = (char)8230;
            _htmlCharacterEntities["Iacute"] = (char)205;
            _htmlCharacterEntities["iacute"] = (char)237;
            _htmlCharacterEntities["Icirc"] = (char)206;
            _htmlCharacterEntities["icirc"] = (char)238;
            _htmlCharacterEntities["iexcl"] = (char)161;
            _htmlCharacterEntities["Igrave"] = (char)204;
            _htmlCharacterEntities["igrave"] = (char)236;
            _htmlCharacterEntities["image"] = (char)8465;
            _htmlCharacterEntities["infin"] = (char)8734;
            _htmlCharacterEntities["int"] = (char)8747;
            _htmlCharacterEntities["Iota"] = (char)921;
            _htmlCharacterEntities["iota"] = (char)953;
            _htmlCharacterEntities["iquest"] = (char)191;
            _htmlCharacterEntities["isin"] = (char)8712;
            _htmlCharacterEntities["Iuml"] = (char)207;
            _htmlCharacterEntities["iuml"] = (char)239;
            _htmlCharacterEntities["Kappa"] = (char)922;
            _htmlCharacterEntities["kappa"] = (char)954;
            _htmlCharacterEntities["Lambda"] = (char)923;
            _htmlCharacterEntities["lambda"] = (char)955;
            _htmlCharacterEntities["lang"] = (char)9001;
            _htmlCharacterEntities["laquo"] = (char)171;
            _htmlCharacterEntities["larr"] = (char)8592;
            _htmlCharacterEntities["lArr"] = (char)8656;
            _htmlCharacterEntities["lceil"] = (char)8968;
            _htmlCharacterEntities["ldquo"] = (char)8220;
            _htmlCharacterEntities["le"] = (char)8804;
            _htmlCharacterEntities["lfloor"] = (char)8970;
            _htmlCharacterEntities["lowast"] = (char)8727;
            _htmlCharacterEntities["loz"] = (char)9674;
            _htmlCharacterEntities["lrm"] = (char)8206;
            _htmlCharacterEntities["lsaquo"] = (char)8249;
            _htmlCharacterEntities["lsquo"] = (char)8216;
            _htmlCharacterEntities["lt"] = (char)60;
            _htmlCharacterEntities["macr"] = (char)175;
            _htmlCharacterEntities["mdash"] = (char)8212;
            _htmlCharacterEntities["micro"] = (char)181;
            _htmlCharacterEntities["middot"] = (char)183;
            _htmlCharacterEntities["minus"] = (char)8722;
            _htmlCharacterEntities["Mu"] = (char)924;
            _htmlCharacterEntities["mu"] = (char)956;
            _htmlCharacterEntities["nabla"] = (char)8711;
            _htmlCharacterEntities["nbsp"] = (char)160;
            _htmlCharacterEntities["ndash"] = (char)8211;
            _htmlCharacterEntities["ne"] = (char)8800;
            _htmlCharacterEntities["ni"] = (char)8715;
            _htmlCharacterEntities["not"] = (char)172;
            _htmlCharacterEntities["notin"] = (char)8713;
            _htmlCharacterEntities["nsub"] = (char)8836;
            _htmlCharacterEntities["Ntilde"] = (char)209;
            _htmlCharacterEntities["ntilde"] = (char)241;
            _htmlCharacterEntities["Nu"] = (char)925;
            _htmlCharacterEntities["nu"] = (char)957;
            _htmlCharacterEntities["Oacute"] = (char)211;
            _htmlCharacterEntities["ocirc"] = (char)244;
            _htmlCharacterEntities["OElig"] = (char)338;
            _htmlCharacterEntities["oelig"] = (char)339;
            _htmlCharacterEntities["Ograve"] = (char)210;
            _htmlCharacterEntities["ograve"] = (char)242;
            _htmlCharacterEntities["oline"] = (char)8254;
            _htmlCharacterEntities["Omega"] = (char)937;
            _htmlCharacterEntities["omega"] = (char)969;
            _htmlCharacterEntities["Omicron"] = (char)927;
            _htmlCharacterEntities["omicron"] = (char)959;
            _htmlCharacterEntities["oplus"] = (char)8853;
            _htmlCharacterEntities["or"] = (char)8744;
            _htmlCharacterEntities["ordf"] = (char)170;
            _htmlCharacterEntities["ordm"] = (char)186;
            _htmlCharacterEntities["Oslash"] = (char)216;
            _htmlCharacterEntities["oslash"] = (char)248;
            _htmlCharacterEntities["Otilde"] = (char)213;
            _htmlCharacterEntities["otilde"] = (char)245;
            _htmlCharacterEntities["otimes"] = (char)8855;
            _htmlCharacterEntities["Ouml"] = (char)214;
            _htmlCharacterEntities["ouml"] = (char)246;
            _htmlCharacterEntities["para"] = (char)182;
            _htmlCharacterEntities["part"] = (char)8706;
            _htmlCharacterEntities["permil"] = (char)8240;
            _htmlCharacterEntities["perp"] = (char)8869;
            _htmlCharacterEntities["Phi"] = (char)934;
            _htmlCharacterEntities["phi"] = (char)966;
            _htmlCharacterEntities["pi"] = (char)960;
            _htmlCharacterEntities["piv"] = (char)982;
            _htmlCharacterEntities["plusmn"] = (char)177;
            _htmlCharacterEntities["pound"] = (char)163;
            _htmlCharacterEntities["prime"] = (char)8242;
            _htmlCharacterEntities["Prime"] = (char)8243;
            _htmlCharacterEntities["prod"] = (char)8719;
            _htmlCharacterEntities["prop"] = (char)8733;
            _htmlCharacterEntities["Psi"] = (char)936;
            _htmlCharacterEntities["psi"] = (char)968;
            _htmlCharacterEntities["quot"] = (char)34;
            _htmlCharacterEntities["radic"] = (char)8730;
            _htmlCharacterEntities["rang"] = (char)9002;
            _htmlCharacterEntities["raquo"] = (char)187;
            _htmlCharacterEntities["rarr"] = (char)8594;
            _htmlCharacterEntities["rArr"] = (char)8658;
            _htmlCharacterEntities["rceil"] = (char)8969;
            _htmlCharacterEntities["rdquo"] = (char)8221;
            _htmlCharacterEntities["real"] = (char)8476;
            _htmlCharacterEntities["reg"] = (char)174;
            _htmlCharacterEntities["rfloor"] = (char)8971;
            _htmlCharacterEntities["Rho"] = (char)929;
            _htmlCharacterEntities["rho"] = (char)961;
            _htmlCharacterEntities["rlm"] = (char)8207;
            _htmlCharacterEntities["rsaquo"] = (char)8250;
            _htmlCharacterEntities["rsquo"] = (char)8217;
            _htmlCharacterEntities["sbquo"] = (char)8218;
            _htmlCharacterEntities["Scaron"] = (char)352;
            _htmlCharacterEntities["scaron"] = (char)353;
            _htmlCharacterEntities["sdot"] = (char)8901;
            _htmlCharacterEntities["sect"] = (char)167;
            _htmlCharacterEntities["shy"] = (char)173;
            _htmlCharacterEntities["Sigma"] = (char)931;
            _htmlCharacterEntities["sigma"] = (char)963;
            _htmlCharacterEntities["sigmaf"] = (char)962;
            _htmlCharacterEntities["sim"] = (char)8764;
            _htmlCharacterEntities["spades"] = (char)9824;
            _htmlCharacterEntities["sub"] = (char)8834;
            _htmlCharacterEntities["sube"] = (char)8838;
            _htmlCharacterEntities["sum"] = (char)8721;
            _htmlCharacterEntities["sup"] = (char)8835;
            _htmlCharacterEntities["sup1"] = (char)185;
            _htmlCharacterEntities["sup2"] = (char)178;
            _htmlCharacterEntities["sup3"] = (char)179;
            _htmlCharacterEntities["supe"] = (char)8839;
            _htmlCharacterEntities["szlig"] = (char)223;
            _htmlCharacterEntities["Tau"] = (char)932;
            _htmlCharacterEntities["tau"] = (char)964;
            _htmlCharacterEntities["there4"] = (char)8756;
            _htmlCharacterEntities["Theta"] = (char)920;
            _htmlCharacterEntities["theta"] = (char)952;
            _htmlCharacterEntities["thetasym"] = (char)977;
            _htmlCharacterEntities["thinsp"] = (char)8201;
            _htmlCharacterEntities["THORN"] = (char)222;
            _htmlCharacterEntities["thorn"] = (char)254;
            _htmlCharacterEntities["tilde"] = (char)732;
            _htmlCharacterEntities["times"] = (char)215;
            _htmlCharacterEntities["trade"] = (char)8482;
            _htmlCharacterEntities["Uacute"] = (char)218;
            _htmlCharacterEntities["uacute"] = (char)250;
            _htmlCharacterEntities["uarr"] = (char)8593;
            _htmlCharacterEntities["uArr"] = (char)8657;
            _htmlCharacterEntities["Ucirc"] = (char)219;
            _htmlCharacterEntities["ucirc"] = (char)251;
            _htmlCharacterEntities["Ugrave"] = (char)217;
            _htmlCharacterEntities["ugrave"] = (char)249;
            _htmlCharacterEntities["uml"] = (char)168;
            _htmlCharacterEntities["upsih"] = (char)978;
            _htmlCharacterEntities["Upsilon"] = (char)933;
            _htmlCharacterEntities["upsilon"] = (char)965;
            _htmlCharacterEntities["Uuml"] = (char)220;
            _htmlCharacterEntities["uuml"] = (char)252;
            _htmlCharacterEntities["weierp"] = (char)8472;
            _htmlCharacterEntities["Xi"] = (char)926;
            _htmlCharacterEntities["xi"] = (char)958;
            _htmlCharacterEntities["Yacute"] = (char)221;
            _htmlCharacterEntities["yacute"] = (char)253;
            _htmlCharacterEntities["yen"] = (char)165;
            _htmlCharacterEntities["Yuml"] = (char)376;
            _htmlCharacterEntities["yuml"] = (char)255;
            _htmlCharacterEntities["Zeta"] = (char)918;
            _htmlCharacterEntities["zeta"] = (char)950;
            _htmlCharacterEntities["zwj"] = (char)8205;
            _htmlCharacterEntities["zwnj"] = (char)8204;
        }

        #endregion Private Methods

        // ---------------------------------------------------------------------
        //
        // Private Fields
        //
        // ---------------------------------------------------------------------

        #region Private Fields

        // html element names
        // this is an array list now, but we may want to make it a hashtable later for better performance
        private static ArrayList _htmlInlineElements;

        private static ArrayList _htmlBlockElements;

        private static ArrayList _htmlOtherOpenableElements;

        // list of html empty element names
        private static ArrayList _htmlEmptyElements;

        // names of html elements for which closing tags are optional, and close when the outer nested element closes
        private static ArrayList _htmlElementsClosingOnParentElementEnd;

        // names of elements that close certain optional closing tag elements when they start
        
        // names of elements closing the colgroup element
        private static ArrayList _htmlElementsClosingColgroup;

        // names of elements closing the dd element
        private static ArrayList _htmlElementsClosingDD;

        // names of elements closing the dt element
        private static ArrayList _htmlElementsClosingDT;

        // names of elements closing the li element
        private static ArrayList _htmlElementsClosingLI;

        // names of elements closing the tbody element
        private static ArrayList _htmlElementsClosingTbody;

        // names of elements closing the td element
        private static ArrayList _htmlElementsClosingTD;

        // names of elements closing the tfoot element
        private static ArrayList _htmlElementsClosingTfoot;

        // names of elements closing thead element
        private static ArrayList _htmlElementsClosingThead;

        // names of elements closing the th element
        private static ArrayList _htmlElementsClosingTH;

        // names of elements closing the tr element
        private static ArrayList _htmlElementsClosingTR;

        // html character entities hashtable
        private static Hashtable _htmlCharacterEntities;

        #endregion Private Fields
    }
}



<|start_filename|>Sample Applications/DataBindingDemo/AddProductWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace DataBindingDemo
{
    /// <summary>
    ///     Interaction logic for AddProductWindow.xaml
    /// </summary>
    public partial class AddProductWindow : Window
    {
        public AddProductWindow()
        {
            InitializeComponent();
        }

        private void OnInit(object sender, RoutedEventArgs e)
        {
            DataContext = new AuctionItem("Type your description here",
                ProductCategory.DvDs, 1, DateTime.Now, ((App) Application.Current).CurrentUser,
                SpecialFeatures.None);
        }

        private void SubmitProduct(object sender, RoutedEventArgs e)
        {
            var item = (AuctionItem) (DataContext);
            ((App) Application.Current).AuctionItems.Add(item);
            Close();
        }
    }
}

<|start_filename|>Sample Applications/LayoutTransitionsDemo/LayoutToLayoutHost.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace LayoutTransitionsDemo
{
    public class LayoutToLayoutHost : Border
    {
        public static readonly DependencyProperty TargetProperty =
            DependencyProperty.Register("Target", typeof (LayoutToLayoutTarget), typeof (LayoutToLayoutHost), null);

        //Animation duration
        private readonly int _timeSpan = 500;
        //Is this a fade-out animation?
        private bool _disappearOnCompletion;
        //This keeps track of time for when all the animations finish
        private DispatcherTimer _refresher;
        //This is kept as a member object so that local animations can affect it
        private TranslateTransform _translation;
        //Should I animate my way to future layout changes?
        public bool AnimateChanges;
        //Am I currently in the middle of an animation?
        public bool Animating;

        public LayoutToLayoutHost()
        {
            Loaded += OnLoad;
        }

        public LayoutToLayoutTarget Target
        {
            get { return (LayoutToLayoutTarget) GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }

        private void OnLoad(object sender, RoutedEventArgs e)
        {
            if (Target != null)
            {
                Debug.WriteLine("Binding Target!!!");
                BindToTarget(Target);
            }
            else
                Debug.WriteLine("Target was NULL!");

            Unloaded += OnUnload; //this gets done here rather in the ctor to avoid a frame bug (Windows OS 1224171)
        }

        /*
         * If the host gets unloaded, break the cyclical reference to make sure the GC does its job
         * */

        private void OnUnload(object sender, RoutedEventArgs e)
        {
            Target.Host = null;
            Target = null;
        }

        /*
         * Link up the Host to the Target and initialize but do not start the timer
         * */

        public void BindToTarget(LayoutToLayoutTarget t)
        {
            Target = t;
            t.Host = this;
            _translation = new TranslateTransform(0, 0);
            RenderTransform = _translation;

            _refresher = new DispatcherTimer {Interval = TimeSpan.FromMilliseconds(_timeSpan)};
            _refresher.Tick += OnAnimStateInvalidated;

            UpdateFromTarget();
        }

        /*
         * Start a new animation
         * */

        public void BeginAnimating(bool disappear)
        {
            if (Animating)
            {
                EndAnimations();
                //numActive -= 4;
            }

            Animating = false;
            AnimateChanges = true;

            _disappearOnCompletion = disappear;

            if (Visibility != Visibility.Visible)
            {
                Visibility = Visibility.Visible;
                Opacity = 0.0;
            }
        }

        /*
         * Do an immediate update, as long as there is not an animation running
         * */

        public void UpdateFromTarget()
        {
            if ((Target == null) || Animating)
                return;

            if (AnimateChanges)
                AnimateFromTarget();
            else
                MatchLayout();
        }

        /*
         * The double-check might not be necessary anymore, but this fixed a layout infinite loop
         * */

        private void MatchLayout()
        {
            if (Width != Target.ActualWidth)
                Width = Target.ActualWidth;

            if (Height != Target.ActualHeight)
                Height = Target.ActualHeight;

            var pt = Target.TranslatePoint(new Point(0, 0), Parent as UIElement);

            var t = RenderTransform as TranslateTransform;

            if (Math.Abs(t.X - pt.X) > 1)
                t.X = pt.X;

            if (Math.Abs(t.Y - pt.Y) > 1)
                t.Y = pt.Y;
        }

        /*
         * Make a local animation for each animated property
         * Base the destination on the new layout position of the target
         * */

        private void AnimateFromTarget()
        {
            var time = _timeSpan;
            Animating = true;
            AnimateChanges = false;

            var pt = Target.TranslatePoint(new Point(0, 0), Parent as UIElement);
            var t = RenderTransform as TranslateTransform;

            BeginAnimation(WidthProperty, SetupDoubleAnimation(Width, Target.ActualWidth, time));
            BeginAnimation(HeightProperty, SetupDoubleAnimation(Height, Target.ActualHeight, time));
            _translation.BeginAnimation(TranslateTransform.XProperty, SetupDoubleAnimation(t.X, pt.X, time));
            _translation.BeginAnimation(TranslateTransform.YProperty, SetupDoubleAnimation(t.Y, pt.Y, time));

            BeginAnimation(OpacityProperty,
                _disappearOnCompletion
                    ? SetupDoubleAnimation(Opacity, 0.0, time)
                    : SetupDoubleAnimation(Opacity, 1.0, time));


            _refresher.IsEnabled = false; //this restarts the timer
            _refresher.IsEnabled = true;
            _refresher.Start();
        }

        /*
         * This gets called by the DispatcherTimer Refresher when it is done
         * */

        private void OnAnimStateInvalidated(object sender, EventArgs e)
        {
            Animating = false;
            _refresher.IsEnabled = false;
            _refresher.Stop();

            EndAnimations();

            if (_disappearOnCompletion)
                Visibility = Visibility.Hidden;
        }

        /*
         * Explicitly replace all of the local animations will null
         * */

        public void EndAnimations()
        {
            var xBuffer = _translation.X;
            var yBuffer = _translation.Y;
            var widthBuffer = Width;
            var heightBuffer = Height;
            var opacityBuffer = Opacity;

            BeginAnimation(WidthProperty, null);
            BeginAnimation(HeightProperty, null);
            _translation.BeginAnimation(TranslateTransform.XProperty, null);
            _translation.BeginAnimation(TranslateTransform.YProperty, null);
            BeginAnimation(OpacityProperty, null);

            _translation.X = xBuffer;
            _translation.Y = yBuffer;
            Height = heightBuffer;
            Width = widthBuffer;
            Opacity = opacityBuffer;
        }

        /*
         * Helper function to create a DoubleAnimation
         * */

        public DoubleAnimation SetupDoubleAnimation(double @from, double to, int time)
        {
            var myDoubleAnimation = new DoubleAnimation
            {
                From = @from,
                To = to,
                Duration = new Duration(TimeSpan.FromMilliseconds(time)),
                AutoReverse = false
            };

            return myDoubleAnimation;
        }

        /*
         * Break the cyclical reference
         * */

        public void ReleaseFromTarget()
        {
            Target.Host = null;
            Target = null;
        }
    }
}

<|start_filename|>Sample Applications/HtmlToXamlDemo/HtmlSchema.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
using System.Diagnostics;

namespace HtmlToXamlDemo
{
    /// <summary>
    ///     HtmlSchema class
    ///     maintains static information about HTML structure
    ///     can be used by HtmlParser to check conditions under which an element starts or ends, etc.
    /// </summary>
    internal class HtmlSchema
    {
        // ---------------------------------------------------------------------
        //
        // Constructors
        //
        // ---------------------------------------------------------------------

        #region Constructors

        /// <summary>
        ///     static constructor, initializes the ArrayLists
        ///     that hold the elements in various sub-components of the schema
        ///     e.g _htmlEmptyElements, etc.
        /// </summary>
        static HtmlSchema()
        {
            // initializes the list of all html elements
            InitializeInlineElements();

            InitializeBlockElements();

            InitializeOtherOpenableElements();

            // initialize empty elements list
            InitializeEmptyElements();

            // initialize list of elements closing on the outer element end
            InitializeElementsClosingOnParentElementEnd();

            // initalize list of elements that close when a new element starts
            InitializeElementsClosingOnNewElementStart();

            // Initialize character entities
            InitializeHtmlCharacterEntities();
        }

        #endregion Constructors;

        // ---------------------------------------------------------------------
        //
        // Internal Methods
        //
        // ---------------------------------------------------------------------

        #region Internal Methods

        /// <summary>
        ///     returns true when xmlElementName corresponds to empty element
        /// </summary>
        /// <param name="xmlElementName">
        ///     string representing name to test
        /// </param>
        internal static bool IsEmptyElement(string xmlElementName) => _htmlEmptyElements.Contains(xmlElementName.ToLower());

        /// <summary>
        ///     returns true if xmlElementName represents a block formattinng element.
        ///     It used in an algorithm of transferring inline elements over block elements
        ///     in HtmlParser
        /// </summary>
        /// <param name="xmlElementName"></param>
        /// <returns></returns>
        internal static bool IsBlockElement(string xmlElementName) => _htmlBlockElements.Contains(xmlElementName);

        /// <summary>
        ///     returns true if the xmlElementName represents an inline formatting element
        /// </summary>
        /// <param name="xmlElementName"></param>
        /// <returns></returns>
        internal static bool IsInlineElement(string xmlElementName) => _htmlInlineElements.Contains(xmlElementName);

        /// <summary>
        ///     It is a list of known html elements which we
        ///     want to allow to produce bt HTML parser,
        ///     but don'tt want to act as inline, block or no-scope.
        ///     Presence in this list will allow to open
        ///     elements during html parsing, and adding the
        ///     to a tree produced by html parser.
        /// </summary>
        internal static bool IsKnownOpenableElement(string xmlElementName) => _htmlOtherOpenableElements.Contains(xmlElementName);

        /// <summary>
        ///     returns true when xmlElementName closes when the outer element closes
        ///     this is true of elements with optional start tags
        /// </summary>
        /// <param name="xmlElementName">
        ///     string representing name to test
        /// </param>
        internal static bool ClosesOnParentElementEnd(string xmlElementName) => _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower());

        /// <summary>
        ///     returns true if the current element closes when the new element, whose name has just been read, starts
        /// </summary>
        /// <param name="currentElementName">
        ///     string representing current element name
        /// </param>
        /// <param name="elementName"></param>
        /// string representing name of the next element that will start
        internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName)
        {
            Debug.Assert(currentElementName == currentElementName.ToLower());
            switch (currentElementName)
            {
                case "colgroup":
                    return _htmlElementsClosingColgroup.Contains(nextElementName) && IsBlockElement(nextElementName);
                case "dd":
                    return _htmlElementsClosingDd.Contains(nextElementName) && IsBlockElement(nextElementName);
                case "dt":
                    return _htmlElementsClosingDt.Contains(nextElementName) && IsBlockElement(nextElementName);
                case "li":
                    return _htmlElementsClosingLi.Contains(nextElementName);
                case "p":
                    return IsBlockElement(nextElementName);
                case "tbody":
                    return _htmlElementsClosingTbody.Contains(nextElementName);
                case "tfoot":
                    return _htmlElementsClosingTfoot.Contains(nextElementName);
                case "thead":
                    return _htmlElementsClosingThead.Contains(nextElementName);
                case "tr":
                    return _htmlElementsClosingTr.Contains(nextElementName);
                case "td":
                    return _htmlElementsClosingTd.Contains(nextElementName);
                case "th":
                    return _htmlElementsClosingTh.Contains(nextElementName);
            }
            return false;
        }

        /// <summary>
        ///     returns true if the string passed as argument is an Html entity name
        /// </summary>
        /// <param name="entityName">
        ///     string to be tested for Html entity name
        /// </param>
        internal static bool IsEntity(string entityName)
        {
            // we do not convert entity strings to lowercase because these names are case-sensitive
            if (_htmlCharacterEntities.Contains(entityName))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        ///     returns the character represented by the entity name string which is passed as an argument, if the string is an
        ///     entity name
        ///     as specified in _htmlCharacterEntities, returns the character value of 0 otherwise
        /// </summary>
        /// <param name="entityName">
        ///     string representing entity name whose character value is desired
        /// </param>
        internal static char EntityCharacterValue(string entityName)
        {
            if (_htmlCharacterEntities.Contains(entityName))
            {
                return (char) _htmlCharacterEntities[entityName];
            }
            return (char) 0;
        }

        #endregion Internal Methods

        // ---------------------------------------------------------------------
        //
        //  Internal Properties
        //
        // ---------------------------------------------------------------------

        #region Internal Properties

        #endregion Internal Indexers

        // ---------------------------------------------------------------------
        //
        // Private Methods
        //
        // ---------------------------------------------------------------------

        #region Private Methods

        private static void InitializeInlineElements()
        {
            _htmlInlineElements = new ArrayList
            {
                "a",
                "abbr",
                "acronym",
                "address",
                "b",
                "bdo",
                "big",
                "button",
                "code",
                "del",
                "dfn",
                "em",
                "font",
                "i",
                "ins",
                "kbd",
                "label",
                "legend",
                "q",
                "s",
                "samp",
                "small",
                "span",
                "strike",
                "strong",
                "sub",
                "sup",
                "u",
                "var"
            };
            // ???
            // deleted text
            // inserted text
            // text to entered by a user
            // ???
            // short inline quotation
            // strike-through text style
            // Specifies a code sample
            // indicates an instance of a program variable
        }

        private static void InitializeBlockElements()
        {
            _htmlBlockElements = new ArrayList
            {
                "blockquote",
                "body",
                "caption",
                "center",
                "cite",
                "dd",
                "dir",
                "div",
                "dl",
                "dt",
                "form",
                "h1",
                "h2",
                "h3",
                "h4",
                "h5",
                "h6",
                "html",
                "li",
                "menu",
                "ol",
                "p",
                "pre",
                "table",
                "tbody",
                "td",
                "textarea",
                "tfoot",
                "th",
                "thead",
                "tr",
                "tt",
                "ul"
            };

            //  treat as UL element
            // Not a block according to XHTML spec
            //  treat as UL element
            // Renders text in a fixed-width font
        }

        /// <summary>
        ///     initializes _htmlEmptyElements with empty elements in HTML 4 spec at
        ///     http://www.w3.org/TR/REC-html40/index/elements.html
        /// </summary>
        private static void InitializeEmptyElements()
        {
            // Build a list of empty (no-scope) elements 
            // (element not requiring closing tags, and not accepting any content)
            _htmlEmptyElements = new ArrayList
            {
                "area",
                "base",
                "basefont",
                "br",
                "col",
                "frame",
                "hr",
                "img",
                "input",
                "isindex",
                "link",
                "meta",
                "param"
            };
        }

        private static void InitializeOtherOpenableElements()
        {
            // It is a list of known html elements which we
            // want to allow to produce bt HTML parser,
            // but don'tt want to act as inline, block or no-scope.
            // Presence in this list will allow to open
            // elements during html parsing, and adding the
            // to a tree produced by html parser.
            _htmlOtherOpenableElements = new ArrayList
            {
                "applet",
                "base",
                "basefont",
                "colgroup",
                "fieldset",
                "frameset",
                "head",
                "iframe",
                "map",
                "noframes",
                "noscript",
                "object",
                "optgroup",
                "option",
                "script",
                "select",
                "style",
                "title"
            };
            //_htmlOtherOpenableElements.Add("form"); --> treated as block
        }

        /// <summary>
        ///     initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are
        ///     optional
        ///     we assume that for any element for which closing tags are optional, the element closes when it's outer element
        ///     (in which it is nested) does
        /// </summary>
        private static void InitializeElementsClosingOnParentElementEnd()
        {
            _htmlElementsClosingOnParentElementEnd = new ArrayList
            {
                "body",
                "colgroup",
                "dd",
                "dt",
                "head",
                "html",
                "li",
                "p",
                "tbody",
                "td",
                "tfoot",
                "thead",
                "th",
                "tr"
            };
        }

        private static void InitializeElementsClosingOnNewElementStart()
        {
            _htmlElementsClosingColgroup = new ArrayList {"colgroup", "tr", "thead", "tfoot", "tbody"};

            _htmlElementsClosingDd = new ArrayList {"dd", "dt"};
            // TODO: dd may end in other cases as well - if a new "p" starts, etc.
            // TODO: these are the basic "legal" cases but there may be more recovery

            _htmlElementsClosingDt = new ArrayList();
            _htmlElementsClosingDd.Add("dd");
            _htmlElementsClosingDd.Add("dt");
            // TODO: dd may end in other cases as well - if a new "p" starts, etc.
            // TODO: these are the basic "legal" cases but there may be more recovery

            _htmlElementsClosingLi = new ArrayList {"li"};
            // TODO: more complex recovery

            _htmlElementsClosingTbody = new ArrayList {"tbody", "thead", "tfoot"};
            // TODO: more complex recovery

            _htmlElementsClosingTr = new ArrayList {"thead", "tfoot", "tbody", "tr"};
            // NOTE: tr should not really close on a new thead
            // because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional
            // and thead can't come after tbody
            // however, if we do encounter this, it's probably best to end the row and ignore the thead or treat
            // it as part of the table
            // TODO: more complex recovery

            _htmlElementsClosingTd = new ArrayList {"td", "th", "tr", "tbody", "tfoot", "thead"};
            // TODO: more complex recovery

            _htmlElementsClosingTh = new ArrayList {"td", "th", "tr", "tbody", "tfoot", "thead"};
            // TODO: more complex recovery

            _htmlElementsClosingThead = new ArrayList {"tbody", "tfoot"};
            // TODO: more complex recovery

            _htmlElementsClosingTfoot = new ArrayList {"tbody", "thead"};
            // although thead comes before tfoot, we add it because if it is found the tfoot should close
            // and some recovery processing be done on the thead
            // TODO: more complex recovery
        }

        /// <summary>
        ///     initializes _htmlCharacterEntities hashtable with the character corresponding to entity names
        /// </summary>
        private static void InitializeHtmlCharacterEntities()
        {
            _htmlCharacterEntities = new Hashtable
            {
                ["Aacute"] = (char) 193,
                ["aacute"] = (char) 225,
                ["Acirc"] = (char) 194,
                ["acirc"] = (char) 226,
                ["acute"] = (char) 180,
                ["AElig"] = (char) 198,
                ["aelig"] = (char) 230,
                ["Agrave"] = (char) 192,
                ["agrave"] = (char) 224,
                ["alefsym"] = (char) 8501,
                ["Alpha"] = (char) 913,
                ["alpha"] = (char) 945,
                ["amp"] = (char) 38,
                ["and"] = (char) 8743,
                ["ang"] = (char) 8736,
                ["Aring"] = (char) 197,
                ["aring"] = (char) 229,
                ["asymp"] = (char) 8776,
                ["Atilde"] = (char) 195,
                ["atilde"] = (char) 227,
                ["Auml"] = (char) 196,
                ["auml"] = (char) 228,
                ["bdquo"] = (char) 8222,
                ["Beta"] = (char) 914,
                ["beta"] = (char) 946,
                ["brvbar"] = (char) 166,
                ["bull"] = (char) 8226,
                ["cap"] = (char) 8745,
                ["Ccedil"] = (char) 199,
                ["ccedil"] = (char) 231,
                ["cent"] = (char) 162,
                ["Chi"] = (char) 935,
                ["chi"] = (char) 967,
                ["circ"] = (char) 710,
                ["clubs"] = (char) 9827,
                ["cong"] = (char) 8773,
                ["copy"] = (char) 169,
                ["crarr"] = (char) 8629,
                ["cup"] = (char) 8746,
                ["curren"] = (char) 164,
                ["dagger"] = (char) 8224,
                ["Dagger"] = (char) 8225,
                ["darr"] = (char) 8595,
                ["dArr"] = (char) 8659,
                ["deg"] = (char) 176,
                ["Delta"] = (char) 916,
                ["delta"] = (char) 948,
                ["diams"] = (char) 9830,
                ["divide"] = (char) 247,
                ["Eacute"] = (char) 201,
                ["eacute"] = (char) 233,
                ["Ecirc"] = (char) 202,
                ["ecirc"] = (char) 234,
                ["Egrave"] = (char) 200,
                ["egrave"] = (char) 232,
                ["empty"] = (char) 8709,
                ["emsp"] = (char) 8195,
                ["ensp"] = (char) 8194,
                ["Epsilon"] = (char) 917,
                ["epsilon"] = (char) 949,
                ["equiv"] = (char) 8801,
                ["Eta"] = (char) 919,
                ["eta"] = (char) 951,
                ["ETH"] = (char) 208,
                ["eth"] = (char) 240,
                ["Euml"] = (char) 203,
                ["euml"] = (char) 235,
                ["euro"] = (char) 8364,
                ["exist"] = (char) 8707,
                ["fnof"] = (char) 402,
                ["forall"] = (char) 8704,
                ["frac12"] = (char) 189,
                ["frac14"] = (char) 188,
                ["frac34"] = (char) 190,
                ["frasl"] = (char) 8260,
                ["Gamma"] = (char) 915,
                ["gamma"] = (char) 947,
                ["ge"] = (char) 8805,
                ["gt"] = (char) 62,
                ["harr"] = (char) 8596,
                ["hArr"] = (char) 8660,
                ["hearts"] = (char) 9829,
                ["hellip"] = (char) 8230,
                ["Iacute"] = (char) 205,
                ["iacute"] = (char) 237,
                ["Icirc"] = (char) 206,
                ["icirc"] = (char) 238,
                ["iexcl"] = (char) 161,
                ["Igrave"] = (char) 204,
                ["igrave"] = (char) 236,
                ["image"] = (char) 8465,
                ["infin"] = (char) 8734,
                ["int"] = (char) 8747,
                ["Iota"] = (char) 921,
                ["iota"] = (char) 953,
                ["iquest"] = (char) 191,
                ["isin"] = (char) 8712,
                ["Iuml"] = (char) 207,
                ["iuml"] = (char) 239,
                ["Kappa"] = (char) 922,
                ["kappa"] = (char) 954,
                ["Lambda"] = (char) 923,
                ["lambda"] = (char) 955,
                ["lang"] = (char) 9001,
                ["laquo"] = (char) 171,
                ["larr"] = (char) 8592,
                ["lArr"] = (char) 8656,
                ["lceil"] = (char) 8968,
                ["ldquo"] = (char) 8220,
                ["le"] = (char) 8804,
                ["lfloor"] = (char) 8970,
                ["lowast"] = (char) 8727,
                ["loz"] = (char) 9674,
                ["lrm"] = (char) 8206,
                ["lsaquo"] = (char) 8249,
                ["lsquo"] = (char) 8216,
                ["lt"] = (char) 60,
                ["macr"] = (char) 175,
                ["mdash"] = (char) 8212,
                ["micro"] = (char) 181,
                ["middot"] = (char) 183,
                ["minus"] = (char) 8722,
                ["Mu"] = (char) 924,
                ["mu"] = (char) 956,
                ["nabla"] = (char) 8711,
                ["nbsp"] = (char) 160,
                ["ndash"] = (char) 8211,
                ["ne"] = (char) 8800,
                ["ni"] = (char) 8715,
                ["not"] = (char) 172,
                ["notin"] = (char) 8713,
                ["nsub"] = (char) 8836,
                ["Ntilde"] = (char) 209,
                ["ntilde"] = (char) 241,
                ["Nu"] = (char) 925,
                ["nu"] = (char) 957,
                ["Oacute"] = (char) 211,
                ["ocirc"] = (char) 244,
                ["OElig"] = (char) 338,
                ["oelig"] = (char) 339,
                ["Ograve"] = (char) 210,
                ["ograve"] = (char) 242,
                ["oline"] = (char) 8254,
                ["Omega"] = (char) 937,
                ["omega"] = (char) 969,
                ["Omicron"] = (char) 927,
                ["omicron"] = (char) 959,
                ["oplus"] = (char) 8853,
                ["or"] = (char) 8744,
                ["ordf"] = (char) 170,
                ["ordm"] = (char) 186,
                ["Oslash"] = (char) 216,
                ["oslash"] = (char) 248,
                ["Otilde"] = (char) 213,
                ["otilde"] = (char) 245,
                ["otimes"] = (char) 8855,
                ["Ouml"] = (char) 214,
                ["ouml"] = (char) 246,
                ["para"] = (char) 182,
                ["part"] = (char) 8706,
                ["permil"] = (char) 8240,
                ["perp"] = (char) 8869,
                ["Phi"] = (char) 934,
                ["phi"] = (char) 966,
                ["pi"] = (char) 960,
                ["piv"] = (char) 982,
                ["plusmn"] = (char) 177,
                ["pound"] = (char) 163,
                ["prime"] = (char) 8242,
                ["Prime"] = (char) 8243,
                ["prod"] = (char) 8719,
                ["prop"] = (char) 8733,
                ["Psi"] = (char) 936,
                ["psi"] = (char) 968,
                ["quot"] = (char) 34,
                ["radic"] = (char) 8730,
                ["rang"] = (char) 9002,
                ["raquo"] = (char) 187,
                ["rarr"] = (char) 8594,
                ["rArr"] = (char) 8658,
                ["rceil"] = (char) 8969,
                ["rdquo"] = (char) 8221,
                ["real"] = (char) 8476,
                ["reg"] = (char) 174,
                ["rfloor"] = (char) 8971,
                ["Rho"] = (char) 929,
                ["rho"] = (char) 961,
                ["rlm"] = (char) 8207,
                ["rsaquo"] = (char) 8250,
                ["rsquo"] = (char) 8217,
                ["sbquo"] = (char) 8218,
                ["Scaron"] = (char) 352,
                ["scaron"] = (char) 353,
                ["sdot"] = (char) 8901,
                ["sect"] = (char) 167,
                ["shy"] = (char) 173,
                ["Sigma"] = (char) 931,
                ["sigma"] = (char) 963,
                ["sigmaf"] = (char) 962,
                ["sim"] = (char) 8764,
                ["spades"] = (char) 9824,
                ["sub"] = (char) 8834,
                ["sube"] = (char) 8838,
                ["sum"] = (char) 8721,
                ["sup"] = (char) 8835,
                ["sup1"] = (char) 185,
                ["sup2"] = (char) 178,
                ["sup3"] = (char) 179,
                ["supe"] = (char) 8839,
                ["szlig"] = (char) 223,
                ["Tau"] = (char) 932,
                ["tau"] = (char) 964,
                ["there4"] = (char) 8756,
                ["Theta"] = (char) 920,
                ["theta"] = (char) 952,
                ["thetasym"] = (char) 977,
                ["thinsp"] = (char) 8201,
                ["THORN"] = (char) 222,
                ["thorn"] = (char) 254,
                ["tilde"] = (char) 732,
                ["times"] = (char) 215,
                ["trade"] = (char) 8482,
                ["Uacute"] = (char) 218,
                ["uacute"] = (char) 250,
                ["uarr"] = (char) 8593,
                ["uArr"] = (char) 8657,
                ["Ucirc"] = (char) 219,
                ["ucirc"] = (char) 251,
                ["Ugrave"] = (char) 217,
                ["ugrave"] = (char) 249,
                ["uml"] = (char) 168,
                ["upsih"] = (char) 978,
                ["Upsilon"] = (char) 933,
                ["upsilon"] = (char) 965,
                ["Uuml"] = (char) 220,
                ["uuml"] = (char) 252,
                ["weierp"] = (char) 8472,
                ["Xi"] = (char) 926,
                ["xi"] = (char) 958,
                ["Yacute"] = (char) 221,
                ["yacute"] = (char) 253,
                ["yen"] = (char) 165,
                ["Yuml"] = (char) 376,
                ["yuml"] = (char) 255,
                ["Zeta"] = (char) 918,
                ["zeta"] = (char) 950,
                ["zwj"] = (char) 8205,
                ["zwnj"] = (char) 8204
            };
        }

        #endregion Private Methods

        // ---------------------------------------------------------------------
        //
        // Private Fields
        //
        // ---------------------------------------------------------------------

        #region Private Fields

        // html element names
        // this is an array list now, but we may want to make it a hashtable later for better performance
        private static ArrayList _htmlInlineElements;

        private static ArrayList _htmlBlockElements;

        private static ArrayList _htmlOtherOpenableElements;

        // list of html empty element names
        private static ArrayList _htmlEmptyElements;

        // names of html elements for which closing tags are optional, and close when the outer nested element closes
        private static ArrayList _htmlElementsClosingOnParentElementEnd;

        // names of elements that close certain optional closing tag elements when they start

        // names of elements closing the colgroup element
        private static ArrayList _htmlElementsClosingColgroup;

        // names of elements closing the dd element
        private static ArrayList _htmlElementsClosingDd;

        // names of elements closing the dt element
        private static ArrayList _htmlElementsClosingDt;

        // names of elements closing the li element
        private static ArrayList _htmlElementsClosingLi;

        // names of elements closing the tbody element
        private static ArrayList _htmlElementsClosingTbody;

        // names of elements closing the td element
        private static ArrayList _htmlElementsClosingTd;

        // names of elements closing the tfoot element
        private static ArrayList _htmlElementsClosingTfoot;

        // names of elements closing the thead element
        private static ArrayList _htmlElementsClosingThead;

        // names of elements closing the th element
        private static ArrayList _htmlElementsClosingTh;

        // names of elements closing the tr element
        private static ArrayList _htmlElementsClosingTr;

        // html character entities hashtable
        private static Hashtable _htmlCharacterEntities;

        #endregion Private Fields
    }
}

<|start_filename|>Events/RoutedEventHandling/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Text;
using System.Windows;

namespace RoutedEventHandling
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly StringBuilder _eventstr = new StringBuilder();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void HandleClick(object sender, RoutedEventArgs args)
        {
            var fe = (FrameworkElement) sender;
            _eventstr.Append("Event handled by element named ");
            _eventstr.Append(fe.Name);
            _eventstr.Append("\n");
            var fe2 = (FrameworkElement) args.Source;
            _eventstr.Append("Event originated from source element of type ");
            _eventstr.Append(args.Source.GetType());
            _eventstr.Append(" with Name ");
            _eventstr.Append(fe2.Name);
            _eventstr.Append("\n");
            _eventstr.Append("Event used routing strategy ");
            _eventstr.Append(args.RoutedEvent.RoutingStrategy);
            _eventstr.Append("\n");
            results.Text = _eventstr.ToString();
        }
    }
}

<|start_filename|>Globalization and Localization/LocalizationResources/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Reflection;
using System.Resources;
using System.Windows;

namespace LocalizationResources
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var rm = new ResourceManager
                ("LocalizationResources.data.stringtable", Assembly.GetExecutingAssembly());
            Title = rm.GetString("Title");
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            var rm = new ResourceManager("LocalizationResources.data.stringtable",
                Assembly.GetExecutingAssembly());
            Text1.Text = rm.GetString("Message");
        }
    }
}

<|start_filename|>Application Management/SingleInstanceDetection/EntryPoint.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace SingleInstanceDetection
{
    public class EntryPoint
    {
        [STAThread]
        public static void Main(string[] args)
        {
            var manager = new SingleInstanceManager();
            manager.Run(args);
        }
    }

    // Using VB bits to detect single instances and process accordingly:
    //  * OnStartup is fired when the first instance loads
    //  * OnStartupNextInstance is fired when the application is re-run again
    //    NOTE: it is redirected to this instance thanks to IsSingleInstance
}

<|start_filename|>Accessibility/FindText/FindTextClient/FindText.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace FindTextClient
{
    public class FindText : Application
    {
        /// <summary>
        ///     Handles our application startup.
        /// </summary>
        /// <param name="e">Event arguments.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
            // Initialize the sample
            new SearchWindow();
        }

        /// <summary>
        ///     The main entry point for the application.
        /// </summary>
        // Launch the sample application.
        internal sealed class TestMain
        {
            [STAThread]
            private static void Main()
            {
                // Create an instance of the sample class and call its Run() method to start it.
                var app = new FindText();
                app.Run();
            }
        }
    }
}

<|start_filename|>Sample Applications/HtmlToXamlDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace HtmlToXamlDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public void ConvertContent(object sender, RoutedEventArgs e)
        {
            myTextBox.Text = HtmlToXamlConverter.ConvertHtmlToXaml(myTextBox.Text, true);
            MessageBox.Show("Content Conversion Complete!");
        }

        public void CopyXaml(object sender, RoutedEventArgs e)
        {
            myTextBox.SelectAll();
            myTextBox.Copy();
        }

        public void ConvertContent2(object sender, RoutedEventArgs e)
        {
            myTextBox2.Text = HtmlFromXamlConverter.ConvertXamlToHtml(myTextBox2.Text);
            MessageBox.Show("Content Conversion Complete!");
        }

        public void CopyHtml(object sender, RoutedEventArgs e)
        {
            myTextBox2.SelectAll();
            myTextBox2.Copy();
        }
    }
}

<|start_filename|>Data Binding/ADODataSet/IntColorConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

namespace ADODataSet
{
    public class IntColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var numValue = (int) value;
            return numValue < 350 ? Brushes.Green : Brushes.Red;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => null;
    }
}

<|start_filename|>Windows/Wizard/WizardData.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Wizard
{
    /// <summary>
    ///     Data that is collected by the wizard
    /// </summary>
    public class WizardData
    {
        public string DataItem1 { get; set; }
        public string DataItem2 { get; set; }
        public string DataItem3 { get; set; }
    }
}

<|start_filename|>Getting Started/ControlsAndLayout/ControlsAndLayout/Scene.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;

namespace ControlsAndLayout
{
    public partial class Scene
    {
        public bool RealTimeUpdate = true;

        private void HandleSelectionChanged(object sender, SelectionChangedEventArgs args)
        {
            if (sender == null)
                return;

            Details.DataContext = (sender as ListBox).DataContext;
        }

        protected void HandleTextChanged(object sender, TextChangedEventArgs me)
        {
            if (RealTimeUpdate) ParseCurrentBuffer();
        }

        private void ParseCurrentBuffer()
        {
            try
            {
                var ms = new MemoryStream();
                var sw = new StreamWriter(ms);
                var str = TextBox1.Text;
                sw.Write(str);
                sw.Flush();
                ms.Flush();
                ms.Position = 0;
                try
                {
                    var content = XamlReader.Load(ms);
                    if (content != null)
                    {
                        cc.Children.Clear();
                        cc.Children.Add((UIElement) content);
                    }
                    TextBox1.Foreground = Brushes.Black;
                    ErrorText.Text = "";
                }

                catch (XamlParseException xpe)
                {
                    TextBox1.Foreground = Brushes.Red;
                    TextBox1.TextWrapping = TextWrapping.Wrap;
                    ErrorText.Text = xpe.Message;
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }

        protected void OnClickParseButton(object sender, RoutedEventArgs args)
        {
            ParseCurrentBuffer();
        }

        protected void ShowPreview(object sender, RoutedEventArgs args)
        {
            PreviewRow.Height = new GridLength(1, GridUnitType.Star);
            CodeRow.Height = new GridLength(0);
        }

        protected void ShowCode(object sender, RoutedEventArgs args)
        {
            PreviewRow.Height = new GridLength(0);
            CodeRow.Height = new GridLength(1, GridUnitType.Star);
        }

        protected void ShowSplit(object sender, RoutedEventArgs args)
        {
            PreviewRow.Height = new GridLength(1, GridUnitType.Star);
            CodeRow.Height = new GridLength(1, GridUnitType.Star);
        }
    }
}

<|start_filename|>Sample Applications/PhotoStoreDemo/PrintType.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace PhotoStoreDemo
{
    public class PrintType
    {
        public PrintType(string description, double cost)
        {
            Description = description;
            Cost = cost;
        }

        public string Description { get; }
        public double Cost { get; }

        public override string ToString() => Description;
    }
}

<|start_filename|>Documents/Flow Content/FlowContentProperty/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace FlowContentProperty
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public void Lr(object sender, RoutedEventArgs e)
        {
            tf1.FlowDirection = FlowDirection.LeftToRight;
            txt1.Text = "FlowDirection is now " + tf1.FlowDirection;
        }

        public void Rl(object sender, RoutedEventArgs e)
        {
            tf1.FlowDirection = FlowDirection.RightToLeft;
            txt1.Text = "FlowDirection is now " + tf1.FlowDirection;
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/AttributeInfoTableEntry.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

namespace BamlTools
{
    public class AttributeInfoTableEntry
    {
        private readonly int _attributeId;
        private readonly string _name;
        private readonly int _ownerTypeId;

        public AttributeInfoTableEntry(int attributeId, string name, int ownerTypeId)
        {
            _attributeId = attributeId;
            _name = name;
            _ownerTypeId = ownerTypeId;
        }

        public int AttributeId
        {
            get { return _attributeId; }
        }

        public String Name
        {
            get { return _name; }
        }

        public int OwnerTypeId
        {
            get { return _ownerTypeId; }
        }

    }
}


<|start_filename|>Globalization and Localization/StringLocalizationSample/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace StringLocalizationSample
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void messageBoxButton_Click(object sender, RoutedEventArgs e)
        {
            // Programmatic use of string resource from StringResources.xaml resource dictionary
            var localizedMessage = (string) Application.Current.FindResource("LocalizedMessage");
            MessageBox.Show(localizedMessage);
        }
    }
}


<|start_filename|>Sample Applications/EditingExaminerDemo/ReflectionUtils.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Security.Permissions;
using System.Text;

namespace EditingExaminerDemo
{

    #region Namespaces.

    #endregion Namespaces.

    /// <summary>
    ///     Provides Reflection utility methods for test cases.
    /// </summary>
    public static class ReflectionUtils
    {
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        #region Public methods.

        /// <summary>Adds an event handler to a named event on an object.</summary>
        /// <param name='target'>Object on which to add event handler.</param>
        /// <param name='eventName'>Name of event to add to.</param>
        /// <param name='handler'>Delegate for event.</param>
        public static void AddInstanceEventHandler(object target, string eventName, Delegate handler)
        {
            AddRemoveInstanceEventHandler(target, eventName, handler, true);
        }

        /// <summary>
        ///     Creates an instance of the specified type.
        /// </summary>
        /// <param name="type">The type of object to create.</param>
        /// <returns>A reference to the newly created object.</returns>
        public static object CreateInstance(Type type) => Activator.CreateInstance(type);

        /// <summary>
        ///     Supply type name and it will create the object for you.
        /// </summary>
        /// <param name="typeName">name of the type it will try to create</param>
        /// <param name="args">args to the ctor of the object</param>
        /// <returns>A new instance of the specified type.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object CreateInstanceOfType(string typeName, object[] args)
        {
            Type type; // Type to be created.

            if (typeName == null)
            {
                throw new ArgumentNullException(nameof(typeName));
            }
            if (typeName.Length == 0)
            {
                throw new ArgumentException("typeName should not be empty.",
                    nameof(typeName));
            }

            new ReflectionPermission(
                PermissionState.Unrestricted).
                Assert();

            type = FindType(typeName);
            if (type == null)
            {
                throw new Exception("FindType failed to find type " + typeName);
            }

            // we let it throw exception when error occurs.
            // ============================================
            return Activator.CreateInstance(type, args, null);
        }


        /// <summary>
        ///     Retrieves a type given its name.
        /// </summary>
        /// <param name='typeName'>
        ///     Simple name, name with namespace, or type name with
        ///     partial or fully qualified assembly to look for.
        /// </param>
        /// <returns>The specified Type.</returns>
        /// <remarks>
        ///     If an assembly is specified, then this method is equivalent
        ///     to calling Type.GetType(). Otherwise, all loaded assemblies
        ///     will be used to look for the type (unlike Type.GetType(),
        ///     which would only look in the calling assembly and in mscorlib).
        /// </remarks>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static Type FindType(string typeName)
        {
            Type returnValue = null;
            var preferedType = "System.Windows";
            if (typeName == null)
                throw new ArgumentNullException(nameof(typeName));

            // A comma indicates a type with an assembly reference
            if (typeName.IndexOf(',') != -1)
                return Type.GetType(typeName, true);

            // A period indicates a namespace is present.
            var hasNamespace = typeName.IndexOf('.') != -1;

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var assembly in assemblies)
            {
                if (hasNamespace)
                {
                    var t = assembly.GetType(typeName);
                    if (t != null)
                    {
                        return t;
                    }
                }
                else
                {
                    // For type names that are not fully qualified
                    // and don't even have namespaces, explicitly
                    // opt out of WinForms (avoids collision with WPF
                    // the more common case).
                    if (assembly.FullName.Contains("Forms"))
                    {
                        continue;
                    }
                    var testTypes = SafeGetTypes(assembly);
                    foreach (var type in testTypes)
                    {
                        if (type != null && type.Name == typeName)
                        {
                            if (type.FullName.Contains(preferedType))
                            {
                                return type;
                            }
                            if (returnValue == null)
                            {
                                returnValue = type;
                            }
                        }
                    }
                }
            }
            if (returnValue != null)
            {
                return returnValue;
            }
            throw new InvalidOperationException(
                "Unable to find type [" + typeName + "] in loaded assemblies");
        }

        /// <summary>
        ///     Gets the name of a type from the (possibly) full-qualified name.
        /// </summary>
        /// <param name="fullTypeName">Full name of type.</param>
        /// <returns>The bare name.</returns>
        /// <example>
        ///     The following code shows how to use this method.
        ///     <code>...
        /// private void LogTypeName() {
        ///   string typeName = "My.Namespace.Type.HelloThere, myassembly ver1.2.";
        ///   System.Diagnostics.Debug.Assert(TestFinder.GetNameFromFullTypeName(typeName) == "HelloThere");
        /// }
        /// </code>
        /// </example>
        public static string GetNameFromFullTypeName(string fullTypeName)
        {
            if (fullTypeName == null)
            {
                throw new ArgumentNullException(nameof(fullTypeName));
            }
            if (fullTypeName.Length == 0)
            {
                throw new ArgumentException("Full type name cannot be empty", nameof(fullTypeName));
            }
            // Remove the assembly reference.
            var comma = fullTypeName.IndexOf(',');
            if (comma != -1)
            {
                fullTypeName = fullTypeName.Substring(0, comma);
            }
            // Remove the prefixed namespaces.
            var lastPeriod = fullTypeName.LastIndexOf('.');
            if (lastPeriod == -1)
                return fullTypeName;
            return fullTypeName.Substring(lastPeriod + 1);
        }

        /// <summary>
        ///     Retrieves the value of a named field, disregarding the
        ///     visibility.
        /// </summary>
        /// <param name="target">Object from which to get value.</param>
        /// <param name="fieldName">Name of the field.</param>
        /// <returns>The value of the specified field.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object GetField(object target, string fieldName)
        {
            Type type;
            Type queryType;
            FieldInfo fieldInfo;

            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (fieldName == null)
            {
                throw new ArgumentNullException(nameof(fieldName));
            }
            if (fieldName.Length == 0)
            {
                throw new ArgumentException("Field name cannot be blank", fieldName);
            }

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();
            const BindingFlags bindingAttr =
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Instance | BindingFlags.Static |
                BindingFlags.FlattenHierarchy;

            type = target.GetType();
            queryType = type;
            fieldInfo = queryType.GetField(fieldName, bindingAttr);
            while (fieldInfo == null && queryType != typeof (object))
            {
                queryType = queryType.BaseType;
                fieldInfo = queryType?.GetField(fieldName, bindingAttr);
            }
            if (fieldInfo == null)
            {
                throw new InvalidOperationException(
                    "Unable to retrieve field information for field [" +
                    fieldName + "] with attributes [" + bindingAttr +
                    "] from type [" + type + "]");
            }
            return fieldInfo.GetValue(target);
        }

        /// <summary>
        ///     Retrieves the value of a named property as implementing the
        ///     specified interface.
        /// </summary>
        /// <param name="target">Object from which to get value.</param>
        /// <param name="interfaceName">Name of the interface on which property is declared.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>The value of the specified property.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object GetInterfaceProperty(object target,
            string interfaceName, string propertyName)
        {
            BindingFlags bindingFlags; // Flags to match property to get.
            Type type; // Type to get property from.

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();

            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (interfaceName == null)
            {
                throw new ArgumentNullException(nameof(interfaceName));
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }

            type = target.GetType();
            type = type.GetInterface(interfaceName);
            bindingFlags = BindingFlags.Public | BindingFlags.NonPublic |
                           BindingFlags.ExactBinding | BindingFlags.FlattenHierarchy |
                           BindingFlags.Instance | BindingFlags.GetProperty;
            return type.InvokeMember(propertyName, bindingFlags, null, target, null);
        }

        /// <summary>
        ///     Retrieves the value of a named property.
        /// </summary>
        /// <param name="target">Object from which to get value.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>The value of the specified property.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object GetProperty(object target, string propertyName)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }
            if (propertyName.Length == 0)
            {
                throw new ArgumentException("Property name cannot be blank", propertyName);
            }

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();
            const BindingFlags bindingAttr =
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Instance | BindingFlags.Static |
                BindingFlags.FlattenHierarchy;
            var type = target.GetType();
            var propertyInfo = type.GetProperty(propertyName, bindingAttr);
            if (propertyInfo == null)
            {
                throw new InvalidOperationException(
                    "Unable to retrieve property information for property [" +
                    propertyName + "] with attributes [" + bindingAttr +
                    "] from type [" + type + "]");
            }
            return propertyInfo.GetValue(target, null);
        }

        /// <summary>
        ///     Retrieves the value of a static named field.
        /// </summary>
        /// <param name="type">Type from which to get value.</param>
        /// <param name="fieldName">Name of the field.</param>
        /// <returns>The value of the specified field.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object GetStaticField(Type type, string fieldName)
        {
            FieldInfo fieldInfo;

            const BindingFlags bindingAttr =
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Static | BindingFlags.FlattenHierarchy;

            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (fieldName == null)
            {
                throw new ArgumentNullException(nameof(fieldName));
            }
            if (fieldName.Length == 0)
            {
                throw new ArgumentException("Field name cannot be blank", fieldName);
            }

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();
            fieldInfo = type.GetField(fieldName, bindingAttr);
            if (fieldInfo == null)
            {
                throw new InvalidOperationException(
                    "Unable to retrieve field information for property [" +
                    fieldName + "] with attributes [" + bindingAttr +
                    "] from type [" + type + "]");
            }
            return fieldInfo.GetValue(null);
        }

        /// <summary>
        ///     Retrieves the value of a static named property.
        /// </summary>
        /// <param name="type">Type from which to get value.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>The value of the specified property.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object GetStaticProperty(Type type, string propertyName)
        {
            PropertyInfo propertyInfo;

            const BindingFlags bindingAttr =
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Static | BindingFlags.FlattenHierarchy;

            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }
            if (propertyName.Length == 0)
            {
                throw new ArgumentException("Property name cannot be blank", propertyName);
            }

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();
            propertyInfo = type.GetProperty(propertyName, bindingAttr);
            if (propertyInfo == null)
            {
                throw new InvalidOperationException(
                    "Unable to retrieve property information for property [" +
                    propertyName + "] with attributes [" + bindingAttr +
                    "] from type [" + type + "]");
            }
            return propertyInfo.GetValue(null, null);
        }

        /// <summary>
        ///     Retrieves the type of the named property on a type.
        /// </summary>
        /// <param name="type">Type that has the property.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>
        ///     The Type of the specified property.
        /// </returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static Type GetPropertyType(Type type, string propertyName)
        {
            const BindingFlags bindingAttr =
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Instance | BindingFlags.Static |
                BindingFlags.FlattenHierarchy;

            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();
            var propertyInfo = type.GetProperty(propertyName, bindingAttr);
            return propertyInfo.PropertyType;
        }

        /// <summary>
        ///     Returns an object suitable for comparison with the specified
        ///     target type from the given object.
        /// </summary>
        /// <param name='o'>Object to return value for.</param>
        /// <param name='targetType'>Target type.</param>
        /// <remarks>
        ///     This method is similar to the Change.ChangeType API call.
        ///     However, if o is a string with value '*null', a null value
        ///     will be returned. If targetType is System.String and o is
        ///     not null, o.ToString() will be returned rather than the
        ///     simple ChangeType (*null if o is null). If the target is an
        ///     enumeration and o is a string, then the Enum.Parse method
        ///     is invoked. Also, all conversions are done with the invariant
        ///     culture.
        /// </remarks>
        public static object GetValueForComparison(object o, Type targetType)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException(nameof(targetType));
            }

            const string nullString = "*null";
            var isTargetString = targetType == typeof (string);
            var isTargetEnum = targetType.IsSubclassOf(typeof (Enum));

            // Handle the case of a null object.
            if (o == null)
            {
                return (isTargetString) ? nullString : null;
            }
            if (isTargetString)
            {
                return o.ToString();
            }
            if ((o is string) && isTargetEnum)
            {
                return Enum.Parse(targetType, (string) o, true);
            }
            return Convert.ChangeType(o, targetType,
                CultureInfo.InvariantCulture);
        }

        /// <summary>Removes an event handler from a named event on an object.</summary>
        /// <param name='target'>Object from which to remove event handler.</param>
        /// <param name='eventName'>Name of event to remove from.</param>
        /// <param name='handler'>Delegate for event.</param>
        public static void RemoveInstanceEventHandler(object target, string eventName, Delegate handler)
        {
            AddRemoveInstanceEventHandler(target, eventName, handler, false);
        }

        /// <summary>
        ///     Retrieves types, guaranteeing that no exceptions will be thown.
        /// </summary>
        /// <param name="assembly">Assembly to get types from.</param>
        /// <returns>
        ///     The types in the specifies assembly, or a zero-length array if an
        ///     exception was thrown and no types could be accessed. If only some
        ///     types are loaded, these are returned, and the returned array
        ///     will have null elements.
        /// </returns>
        public static Type[] SafeGetTypes(Assembly assembly)
        {
            // AssemblySW assemblySW = AssemblySW.Wrap(assembly);
            var testTypes = Type.EmptyTypes;
            try
            {
                var types = assembly.GetTypes();
                testTypes = new Type[types.Length];
                for (var i = 0; i < types.Length; i++)
                {
                    testTypes[i] = types[i];
                }
            }
            catch (ReflectionTypeLoadException re)
            {
                var sb = new StringBuilder();
                sb.Append("ReflectionTypeLoadException thrown while getting types for ");
                sb.Append(assembly.FullName);
                sb.Append(Environment.NewLine);
                sb.Append(re);
                sb.Append("Loader exceptions: ");
                sb.Append(re.LoaderExceptions.Length);
                sb.Append(Environment.NewLine);
                foreach (var exception in re.LoaderExceptions)
                {
                    sb.Append(exception);
                    sb.Append(Environment.NewLine);
                }

                return re.Types;
            }
            catch (Exception exception)
            {
                Debug.Write(exception.ToString());
            }
            return testTypes;
        }

        /// <summary>
        ///     Invokes a method defined on a specific interface on the
        ///     given object.
        /// </summary>
        /// <param name="instance">Object to invoke method on.</param>
        /// <param name="interfaceName">Name of interface defining the method.</param>
        /// <param name="methodName">Name of method to invoke.</param>
        /// <param name="methodArguments">Arguments for the method.</param>
        /// <returns>The return value of the invoked member.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object InvokeInterfaceMethod(object instance, string interfaceName,
            string methodName, object[] methodArguments)
        {
            BindingFlags bindingFlags; // Flags to match method to invoke.
            Type type; // Type to invoke method on.

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();

            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            if (interfaceName == null)
            {
                throw new ArgumentNullException(nameof(interfaceName));
            }
            if (methodName == null)
            {
                throw new ArgumentNullException(nameof(methodName));
            }
            if (methodArguments == null)
            {
                throw new ArgumentNullException(nameof(methodArguments));
            }

            type = instance.GetType();
            type = type.GetInterface(interfaceName);
            bindingFlags = BindingFlags.Public | BindingFlags.NonPublic |
                           BindingFlags.ExactBinding | BindingFlags.FlattenHierarchy |
                           BindingFlags.Instance | BindingFlags.InvokeMethod;
            return type.InvokeMember(methodName, bindingFlags, null, instance,
                methodArguments);
        }

        /// <summary>
        ///     Invokes a method on an object.
        /// </summary>
        /// <param name="instance">Object to invoke method on.</param>
        /// <param name="methodName">Name of method to invoke.</param>
        /// <param name="methodArguments">Arguments for the method.</param>
        /// <returns>The return value of the invoked member.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object InvokeInstanceMethod(object instance, string methodName,
            object[] methodArguments)
        {
            BindingFlags bindingFlags; // Flags to match method to invoke.
            Type type; // Type to invoke method on.

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();

            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            if (methodName == null)
            {
                throw new ArgumentNullException(nameof(methodName));
            }
            if (methodArguments == null)
            {
                throw new ArgumentNullException(nameof(methodArguments));
            }

            type = instance.GetType();
            bindingFlags = BindingFlags.Public | BindingFlags.NonPublic |
                           BindingFlags.ExactBinding | BindingFlags.FlattenHierarchy |
                           BindingFlags.Instance | BindingFlags.InvokeMethod;
            return type.InvokeMember(methodName, bindingFlags, null, instance,
                methodArguments);
        }

        /// <summary>
        ///     Invokes a method on an type.
        /// </summary>
        /// <param name="type">Type to invoke method on.</param>
        /// <param name="methodName">Name of method to invoke.</param>
        /// <param name="methodArguments">Arguments for the method.</param>
        /// <returns>The return value of the invoked member.</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object InvokeStaticMethod(Type type, string methodName,
            object[] methodArguments)
        {
            BindingFlags bindingFlags; // Flags to match method to invoke.

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();

            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (methodName == null)
            {
                throw new ArgumentNullException(nameof(methodName));
            }
            if (methodArguments == null)
            {
                throw new ArgumentNullException(nameof(methodArguments));
            }

            bindingFlags = BindingFlags.Public | BindingFlags.NonPublic |
                           BindingFlags.ExactBinding | BindingFlags.FlattenHierarchy |
                           BindingFlags.Static | BindingFlags.InvokeMethod;
            return type.InvokeMember(methodName, bindingFlags, null, null,
                methodArguments);
        }

        /// <summary>
        ///     call className.methodName static method
        /// </summary>
        /// <param name="className">name of the class where the method exists.</param>
        /// <param name="methodName">name of the method to invoke</param>
        /// <param name="parameters">parameters to the method</param>
        /// <param name="invokeType">Invoke type. See Test.Uis.Utils.InvokeType for details</param>
        /// <returns>return value of hte invoked method</returns>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static object InvokePropertyOrMethod(string className,
            string methodName, object[] parameters, InvokeType invokeType)
        {
            var perm =
                new ReflectionPermission(
                    PermissionState.Unrestricted);
            perm.Assert();

            Type type;
            bool isGetProperty;
            object[] newargs;
            object instance;
            BindingFlags defaultFlags;
            object resultObject;

            //if (ActionManager.IsInvokeTypeStatic(invokeType))
            //{
            //    if (String.IsNullOrEmpty(className))
            //    {
            //        throw new ArgumentException(
            //            "className cannot be null or empty for static invocations",
            //            "className");
            //    }
            //    type = ReflectionUtils.FindType(className);
            //    if (type == null)
            //    {
            //       throw new InvalidOperationException("FindType fails");
            //    }
            //}
            //else
            //{
            if (parameters == null || parameters.Length == 0)
            {
                throw new ArgumentException(
                    "parameters cannot be null or empty for instance invocations",
                    nameof(parameters));
            }
            if (parameters[0] == null)
            {
                throw new ArgumentException(
                    "parameters cannot have a null first element for instance invocations",
                    nameof(parameters));
            }
            type = parameters[0].GetType();
            //}
            Debug.Assert(type != null);

            defaultFlags = BindingFlags.ExactBinding | BindingFlags.Public;
            newargs = null;
            instance = null;

            switch (invokeType)
            {
                case InvokeType.StaticMethod:
                    defaultFlags |= BindingFlags.InvokeMethod;
                    defaultFlags |= BindingFlags.Static;
                    break;
                case InvokeType.InstanceMethod:
                    defaultFlags |= BindingFlags.InvokeMethod;
                    defaultFlags |= BindingFlags.Instance;
                    instance = ExtractFirstParameterAsInstance(parameters, ref newargs);
                    parameters = newargs;
                    break;
                case InvokeType.GetStaticProperty:
                    defaultFlags |= BindingFlags.GetProperty;
                    defaultFlags |= BindingFlags.Static;
                    break;
                case InvokeType.SetStaticProperty:
                    defaultFlags |= BindingFlags.SetProperty;
                    defaultFlags |= BindingFlags.Static;
                    break;
                case InvokeType.GetInstanceProperty:
                    defaultFlags |= BindingFlags.GetProperty;
                    defaultFlags |= BindingFlags.Instance;
                    instance = ExtractFirstParameterAsInstance(parameters, ref newargs);
                    parameters = newargs;
                    break;
                case InvokeType.SetInstanceProperty:
                    defaultFlags |= BindingFlags.SetProperty;
                    defaultFlags |= BindingFlags.Instance;
                    instance = ExtractFirstParameterAsInstance(parameters, ref newargs);
                    parameters = newargs;
                    break;
                case InvokeType.GetStaticField:
                    defaultFlags |= BindingFlags.GetField;
                    defaultFlags |= BindingFlags.Static;
                    break;
                case InvokeType.SetStaticField:
                    defaultFlags |= BindingFlags.SetField;
                    defaultFlags |= BindingFlags.Static;
                    break;
                case InvokeType.GetInstanceField:
                    defaultFlags |= BindingFlags.GetField;
                    defaultFlags |= BindingFlags.Instance;
                    instance = ExtractFirstParameterAsInstance(parameters, ref newargs);
                    parameters = newargs;
                    break;
                case InvokeType.SetInstanceField:
                    defaultFlags |= BindingFlags.SetField;
                    defaultFlags |= BindingFlags.Instance;
                    instance = ExtractFirstParameterAsInstance(parameters, ref newargs);
                    parameters = newargs;
                    break;
            }

            try
            {
                resultObject = type.InvokeMember(
                    methodName, defaultFlags, null, instance, parameters);
            }
            catch (MissingMethodException e)
            {
                isGetProperty = invokeType == InvokeType.GetInstanceProperty ||
                                invokeType == InvokeType.GetStaticProperty;
                if (parameters.Length > 0 && isGetProperty)
                {
                }
                throw e;
            }
            catch (AmbiguousMatchException e)
            {
                throw e;
            }
            return resultObject;
        }

        /// <summary>
        ///     Sets the value of the named property.
        /// </summary>
        /// <param name='target'>Object on which to set value.</param>
        /// <param name='propertyName'>Name of property to set.</param>
        /// <param name='value'>Value of property.</param>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void SetProperty(object target, string propertyName, object value)
        {
            const BindingFlags invokeAttr =
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Instance | BindingFlags.SetProperty;

            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();

            object[] args = {value};
            var type = target.GetType();
            type.InvokeMember(propertyName, invokeAttr, null, target, args);
        }

        #endregion Public methods.

        //------------------------------------------------------
        //
        //  Public Properties
        //
        //------------------------------------------------------

        //------------------------------------------------------
        //
        //  Private Methods
        //
        //------------------------------------------------------

        #region Private methods.

        /// <summary>Adds or removes an event handler to a named event on an object.</summary>
        /// <param name='target'>Object on which to add/remove event handler.</param>
        /// <param name='eventName'>Name of event to add/remove to.</param>
        /// <param name='handler'>Delegate for event.</param>
        /// <param name='add'>true to add the handler, false to remove it.</param>
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void AddRemoveInstanceEventHandler(object target, string eventName,
            Delegate handler, bool add)
        {
            const BindingFlags bindingAttr =
                BindingFlags.Public | BindingFlags.NonPublic |
                BindingFlags.Instance;

            EventInfo eventInfo;
            Type type;

            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (eventName == null)
            {
                throw new ArgumentNullException(nameof(eventName));
            }
            if (eventName.Length == 0)
            {
                throw new ArgumentException("Event name should not be blank.", nameof(eventName));
            }

            new ReflectionPermission(
                PermissionState.Unrestricted)
                .Assert();
            type = target.GetType();
            eventInfo = type.GetEvent(eventName, bindingAttr);
            if (eventInfo == null)
            {
                throw new InvalidOperationException(
                    "Unable to retrieve event information for event [" +
                    eventName + "] with attributes [" + bindingAttr +
                    "] from type [" + type + "]");
            }
            if (add)
            {
                eventInfo.AddEventHandler(target, handler);
            }
            else
            {
                eventInfo.RemoveEventHandler(target, handler);
            }
        }

        /// <summary>
        ///     Describes the specified array of parameters.
        /// </summary>
        /// <param name="parameters">Parameters to describe.</param>
        /// <returns>A string describing the specified parameters.</returns>
        private static string DescribeParameters(object[] parameters)
        {
            if (parameters == null || parameters.Length == 0)
            {
                return "No parameter supplied.";
            }
            var result = "";
            for (var i = 0; i < parameters.Length; i++)
            {
                result += "Parameter " + i + ": ";
                if (parameters[i] == null)
                {
                    result += "null\r\n";
                }
                else
                {
                    result += "[" + parameters[i] + "]" +
                              " (" + parameters[i].GetType().Name + ")\r\n";
                }
            }
            return result;
        }

        /// <summary>
        ///     Extract first parameter in args and return it in instance parameter,
        ///     the rest of objects in args are copied to newargs.
        /// </summary>
        /// <param name="args">array of objects to be extracted</param>
        /// <param name="newargs">aray of objects in args excluding the first one</param>
        /// <returns>args[0] as object</returns>
        private static object ExtractFirstParameterAsInstance(object[] args, ref object[] newargs)
        {
            if (args.Length > 0)
            {
                var instance = args[0];
                newargs = null;
                if (args.Length > 1)
                {
                    // if we call instance method the first object in args is the instance
                    // we need to extract that.
                    // ===================================================================
                    newargs = new object[args.Length - 1];
                    for (var i = 1; i < args.Length; i++)
                    {
                        newargs[i - 1] = args[i];
                    }
                }
                return instance;
            }
            throw new ArgumentException("args doesn't have any element", nameof(args));
        }

        #endregion Private methods.
    }
}

<|start_filename|>Element Tree/OverridingLogicalTree/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;

namespace OverridingLogicalTree
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void AddLogicalElement(object sender, RoutedEventArgs e)
        {
            var mybutton = new Button {Content = "Happy birthday! " + DateTime.Now.TimeOfDay};
            CustomElement.SetSingleChild(mybutton);
        }
    }
}

<|start_filename|>Sample Applications/EditingExaminerDemo/InvokeType.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace EditingExaminerDemo
{
    /// <summary>
    ///     The type of invoke we support (or plan to support).
    /// </summary>
    public enum InvokeType
    {
        /// <summary>
        ///     Invoke static method
        /// </summary>
        StaticMethod = 0,

        /// <summary>
        ///     Invoke instance method (need this pointer to be passed as first parameter in InvokeStaticOrInstanceMethod)
        /// </summary>
        InstanceMethod,

        /// <summary>
        ///     Invoke static get field
        /// </summary>
        GetStaticField,

        /// <summary>
        ///     Invoke static set field
        /// </summary>
        SetStaticField,

        /// <summary>
        ///     Invoke instance get field
        /// </summary>
        GetInstanceField,

        /// <summary>
        ///     Invoke instance set field
        /// </summary>
        SetInstanceField,

        /// <summary>
        ///     Invoke static get property
        /// </summary>
        GetStaticProperty,

        /// <summary>
        ///     Invoke static set property
        /// </summary>
        SetStaticProperty,

        /// <summary>
        ///     Invoke instance get property
        /// </summary>
        GetInstanceProperty,

        /// <summary>
        ///     Invoke instance set property
        /// </summary>
        SetInstanceProperty
    }
}

<|start_filename|>Properties/Callbacks/Gauge.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace Callbacks
{
    public class Gauge : Control
    {
        public static readonly DependencyProperty CurrentReadingProperty = DependencyProperty.Register(
            "CurrentReading",
            typeof (double),
            typeof (Gauge),
            new FrameworkPropertyMetadata(
                double.NaN,
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnCurrentReadingChanged,
                CoerceCurrentReading
                ),
            IsValidReading
            );

        public static readonly DependencyProperty MaxReadingProperty = DependencyProperty.Register(
            "MaxReading",
            typeof (double),
            typeof (Gauge),
            new FrameworkPropertyMetadata(
                double.NaN,
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnMaxReadingChanged,
                CoerceMaxReading
                ),
            IsValidReading
            );

        public static readonly DependencyProperty MinReadingProperty = DependencyProperty.Register(
            "MinReading",
            typeof (double),
            typeof (Gauge),
            new FrameworkPropertyMetadata(
                double.NaN,
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnMinReadingChanged,
                CoerceMinReading
                ),
            IsValidReading);

        public double CurrentReading
        {
            get { return (double) GetValue(CurrentReadingProperty); }
            set { SetValue(CurrentReadingProperty, value); }
        }

        public double MaxReading
        {
            get { return (double) GetValue(MaxReadingProperty); }
            set { SetValue(MaxReadingProperty, value); }
        }

        public double MinReading
        {
            get { return (double) GetValue(MinReadingProperty); }
            set { SetValue(MinReadingProperty, value); }
        }

        public static bool IsValidReading(object value)
        {
            var v = (double) value;
            return (!v.Equals(double.NegativeInfinity) && !v.Equals(double.PositiveInfinity));
        }

        private static object CoerceCurrentReading(DependencyObject d, object value)
        {
            var g = (Gauge) d;
            var current = (double) value;
            if (current < g.MinReading) current = g.MinReading;
            if (current > g.MaxReading) current = g.MaxReading;
            return current;
        }

        private static void OnCurrentReadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            d.CoerceValue(MinReadingProperty);
            d.CoerceValue(MaxReadingProperty);
        }

        private static void OnMaxReadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            d.CoerceValue(MinReadingProperty);
            d.CoerceValue(CurrentReadingProperty);
        }

        private static object CoerceMaxReading(DependencyObject d, object value)
        {
            var g = (Gauge) d;
            var max = (double) value;
            if (max < g.MinReading) max = g.MinReading;
            return max;
        }

        private static void OnMinReadingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            d.CoerceValue(MaxReadingProperty);
            d.CoerceValue(CurrentReadingProperty);
        }

        private static object CoerceMinReading(DependencyObject d, object value)
        {
            var g = (Gauge) d;
            var min = (double) value;
            if (min > g.MaxReading) min = g.MaxReading;
            return min;
        }
    }
}

<|start_filename|>Animation/PropertyAnimation/StoryboardExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace PropertyAnimation
{
    // Uses a storyboard to animate the properties
    // of two buttons.
    public class StoryboardExample : Page
    {
        public StoryboardExample()
        {
            // Create a name scope for the page.
            NameScope.SetNameScope(this, new NameScope());

            WindowTitle = "Animate Properties using Storyboards";
            var myStackPanel = new StackPanel
            {
                MinWidth = 500,
                Margin = new Thickness(30),
                HorizontalAlignment = HorizontalAlignment.Left
            };
            var myTextBlock = new TextBlock {Text = "Storyboard Animation Example"};
            myStackPanel.Children.Add(myTextBlock);

            //
            // Create and animate the first button.
            //

            // Create a button.
            var myWidthAnimatedButton = new Button
            {
                Height = 30,
                Width = 200,
                HorizontalAlignment = HorizontalAlignment.Left,
                Content = "A Button",
                Name = "myWidthAnimatedButton"
            };

            // Set the Name of the button so that it can be referred
            // to in the storyboard that's created later.
            // The ID doesn't have to match the variable name;
            // it can be any unique identifier.

            // Register the name with the page to which the button belongs.
            RegisterName(myWidthAnimatedButton.Name, myWidthAnimatedButton);

            // Create a DoubleAnimation to animate the width of the button.
            var myDoubleAnimation = new DoubleAnimation
            {
                From = 200,
                To = 300,
                Duration = new Duration(TimeSpan.FromMilliseconds(3000))
            };

            // Configure the animation to target the button's Width property.
            Storyboard.SetTargetName(myDoubleAnimation, myWidthAnimatedButton.Name);
            Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(WidthProperty));

            // Create a storyboard to contain the animation.
            var myWidthAnimatedButtonStoryboard = new Storyboard();
            myWidthAnimatedButtonStoryboard.Children.Add(myDoubleAnimation);

            // Animate the button width when it's clicked.
            myWidthAnimatedButton.Click +=
                delegate { myWidthAnimatedButtonStoryboard.Begin(myWidthAnimatedButton); };


            myStackPanel.Children.Add(myWidthAnimatedButton);

            //
            // Create and animate the second button.
            //

            // Create a second button.
            var myColorAnimatedButton = new Button
            {
                Height = 30,
                Width = 200,
                HorizontalAlignment = HorizontalAlignment.Left,
                Content = "Another Button"
            };

            // Create a SolidColorBrush to paint the button's background.
            var myBackgroundBrush = new SolidColorBrush {Color = Colors.Blue};

            // Because a Brush isn't a FrameworkElement, it doesn't
            // have a Name property to set. Instead, you just
            // register a name for the SolidColorBrush with
            // the page where it's used.
            RegisterName("myAnimatedBrush", myBackgroundBrush);

            // Use the brush to paint the background of the button.
            myColorAnimatedButton.Background = myBackgroundBrush;

            // Create a ColorAnimation to animate the button's background.
            var myColorAnimation = new ColorAnimation
            {
                From = Colors.Red,
                To = Colors.Blue,
                Duration = new Duration(TimeSpan.FromMilliseconds(7000))
            };

            // Configure the animation to target the brush's Color property.
            Storyboard.SetTargetName(myColorAnimation, "myAnimatedBrush");
            Storyboard.SetTargetProperty(myColorAnimation, new PropertyPath(SolidColorBrush.ColorProperty));

            // Create a storyboard to contain the animation.
            var myColorAnimatedButtonStoryboard = new Storyboard();
            myColorAnimatedButtonStoryboard.Children.Add(myColorAnimation);

            // Animate the button background color when it's clicked.
            myColorAnimatedButton.Click +=
                delegate { myColorAnimatedButtonStoryboard.Begin(myColorAnimatedButton); };


            myStackPanel.Children.Add(myColorAnimatedButton);
            Content = myStackPanel;
        }
    }
}

//</Snippet11>

<|start_filename|>Animation/Per-FrameAnimation/ReusableFollow/FollowMouseCanvas.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace PerFrameAnimation
{
    public class FollowMouseCanvas : Canvas
    {
        private TimeSpan _lastRender;
        private Canvas _parentCanvas;
        private Point _parentLastMousePosition = new Point(0, 0);
        private Vector _velocity = new Vector(0, 0);

        public FollowMouseCanvas()
        {
            _lastRender = TimeSpan.FromTicks(DateTime.Now.Ticks);
            CompositionTarget.Rendering += UpdatePosition;
        }

        private void UpdatePosition(object sender, EventArgs e)
        {
            var renderingArgs = (RenderingEventArgs) e;

            var deltaTime = (renderingArgs.RenderingTime - _lastRender).TotalSeconds;
            _lastRender = renderingArgs.RenderingTime;

            if (_parentCanvas == null)
            {
                _parentCanvas = VisualTreeHelper.GetParent(this) as Canvas;
                if (_parentCanvas == null)
                {
                    //parent isnt canvas so just abort trying to follow mouse
                    CompositionTarget.Rendering -= UpdatePosition;
                }
                else
                {
                    //parent is canvas, so track mouse position and time
                    _parentCanvas.PreviewMouseMove += UpdateLastMousePosition;
                }
            }


            //get location
            var location = new Point(GetLeft(this), GetTop(this));

            //check for NaN's and replace with 0,0
            if (double.IsNaN(location.X) || double.IsNaN(location.Y))
                location = new Point(0, 0);

            //find vector toward mouse location
            var toMouse = _parentLastMousePosition - location;

            //add a force toward the mouse to the rectangles velocity
            var followForce = 1.0;
            _velocity += toMouse*followForce;

            //dampen the velocity to add stability
            var drag = 0.95;
            _velocity *= drag;

            //update the new location from the velocity
            location += _velocity*deltaTime;

            //set new position
            SetLeft(this, location.X);
            SetTop(this, location.Y);
        }

        private void UpdateLastMousePosition(object sender, MouseEventArgs e)
        {
            if (_parentCanvas == null)
                return;

            _parentLastMousePosition = e.GetPosition(_parentCanvas);
        }
    }
}

<|start_filename|>Data Binding/Colors/DoubleToStringConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace Colors
{
    // One-way conversion between double and string (adding formatting)

    public class DoubleToStringConverter : IValueConverter
    {
        object IValueConverter.Convert(object o, Type type, object parameter, CultureInfo culture) => $"{o:f2}";

        object IValueConverter.ConvertBack(object o, Type type, object parameter, CultureInfo culture) => null;
    }
}

<|start_filename|>Data Binding/Grouping/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Data;

namespace Grouping
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private CollectionView _myView;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void AddGrouping(object sender, RoutedEventArgs e)
        {
            _myView = (CollectionView) CollectionViewSource.GetDefaultView(myItemsControl.ItemsSource);
            if (_myView.CanGroup)
            {
                var groupDescription
                    = new PropertyGroupDescription("@Type");
                _myView.GroupDescriptions.Add(groupDescription);
            }
        }

        private void RemoveGrouping(object sender, RoutedEventArgs e)
        {
            _myView = (CollectionView) CollectionViewSource.GetDefaultView(myItemsControl.ItemsSource);
            _myView.GroupDescriptions.Clear();
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/NewBamlDisassembler.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace BamlTools
{
    public class NewBamlDisassembler
    {
        BamlBinaryReader _reader;
        bool _showAddresses;
        bool _showRecordNumbers;
        bool _showDebugRecords;
        bool _showTableRecords;

        private string _indent;
        private int _indentLevel;
        private int _recordNumber;
        private Dictionary<int, string> _typeInfoTable;
        private Dictionary<int, string> _attributeInfoTable;
        private Dictionary<int, string> _assemblyInfoTable;

        public NewBamlDisassembler(Stream reader)
        {
            _reader = new BamlBinaryReader(reader);
            _typeInfoTable = new Dictionary<int, string>();
            _attributeInfoTable = new Dictionary<int, string>();
            _assemblyInfoTable = new Dictionary<int, string>();
        }

        public string DasmOneBigString()
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                foreach (string line in GetLines())
                {
                    sb.AppendLine(line);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.ToString());
            }
            return sb.ToString();
        }

        public IEnumerable<String> GetLines()
        {
            DataFormatVersion version = ReadFormatVersion();
            yield return VersionToString(version);

            while (!Done())
            {
                long address = _reader.BaseStream.Position;
                BamlRecord record = ReadRecord();

                if ((record.Flags & BamlRecordFlags.End) != 0)
                {
                    IndentLevel -= 1;
                }
                string indent = Indent;  // save the indent because ProcessBamlRecord() may change it.

                ProcessBamlRecord(record);

                if (record.Flags == BamlRecordFlags.Debug && !ShowDebugRecords)
                {
                    continue;
                }

                if (record.Flags == BamlRecordFlags.Table && !ShowTableRecords)
                {
                    continue;
                }

                string recNumString = String.Format("#{0:d3}: ", _recordNumber);
                string addressString = String.Format("{0:x5}: ", address);

                string preamble = String.Empty;
                preamble += (ShowRecordNumbers) ? recNumString : String.Empty;
                preamble += (ShowAddresses) ? addressString : String.Empty;
                preamble += indent;
                yield return preamble + RecordToString(record);
            }
        }

        public bool ShowAddresses
        {
            get { return _showAddresses; }
            set { _showAddresses = value; }
        }

        public bool ShowRecordNumbers
        {
            get { return _showRecordNumbers; }
            set { _showRecordNumbers = value; }
        }

        public bool ShowDebugRecords
        {
            get { return _showDebugRecords; }
            set { _showDebugRecords = value; }
        }

        public bool ShowTableRecords
        {
            get { return _showTableRecords; }
            set { _showTableRecords = value; }
        }

        public long Position
        {
            get { return _reader.BaseStream.Position; }
            set { _reader.BaseStream.Position = value; }
        }

        public long Length
        {
            get { return _reader.BaseStream.Length; }
        }

        public bool Done()
        {
            return (Position >= Length - 1);
        }


        // This property should only be accessed after a disassembly.
        // It is running the disassembly that populates the table.
        public List<TypeInfoTableEntry> TypeInfoTable
        {
            get
            {
                List<TypeInfoTableEntry> list = new List<TypeInfoTableEntry>();
                foreach (KeyValuePair<int, string> entry in _typeInfoTable)
                {
                    list.Add(new TypeInfoTableEntry(entry.Key, entry.Value));
                }
                return list;
            }
        }

        public List<AttributeInfoTableEntry> AttributeInfoTable
        {
            get
            {
                List<AttributeInfoTableEntry> list = new List<AttributeInfoTableEntry>();
                foreach (KeyValuePair<int, string> entry in _attributeInfoTable)
                {
                    list.Add(new AttributeInfoTableEntry(entry.Key, entry.Value, 0));
                }
                return list;
            }
        }

        private DataFormatVersion ReadFormatVersion()
        {
            DataFormatVersion version = new DataFormatVersion();
            int strByteLength = (int)_reader.ReadInt32();

            BinaryReader tempReader = new BinaryReader(_reader.BaseStream, System.Text.Encoding.Unicode);
            char[] chars = tempReader.ReadChars(strByteLength / 2);

            version.name = new string(chars);
            version.readerVersion = _reader.ReadInt32();
            version.updateVersion = _reader.ReadInt32();
            version.writerVersion = _reader.ReadInt32();
            return version;
        }


        public BamlRecord ReadRecord()
        {
            BamlRecordType recordType = (BamlRecordType)_reader.ReadByte();
            BamlRecord record = StaticBamlRecords.GetRecord(recordType);

            long startPosition = Position;
            int variableSize = 0;

            if (record.IsVariableSize)
            {
                variableSize = _reader.Read7BitEncodedInt();
            }

            for (int i = 0; i < record.Fields.Length; i++)
            {
                record.Fields[i].Value = ReadField(record.Fields[i]);
            }

            // this deals with the rare case of undefined padding
            // at the end of a record.  Only allowed for PropertyCustom
            if (record.IsVariableSize)
            {
                int processedSize = (int)(Position - startPosition);
                int extraPadding = variableSize - processedSize;
                Debug.Assert(extraPadding >= 0);
                if (extraPadding > 0)
                {
                    Debug.Assert(recordType == BamlRecordType.PropertyCustom);
                    byte[] bytes = _reader.ReadBytes(extraPadding);
                }
            }
            return record;
        }

        private object ReadField(BamlField field)
        {
            object val = null;
            Type t = field.ClrType;

            if (t == typeof(short))
            {
                val = _reader.ReadInt16();
            }
            else if (t == typeof(int))
            {
                val = _reader.ReadInt32();
            }
            else if (t == typeof(string))
            {
                val = _reader.ReadString();
            }
            else if (t == typeof(bool))
            {
                val = _reader.ReadBoolean();
            }
            else if (t == typeof(byte))
            {
                val = _reader.ReadByte();
            }
            else if (t == typeof(Int16[]))
            {
                short arrayLength = (short)_reader.ReadInt16();
                short[] array = new short[arrayLength];
                for (int i = 0; i < array.Length; i++)
                {
                    array[i] = (short)_reader.ReadInt16();
                }
                val = array;
            }
            else
            {
                throw new InvalidOperationException("Field Type not known");
            }

            return val;
        }

        private string VersionToString(DataFormatVersion version)
        {
            return String.Format("'{0}' {1}.{2} {3}.{4} {5}.{6}", version.name,
                    version.readerVersion & 0xFFFF, (version.readerVersion >> 16) & 0xFFFF,
                    version.updateVersion & 0xFFFF, (version.updateVersion >> 16) & 0xFFFF,
                    version.writerVersion & 0xFFFF, (version.writerVersion >> 16) & 0xFFFF);
        }

        private string RecordToString(BamlRecord record)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(record.Id.ToString());

            for (int i = 0; i < record.Fields.Length; i++)
            {
                BamlField currentField = record.Fields[i];
                string name = String.Empty;
                string valString;
                switch (currentField.BamlFieldType)
                {
                    case BamlFieldType.TypeId:
                    case BamlFieldType.ConverterTypeId:
                        valString = TypeIdToString((short)currentField.Value);
                        break;

                    case BamlFieldType.AttributeId:
                        valString = AttributeIdToString((short)currentField.Value);
                        break;

                    default:
                        valString = currentField.Value as String;
                        if (valString != null)
                        {
                            valString = ("\"" + valString + "\"");
                        }
                        else
                        {
                            valString = currentField.Value.ToString();
                        }
                        break;
                }
                sb.Append(", " + currentField.Name + "(" + valString + ")");
            }
            return sb.ToString();
        }

        private string TypeIdToString(short typeId)
        {
            string name = String.Empty;
            if (typeId < 0)
            {
                name = "<" + KnownElements.Elements[-typeId].ShortName + ">";
                Debug.Assert(KnownElements.Elements[-typeId].BamlNumber == -typeId);
            }
            else
            {
                name = "<" + _typeInfoTable[typeId] + ">";
            }
            return typeId + name;
        }

        private string AttributeIdToString(short attributeId)
        {
            string name = String.Empty;
            if (attributeId < 0)
            {
                name = "<" + KnownProperties.Properties[-attributeId].PropertyName + ">";
                Debug.Assert(KnownElements.Elements[-attributeId].BamlNumber == -attributeId);
            }
            else
            {
                name = "<" + _attributeInfoTable[attributeId] + ">";
            }
            return attributeId.ToString() + name;
        }


        private void ProcessBamlRecord(BamlRecord record)
        {
            _recordNumber += 1;
            if ((record.Flags & BamlRecordFlags.Start) != 0)
            {
                IndentLevel += 1;
            }
            if ((record.Flags & BamlRecordFlags.Table) != 0)
            {
                switch (record.Id)
                {
                    case BamlRecordType.AssemblyInfo:
                        _assemblyInfoTable.Add((short)record.Fields[0].Value, (string)record.Fields[1].Value);
                        break;

                    case BamlRecordType.TypeInfo:
                        _typeInfoTable.Add((short)record.Fields[0].Value, (string)record.Fields[2].Value);
                        break;

                    case BamlRecordType.AttributeInfo:
                        _attributeInfoTable.Add((short)record.Fields[0].Value, (string)record.Fields[3].Value);
                        break;

                    default:
                        //Debug.Assert(false, "Bad record in BamlRecordFlags.Table");
                        break;
                }
            }
        }

        private string Indent
        {
            get { return _indent; }
        }

        private int IndentLevel
        {
            get { return _indentLevel; }
            set
            {
                _indentLevel = value;
                _indent = String.Empty;
                for (int i = 0; i < _indentLevel; i++)
                {
                    _indent += " . ";
                }
            }
        }
    }
}


<|start_filename|>Sample Applications/ExpenseIt/ExpenseItDemo/Validation/EmailValidationrule.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Controls;

// ValidationRule

// CultureInfo

namespace ExpenseItDemo.Validation
{
    // Email Validation Rule
    public class EmailValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            // Is a valid email address?
            var pattern =
                @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*";
            if (!Regex.IsMatch((string) value, pattern))
            {
                var msg = $"{value} is not a valid email address.";
                return new ValidationResult(false, msg);
            }

            // Email address is valid
            return new ValidationResult(true, null);
        }
    }
}

<|start_filename|>Accessibility/InsertText/InsertTextTarget/Form1.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Forms;

namespace InsertTextW32Target
{
    public partial class Target : Form
    {
        public Target()
        {
            InitializeComponent();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            tbTargetMultiLine.Enabled = (checkBox1.CheckState != CheckState.Checked);
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            rtbTarget.Enabled = (checkBox2.CheckState != CheckState.Checked);
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            tbTarget.Enabled = (checkBox3.CheckState != CheckState.Checked);
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/ExpExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Raise the first expression to the power of the second.
    /// </summary>
    public sealed class ExpExpression : BinaryExpression
    {
        public ExpExpression(IExpression left, IExpression right) : base(left, right)
        {
        }

        protected override double Operate(double d1, double d2) => Math.Pow(d1, d2);

        public override IExpression Differentiate(string byVar)
        {
            if (right is ConstantExpression)
            {
                //      f(x) = g(x)^n;
                //     f'(x) = n * g'(x) * g(x)^(n-1);
                return new MultExpression(new MultExpression(right, left.Differentiate(byVar)),
                    new ExpExpression(left,
                        new SubExpression(right,
                            new ConstantExpression(1))));
            }
            var simple = left.Simplify();
            if (simple is ConstantExpression)
            {
                //  f(x) = a^g(x);
                // f'(x) = (ln a) * g'(x) * a^g(x);
                var a = ((ConstantExpression) simple).Value;
                return new MultExpression(new MultExpression(new ConstantExpression(Math.Log(a)),
                    right.Differentiate(byVar)),
                    new ExpExpression(simple, right));
            }
            throw new CannotDifferentiateException("I do not support complex exponent differentiation");
        }

        public override IExpression Simplify()
        {
            var newLeft = left.Simplify();
            var newRight = right.Simplify();

            var leftConst = newLeft as ConstantExpression;
            var rightConst = newRight as ConstantExpression;

            if (leftConst != null && rightConst != null)
            {
                // two constants;  just evaluate it;
                return new ConstantExpression(Math.Pow(leftConst.Value, rightConst.Value));
            }
            if (rightConst != null)
            {
                if (rightConst.Value == 0)
                {
                    // x ^ 0;  return 1;
                    return new ConstantExpression(1);
                }
                if (rightConst.Value == 1)
                {
                    // x ^ 1;  return x;
                    return newLeft;
                }
            }
            else if (leftConst != null && leftConst.Value == 0)
            {
                // 0 ^ y;  return 0;
                return new ConstantExpression(0);
            }
            // x ^ y;  no simplification
            return new ExpExpression(newLeft, newRight);
        }

        public override string ToString() => "(" + left.ToString() + "^" + right.ToString() + ")";
    }
}

<|start_filename|>Graphics/2DTransforms/InteractiveMatrixTransformExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Controls;
using System.Windows.Media;

namespace Microsoft.Samples.Graphics.Transforms
{
    public partial class InteractiveMatrixTransformExample : Page
    {
        private void ApplyButtonClicked(object sender, EventArgs args)
        {
            UpdateMatrixTransform();
        }

        private void UpdateMatrixTransform()
        {
            var myMatrix = new Matrix
            {
                M11 = double.Parse(M11TextBox.Text),
                M12 = double.Parse(M12TextBox.Text),
                M21 = double.Parse(M21TextBox.Text),
                M22 = double.Parse(M22TextBox.Text),
                OffsetX = double.Parse(OffsetXTextBox.Text),
                OffsetY = double.Parse(OffsetYTextBox.Text)
            };


            myMatrixTransform.Matrix = myMatrix;
        }
    }
}

<|start_filename|>Globalization and Localization/GlobalizationHomepage/HomePage.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Controls;

namespace GlobalizationHomepage
{
    /// <summary>
    ///     Interaction logic for HomePage.xaml
    /// </summary>
    public partial class HomePage : Page
    {
        public HomePage()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/DrawAxisHelper.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace GraphingCalculatorDemo
{
    public class DrawAxisHelper
    {
        private readonly Canvas _screen;
        private Size _screenSize;
        private double _xmin, _xmax, _ymin, _ymax;

        public DrawAxisHelper(Canvas screen, Size screenSize)
        {
            _screen = screen;
            _screenSize = screenSize;
        }

        public void DrawAxes(double xmin, double xmax, double ymin, double ymax)
        {
            _xmin = xmin;
            _xmax = xmax;
            _ymin = ymin;
            _ymax = ymax;

            var canvasWidth = _screenSize.Width;
            var canvasHeight = _screenSize.Height;
            var graphWidth = xmax - xmin;
            var graphHeight = ymax - ymin;
            var xOffset = (xmin >= 0) ? 0.0 : (xmax <= 0) ? 1.0 : -xmin/graphWidth;
            var yOffset = (ymin >= 0) ? 1.0 : (ymax <= 0) ? 0.0 : ymax/graphHeight;
            xOffset = Math.Floor(xOffset*(canvasWidth - 0.0));
            yOffset = Math.Floor(yOffset*(canvasHeight - 0.0));

            // X axis
            DrawLine(xOffset, 0.0, xOffset, canvasHeight, false);
            // Y axis
            DrawLine(0.0, yOffset, canvasWidth, yOffset, false);
        }

        private void DrawLine(double x1, double y1, double x2, double y2, bool dotted)
        {
            var line = new Line
            {
                X1 = x1,
                Y1 = y1,
                X2 = x2,
                Y2 = y2,
                Stroke = Brushes.Red,
                StrokeThickness = 1.0
            };
            if (dotted)
            {
                var collection = new DoubleCollection {3, 3};
                line.StrokeDashArray = collection;
            }
            _screen.Children.Add(line);
        }
    }
}

<|start_filename|>Drag and Drop/DragDropObjects/SimpleCircleAdorner.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DragDropObjects
{
    public class SimpleCircleAdorner : Adorner
    {
        private readonly Rectangle _child;
        private double _leftOffset;
        private double _topOffset;
        // Be sure to call the base class constructor.
        public SimpleCircleAdorner(UIElement adornedElement)
            : base(adornedElement)
        {
            var brush = new VisualBrush(adornedElement);

            _child = new Rectangle
            {
                Width = adornedElement.RenderSize.Width,
                Height = adornedElement.RenderSize.Height
            };


            var animation = new DoubleAnimation(0.3, 1, new Duration(TimeSpan.FromSeconds(1)))
            {
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever
            };
            brush.BeginAnimation(Brush.OpacityProperty, animation);

            _child.Fill = brush;
        }

        protected override int VisualChildrenCount => 1;

        public double LeftOffset
        {
            get { return _leftOffset; }
            set
            {
                _leftOffset = value;
                UpdatePosition();
            }
        }

        public double TopOffset
        {
            get { return _topOffset; }
            set
            {
                _topOffset = value;
                UpdatePosition();
            }
        }

        // A common way to implement an adorner's rendering behavior is to override the OnRender
        // method, which is called by the layout subsystem as part of a rendering pass.
        protected override void OnRender(DrawingContext drawingContext)
        {
            // Get a rectangle that represents the desired size of the rendered element
            // after the rendering pass.  This will be used to draw at the corners of the 
            // adorned element.
            var adornedElementRect = new Rect(AdornedElement.DesiredSize);

            // Some arbitrary drawing implements.
            var renderBrush = new SolidColorBrush(Colors.Green) {Opacity = 0.2};
            var renderPen = new Pen(new SolidColorBrush(Colors.Navy), 1.5);
            const double renderRadius = 5.0;

            // Just draw a circle at each corner.
            drawingContext.DrawRectangle(renderBrush, renderPen, adornedElementRect);
            drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.TopLeft, renderRadius, renderRadius);
            drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.TopRight, renderRadius, renderRadius);
            drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.BottomLeft, renderRadius, renderRadius);
            drawingContext.DrawEllipse(renderBrush, renderPen, adornedElementRect.BottomRight, renderRadius,
                renderRadius);
        }

        protected override Size MeasureOverride(Size constraint)
        {
            _child.Measure(constraint);
            return _child.DesiredSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            _child.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override Visual GetVisualChild(int index) => _child;

        private void UpdatePosition()
        {
            var adornerLayer = Parent as AdornerLayer;
            adornerLayer?.Update(AdornedElement);
        }

        public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
        {
            var result = new GeneralTransformGroup();
            result.Children.Add(base.GetDesiredTransform(transform));
            result.Children.Add(new TranslateTransform(_leftOffset, _topOffset));
            return result;
        }
    }
}

<|start_filename|>Windows/DialogBox/FontDialogBox.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace DialogBox
{
    public partial class FontDialogBox : Window
    {
        public FontDialogBox()
        {
            InitializeComponent();

            fontFamilyListBox.ItemsSource = FontPropertyLists.FontFaces;
            fontStyleListBox.ItemsSource = FontPropertyLists.FontStyles;
            fontWeightListBox.ItemsSource = FontPropertyLists.FontWeights;
            fontSizeListBox.ItemsSource = FontPropertyLists.FontSizes;
        }

        public new FontFamily FontFamily
        {
            get { return (FontFamily) fontFamilyListBox.SelectedItem; }
            set
            {
                fontFamilyListBox.SelectedItem = value;
                fontFamilyListBox.ScrollIntoView(value);
            }
        }

        public new FontStyle FontStyle
        {
            get { return (FontStyle) fontStyleListBox.SelectedItem; }
            set
            {
                fontStyleListBox.SelectedItem = value;
                fontStyleListBox.ScrollIntoView(value);
            }
        }

        public new FontWeight FontWeight
        {
            get { return (FontWeight) fontWeightListBox.SelectedItem; }
            set
            {
                fontWeightListBox.SelectedItem = value;
                fontWeightListBox.ScrollIntoView(value);
            }
        }

        public new double FontSize
        {
            get { return (double) fontSizeListBox.SelectedItem; }
            set
            {
                fontSizeListBox.SelectedItem = value;
                fontSizeListBox.ScrollIntoView(value);
            }
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            // Dialog box accepted
            DialogResult = true;
        }

        private void fontFamilyTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // If user enters family text, select family in list if matching item found
            FontFamily = new FontFamily(fontFamilyTextBox.Text);
        }

        private void fontStyleTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // If user enters style text, select style in list if matching item found
            if (FontPropertyLists.CanParseFontStyle(fontStyleTextBox.Text))
            {
                FontStyle = FontPropertyLists.ParseFontStyle(fontStyleTextBox.Text);
            }
        }

        private void fontWeightTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // If user enters weight text, select weight in list if matching item found
            if (FontPropertyLists.CanParseFontWeight(fontWeightTextBox.Text))
            {
                FontWeight = FontPropertyLists.ParseFontWeight(fontWeightTextBox.Text);
            }
        }

        private void fontSizeTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // If user enters size text, select size in list if matching item found
            double fontSize;
            if (double.TryParse(fontSizeTextBox.Text, out fontSize))
            {
                FontSize = fontSize;
            }
        }
    }
}

<|start_filename|>Sample Applications/SlidePuzzleDemo/PuzzleCell.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace SlidePuzzleDemo
{
    internal struct PuzzleCell
    {
        public PuzzleCell(int row, int col, int cellNumber)
        {
            Row = row;
            Col = col;
            CellNumber = cellNumber;
        }

        public int Row { get; }
        public int Col { get; }
        public int CellNumber { get; }
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/LensApertureConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace PhotoViewerDemo
{
    /// <summary>
    ///     Converts a lens aperture from a decimal into a human-preferred string (e.g. 1.8 becomes F1.8)
    /// </summary>
    public class LensApertureConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return $"F{value:##.0}";
            }
            return string.Empty;
        }

        public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
        {
            if (!string.IsNullOrEmpty((string) value))
            {
                return decimal.Parse(((string) value).Substring(1));
            }
            return null;
        }
    }
}

<|start_filename|>Accessibility/FocusTracker/Tracker.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Automation;

namespace FocusTracker
{
    internal class Tracker
    {
        private AutomationElement _lastTopLevelWindow;

        /// <summary>
        ///     Constructor.
        /// </summary>
        public Tracker()
        {
            Startup();
        }

        /// <summary>
        ///     Entry point.
        /// </summary>
        /// <param name="args">Command-line arguments; not used.</param>
        public static void Main(string[] args)
        {
            Console.Title = "UI Automation Focus-tracking Sample";
            Console.WriteLine("Please wait while UI Automation initializes...");
            var reader = new Tracker();
            Console.WriteLine("Tracking focus. Press Enter to quit.");
            Console.ReadLine();
            Automation.RemoveAllEventHandlers();
        }

        /// <summary>
        ///     Initialization.
        /// </summary>
        private void Startup()
        {
            Automation.AddAutomationFocusChangedEventHandler(OnFocusChanged);
        }

        /// <summary>
        ///     Retrieves the top-level window that contains the specified
        ///     UI Automation element.
        /// </summary>
        /// <param name="element">The contained element.</param>
        /// <returns>The  top-level window element.</returns>
        private AutomationElement GetTopLevelWindow(AutomationElement element)
        {
            var walker = TreeWalker.ControlViewWalker;
            AutomationElement elementParent;
            var node = element;
            try // In case the element disappears suddenly, as menu items are 
                // likely to do.
            {
                if (node == AutomationElement.RootElement)
                {
                    return node;
                }
                // Walk up the tree to the child of the root.
                while (true)
                {
                    elementParent = walker.GetParent(node);
                    if (elementParent == null)
                    {
                        return null;
                    }
                    if (elementParent == AutomationElement.RootElement)
                    {
                        break;
                    }
                    node = elementParent;
                }
            }
            catch (ElementNotAvailableException)
            {
                node = null;
            }
            catch (ArgumentNullException)
            {
                node = null;
            }
            return node;
        }

        /// <summary>
        ///     Handles focus-changed events. If the element that received focus is
        ///     in a different top-level window, announces that. If not, just
        ///     announces which element received focus.
        /// </summary>
        /// <param name="src">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void OnFocusChanged(object src, AutomationFocusChangedEventArgs e)
        {
            try
            {
                var elementFocused = src as AutomationElement;
                var topLevelWindow = GetTopLevelWindow(elementFocused);
                if (topLevelWindow == null)
                {
                    return;
                }

                // If top-level window has changed, announce it.
                if (topLevelWindow != _lastTopLevelWindow)
                {
                    _lastTopLevelWindow = topLevelWindow;
                    Console.WriteLine("Focus moved to top-level window:");
                    Console.WriteLine("  " + topLevelWindow.Current.Name);
                    Console.WriteLine();
                }
                else
                {
                    // Announce focused element.
                    Console.WriteLine("Focused element: ");
                    Console.WriteLine("  Type: " +
                                      elementFocused.Current.LocalizedControlType);
                    Console.WriteLine("  Name: " + elementFocused.Current.Name);
                    Console.WriteLine();
                }
            }
            catch (ElementNotAvailableException)
            {
            }
        }
    }
}

<|start_filename|>Sample Applications/DataBindingDemo/AuctionItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace DataBindingDemo
{
    public class AuctionItem : INotifyPropertyChanged
    {
        private readonly ObservableCollection<Bid> _bids;
        private ProductCategory _category;
        private string _description;
        private SpecialFeatures _specialFeatures;
        private DateTime _startDate;
        private int _startPrice;

        public AuctionItem(string description, ProductCategory category, int startPrice, DateTime startDate, User owner,
            SpecialFeatures specialFeatures)
        {
            _description = description;
            _category = category;
            _startPrice = startPrice;
            _startDate = startDate;
            Owner = owner;
            _specialFeatures = specialFeatures;
            _bids = new ObservableCollection<Bid>();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        ///     Exposing Bids as a ReadOnlyObservableCollection and adding an AddBid method so that CurrentPrice
        /// </summary>
        /// <param name="bid"></param>
        public void AddBid(Bid bid)
        {
            _bids.Add(bid);
            OnPropertyChanged("CurrentPrice");
        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        #region Properties Getters and Setters

        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                OnPropertyChanged("Description");
            }
        }

        public int StartPrice
        {
            get { return _startPrice; }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Price must be positive");
                }
                _startPrice = value;
                OnPropertyChanged("StartPrice");
                OnPropertyChanged("CurrentPrice");
            }
        }

        public DateTime StartDate
        {
            get { return _startDate; }
            set
            {
                _startDate = value;
                OnPropertyChanged("StartDate");
            }
        }

        public ProductCategory Category
        {
            get { return _category; }
            set
            {
                _category = value;
                OnPropertyChanged("Category");
            }
        }

        public User Owner { get; }

        public SpecialFeatures SpecialFeatures
        {
            get { return _specialFeatures; }
            set
            {
                _specialFeatures = value;
                OnPropertyChanged("SpecialFeatures");
            }
        }

        public ReadOnlyObservableCollection<Bid> Bids => new ReadOnlyObservableCollection<Bid>(_bids);

        public int CurrentPrice
        {
            get
            {
                var price = 0;
                // There is at least on bid on this product
                if (_bids.Count > 0)
                {
                    // Get the amount of the last bid
                    var lastBid = _bids[_bids.Count - 1];
                    price = lastBid.Amount;
                }
                // No bids on this product yet
                else
                {
                    price = _startPrice;
                }
                return price;
            }
        }

        #endregion
    }
}

<|start_filename|>Speech and Media/MediaGallery/MediaElementExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MediaGallery
{
    public partial class MediaElementExample : Page
    {
        // Play the media.
        private void OnMouseDownPlayMedia(object sender, MouseButtonEventArgs args)
        {
            // The Play method will begin the media if it is not currently active or 
            // resume media if it is paused. This has no effect if the media is
            // already running.
            myMediaElement.Play();

            // Initialize the MediaElement property values.
            InitializePropertyValues();
        }

        // Pause the media.
        private void OnMouseDownPauseMedia(object sender, MouseButtonEventArgs args)
        {
            // The Pause method pauses the media if it is currently running.
            // The Play method can be used to resume.
            myMediaElement.Pause();
        }

        // Stop the media.
        private void OnMouseDownStopMedia(object sender, MouseButtonEventArgs args)
        {
            // The Stop method stops and resets the media to be played from
            // the beginning.
            myMediaElement.Stop();
        }

        // Change the volume of the media.
        public void ChangeMediaVolume(object sender, RoutedPropertyChangedEventArgs<double> args)
        {
            myMediaElement.Volume = volumeSlider.Value;
        }

        // When the media opens, initialize the "Seek To" slider maximum value
        // to the total number of miliseconds in the length of the media clip.
        public void Element_MediaOpened(object sender, EventArgs e)
        {
            timelineSlider.Maximum = myMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
        }

        // Jump to different parts of the media (seek to). 
        public void SeekToMediaPosition(object sender, RoutedPropertyChangedEventArgs<double> args)
        {
            var sliderValue = (int) timelineSlider.Value;

            // Overloaded constructor takes the arguments days, hours, minutes, seconds, miniseconds.
            // Create a TimeSpan with miliseconds equal to the slider value.
            var ts = new TimeSpan(0, 0, 0, 0, sliderValue);
            myMediaElement.Position = ts;
        }

        private void InitializePropertyValues()
        {
            // Set the media's starting Volume to the current value of the
            // its slider control.
            myMediaElement.Volume = volumeSlider.Value;
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/aitdecoder.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Declaration of AitDecoder
//----------------------------------------------------------------------------------------
#pragma once

#include "UnknownImpl.h"

extern const GUID CLSID_AitContainer;
extern const GUID CLSID_AitDecoder;

struct AitBlockHeader;

class AitFrameDecode : public BaseFrameDecode
{
public:
    AitFrameDecode(IWICImagingFactory *pIFactory, UINT num);
    ~AitFrameDecode();

    // IWICBitmapFrameDecode Interface

    HRESULT InputColBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputFraBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputPalBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputPreBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputThuBlock(IStream *stream, const AitBlockHeader &bh);

private:
};


class AitDecoder : public BaseDecoder
{
public:
    AitDecoder();
    ~AitDecoder();


    // IWICBitmapDecoder Interface
    STDMETHOD(QueryCapability)( 
        /* [in] */ IStream *pIStream,
        /* [out] */ DWORD *pCapability);

    STDMETHOD(Initialize)( 
        /* [in] */ IStream *pIStream,
        /* [in] */ WICDecodeOptions cacheOptions);
 
   //Additional Functions
   virtual BaseFrameDecode* CreateNewDecoderFrame(IWICImagingFactory* factory , UINT i); 

private:
    HRESULT InputBlock(IStream *stream, AitBlockHeader &bh);
    HRESULT InputAitBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputColBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputFraBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputPalBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputPreBlock(IStream *stream, const AitBlockHeader &bh);
    HRESULT InputThuBlock(IStream *stream, const AitBlockHeader &bh);
};


<|start_filename|>Compatibility/AppContextInformation.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Wpf_AppCompat_Quirks
{
    public class CompatSwitchInformation
    {
        public string Class { get; set; }
        public string SwitchName { get; set; }
        public string DefaultValue { get; set; }
        public string SettingsSource { get; set; }
    }
}


<|start_filename|>PerMonitorDPI/TextFormatting/FontRendering.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;

namespace TextFormatting
{
    /// <summary>
    /// Class for combining Font and other text related properties. 
    /// (Typeface, Alignment, Decorations, etc)
    /// </summary>
    class FontRendering
    {
        #region Constructors
        public FontRendering(
           double emSize,
           TextAlignment alignment,
           TextDecorationCollection decorations,
           Brush textColor,
           Typeface face)
        {
            _fontSize = emSize;
            _alignment = alignment;
            _textDecorations = decorations;
            _textColor = textColor;
            _typeface = face;
        }

        public FontRendering()
        {
            _fontSize = 12.0f;
            _alignment = TextAlignment.Left;
            _textDecorations = new TextDecorationCollection();
            _textColor = Brushes.Black;
            _typeface = new Typeface(new FontFamily("Arial"),
               FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
        }
        #endregion

        #region Properties
        public double FontSize
        {
            get { return _fontSize; }
            set
            {
                if (value <= 0)
                    throw new ArgumentOutOfRangeException("value", "Parameter Must Be Greater Than Zero.");
                if (double.IsNaN(value))
                    throw new ArgumentOutOfRangeException("value", "Parameter Cannot Be NaN.");
                _fontSize = value;
            }
        }

        public TextAlignment TextAlignment
        {
            get { return _alignment; }
            set { _alignment = value; }
        }

        public TextDecorationCollection TextDecorations
        {
            get { return _textDecorations; }
            set { _textDecorations = value; }
        }

        public Brush TextColor
        {
            get { return _textColor; }
            set { _textColor = value; }
        }

        public Typeface Typeface
        {
            get { return _typeface; }
            set { _typeface = value; }
        }
        #endregion

        #region Private Fields
        private double _fontSize;
        private TextAlignment _alignment;
        private TextDecorationCollection _textDecorations;
        private Brush _textColor;
        private Typeface _typeface;
        #endregion
    }
}


<|start_filename|>Sample Applications/PhotoStoreDemo/ImageFile.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Media.Imaging;

namespace PhotoStoreDemo
{
    public class ImageFile
    {
        public ImageFile(string path)
        {
            Path = path;
            Uri = new Uri(Path);
            Image = BitmapFrame.Create(Uri);
        }

        public string Path { get; }
        public Uri Uri { get; }
        public BitmapFrame Image { get; }

        public override string ToString() => Path;
    }
}

<|start_filename|>Sample Applications/FontDialog/FontSizeListItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Controls;

namespace FontDialog
{
    internal class FontSizeListItem : TextBlock, IComparable
    {
        public FontSizeListItem(double sizeInPoints)
        {
            SizeInPoints = sizeInPoints;
            Text = sizeInPoints.ToString(CultureInfo.InvariantCulture);
        }

        public double SizeInPoints { get; }
        public double SizeInPixels => PointsToPixels(SizeInPoints);

        int IComparable.CompareTo(object obj)
        {
            double value;

            if (obj is double)
            {
                value = (double) obj;
            }
            else
            {
                if (!double.TryParse(obj.ToString(), out value))
                {
                    return 1;
                }
            }

            return
                FuzzyEqual(SizeInPoints, value)
                    ? 0
                    : (SizeInPoints < value) ? -1 : 1;
        }

        public override string ToString() => SizeInPoints.ToString(CultureInfo.InvariantCulture);

        public static bool FuzzyEqual(double a, double b) => Math.Abs(a - b) < 0.01;

        public static double PointsToPixels(double value) => value * (96.0 / 72.0);

        public static double PixelsToPoints(double value) => value * (72.0 / 96.0);
    }
}

<|start_filename|>Graphics/AITCodec/cpp/unknownimpl.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------
//  Description: Declaration and Definition of TestUnknown
//----------------------------------------------------------------------------------------
#pragma once


class UnknownImpl
{
private:
    int numReferences;

public:
    UnknownImpl()
        : numReferences(0)
    {}

    ULONG STDMETHODCALLTYPE AddRef()
    {
        return ++numReferences;
    }

    ULONG STDMETHODCALLTYPE Release()
    {
        ULONG result;

        if (numReferences > 0)
        {
            --numReferences;
            result = numReferences;
        }
        else
        {
            result = numReferences = 0;
        }

        return result;
    }
};


<|start_filename|>Migration and Interoperability/HostingWfWithVisualStyles/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using Application = System.Windows.Forms.Application;

namespace HostingWfWithVisualStyles
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            // Comment out the following line to disable visual
            // styles for the hosted Windows Forms control.
            Application.EnableVisualStyles();

            // Create a WindowsFormsHost element to host
            // the Windows Forms control.
            var host =
                new WindowsFormsHost();

            // Create a Windows Forms tab control.
            var tc = new TabControl();
            tc.TabPages.Add("Tab1");
            tc.TabPages.Add("Tab2");

            // Assign the Windows Forms tab control as the hosted control.
            host.Child = tc;

            // Assign the host element to the parent Grid element.
            grid1.Children.Add(host);
        }
    }
}

<|start_filename|>Input and Commands/CommandSourceControlUsingSystemTimer/SliderValueConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace CommandSourceControlUsingSystemTimer
{
    [ValueConversion(typeof (double), typeof (int))]
    public class SliderValueConverter : IValueConverter
    {
        public object Convert(object value,
            Type targetType,
            object parameter,
            CultureInfo culture)
        {
            var sliderValue = (double) value;

            return (int) sliderValue;
        }

        public object ConvertBack(object value,
            Type targetType,
            object parameter,
            CultureInfo culture) => null;
    }
}

<|start_filename|>Drag and Drop/DragDropObjects/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace DragDropObjects
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _isDown;
        private bool _isDragging;
        private Canvas _myCanvas;
        private UIElement _originalElement;
        private double _originalLeft;
        private double _originalTop;
        private SimpleCircleAdorner _overlayElement;
        private Point _startPoint;

        public void OnPageLoad(object sender, RoutedEventArgs e)
        {
            _myCanvas = new Canvas();

            var rect1 = new Rectangle();
            rect1.Height = rect1.Width = 32;
            rect1.Fill = Brushes.Blue;

            Canvas.SetTop(rect1, 8);
            Canvas.SetLeft(rect1, 8);


            var tb = new TextBox {Text = "This is a TextBox. Drag and drop me"};
            Canvas.SetTop(tb, 100);
            Canvas.SetLeft(tb, 100);

            _myCanvas.Children.Add(rect1);
            _myCanvas.Children.Add(tb);

            _myCanvas.PreviewMouseLeftButtonDown += MyCanvas_PreviewMouseLeftButtonDown;
            _myCanvas.PreviewMouseMove += MyCanvas_PreviewMouseMove;
            _myCanvas.PreviewMouseLeftButtonUp += MyCanvas_PreviewMouseLeftButtonUp;
            PreviewKeyDown += window1_PreviewKeyDown;

            myStackPanel.Children.Add(_myCanvas);
        }

        private void window1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape && _isDragging)
            {
                DragFinished(true);
            }
        }

        private void MyCanvas_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_isDown)
            {
                DragFinished(false);
                e.Handled = true;
            }
        }

        private void DragFinished(bool cancelled)
        {
            Mouse.Capture(null);
            if (_isDragging)
            {
                AdornerLayer.GetAdornerLayer(_overlayElement.AdornedElement).Remove(_overlayElement);

                if (cancelled == false)
                {
                    Canvas.SetTop(_originalElement, _originalTop + _overlayElement.TopOffset);
                    Canvas.SetLeft(_originalElement, _originalLeft + _overlayElement.LeftOffset);
                }
                _overlayElement = null;
            }
            _isDragging = false;
            _isDown = false;
        }

        private void MyCanvas_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (_isDown)
            {
                if ((_isDragging == false) &&
                    ((Math.Abs(e.GetPosition(_myCanvas).X - _startPoint.X) >
                      SystemParameters.MinimumHorizontalDragDistance) ||
                     (Math.Abs(e.GetPosition(_myCanvas).Y - _startPoint.Y) >
                      SystemParameters.MinimumVerticalDragDistance)))
                {
                    DragStarted();
                }
                if (_isDragging)
                {
                    DragMoved();
                }
            }
        }

        private void DragStarted()
        {
            _isDragging = true;
            _originalLeft = Canvas.GetLeft(_originalElement);
            _originalTop = Canvas.GetTop(_originalElement);

            _overlayElement = new SimpleCircleAdorner(_originalElement);
            var layer = AdornerLayer.GetAdornerLayer(_originalElement);
            layer.Add(_overlayElement);
        }

        private void DragMoved()
        {
            var currentPosition = Mouse.GetPosition(_myCanvas);

            _overlayElement.LeftOffset = currentPosition.X - _startPoint.X;
            _overlayElement.TopOffset = currentPosition.Y - _startPoint.Y;
        }

        private void MyCanvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.Source == _myCanvas)
            {
            }
            else
            {
                _isDown = true;
                _startPoint = e.GetPosition(_myCanvas);
                _originalElement = e.Source as UIElement;
                _myCanvas.CaptureMouse();
                e.Handled = true;
            }
        }
    }

    // Adorners must subclass the abstract base class Adorner.
}

<|start_filename|>Tools/BamlReflector/BamlTools/HexDumper.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace BamlTools
{
    public class HexDumper
    {
        static string Symbols = "0123456789ABCDEF";

        Stream _reader;
        bool _showAddresses;
        bool _showText;

        public HexDumper(Stream stream)
        {
            _reader = stream;
            _showText = true;
        }

        public string DumpOneBigString()
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                foreach (string line in GetLines())
                {
                    sb.AppendLine(line);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.ToString());
            }

            return sb.ToString();
        }

        public IEnumerable<String> GetLines()
        {
            string hexString;
            byte[] inputBuffer = new byte[FullHexByteLength];

            while (_reader.Position < _reader.Length)
            {
                int count = _reader.Read(inputBuffer, 0, inputBuffer.Length);
                hexString = HexStringConvert(inputBuffer, count);
                if (ShowText)
                {
                    string textString = TextConvert(inputBuffer, count);
                    hexString = Pad(hexString, FullHexStringLength, ' ');
                    hexString += "  " + textString;
                }

                if (ShowAddresses)
                {
                    hexString = String.Format("{0:x5}: {1}", _reader.Position, hexString);
                }
                yield return hexString;
            }
        }

        public bool ShowAddresses
        {
            get { return _showAddresses; }
            set { _showAddresses = value; }
        }

        public bool ShowText
        {
            get { return _showText; }
            set { _showText = value; }
        }

        private const int FullHexByteLength = 16;

        private int FullHexStringLength
        {
            get { return FullHexByteLength * 3; }
        }

        private string HexStringConvert(byte[] input, int count)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                int high = (input[i] >> 4) & 0xF;
                int low = input[i] & 0xF;
                sb.AppendFormat("{0}{1} ", Symbols[high], Symbols[low]);
            }
            return sb.ToString();
        }

        private string TextConvert(byte[] input, int count)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                sb.Append((input[i] < ' ' || (int)input[i] > 127) ? '.' : (char)input[i]);
            }
            return sb.ToString();
        }

        private string Pad(string str, int length, char fill)
        {
            // this is somewhat inefficent, but it is only called once.
            for (int i = str.Length; i < length; i++)
            {
                str += fill;
            }
            return str;
        }
    }
}


<|start_filename|>Migration and Interoperability/PropertyMappingWithElementHost/Form1.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Drawing;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Button = System.Windows.Controls.Button;
using Color = System.Drawing.Color;

namespace PropertyMappingWithElementHost
{
    public partial class Form1 : Form
    {
        private ElementHost _elemHost;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Create the ElementHost control.
            _elemHost = new ElementHost {Dock = DockStyle.Fill};
            Controls.Add(_elemHost);

            // Create a Windows Presentation Foundation Button element 
            // and assign it as the ElementHost control's child. 
            var wpfButton = new Button {Content = "Windows Presentation Foundation Button"};
            _elemHost.Child = wpfButton;

            // Map the Margin property.
            AddMarginMapping();

            // Remove the mapping for the Cursor property.
            RemoveCursorMapping();

            // Add a mapping for the Region property.
            AddRegionMapping();

            // Add another mapping for the BackColor property.
            ExtendBackColorMapping();

            // Cause the OnMarginChange delegate to be called.
            _elemHost.Margin = new Padding(23, 23, 23, 23);

            // Cause the OnRegionChange delegate to be called.
            _elemHost.Region = new Region();

            // Cause the OnBackColorChange delegate to be called.
            _elemHost.BackColor = Color.AliceBlue;
        }

        // The AddMarginMapping method adds a new property mapping
        // for the Margin property.
        private void AddMarginMapping()
        {
            _elemHost.PropertyMap.Add(
                "Margin",
                OnMarginChange);
        }

        // The OnMarginChange method implements the mapping 
        // from the Windows Forms Margin property to the
        // Windows Presentation Foundation Margin property.
        //
        // The provided Padding value is used to construct 
        // a Thickness value for the hosted element's Margin
        // property.
        private void OnMarginChange(object h, string propertyName, object value)
        {
            var host = h as ElementHost;
            var p = (Padding) value;
            var wpfButton =
                host.Child as Button;

            var t = new Thickness(p.Left, p.Top, p.Right, p.Bottom);

            wpfButton.Margin = t;
        }

        // The RemoveCursorMapping method deletes the default
        // mapping for the Cursor property.
        private void RemoveCursorMapping()
        {
            _elemHost.PropertyMap.Remove("Cursor");
        }

        // The AddRegionMapping method assigns a custom 
        // mapping for the Region property.
        private void AddRegionMapping()
        {
            _elemHost.PropertyMap.Add(
                "Region",
                OnRegionChange);
        }

        // The OnRegionChange method assigns an EllipseGeometry to
        // the hosted element's Clip property.
        private void OnRegionChange(
            object h,
            string propertyName,
            object value)
        {
            var host = h as ElementHost;
            var wpfButton =
                host.Child as Button;

            wpfButton.Clip = new EllipseGeometry(new Rect(
                0,
                0,
                wpfButton.ActualWidth,
                wpfButton.ActualHeight));
        }

        // The Form1_Resize method handles the form's Resize event.
        // It calls the OnRegionChange method explicitly to 
        // assign a new clipping geometry to the hosted element.
        private void Form1_Resize(object sender, EventArgs e)
        {
            OnRegionChange(_elemHost, "Region", null);
        }

        // The ExtendBackColorMapping method adds a property
        // translator if a mapping already exists.
        private void ExtendBackColorMapping()
        {
            if (_elemHost.PropertyMap["BackColor"] != null)
            {
                _elemHost.PropertyMap["BackColor"] +=
                    OnBackColorChange;
            }
        }

        // The OnBackColorChange method assigns a specific image 
        // to the hosted element's Background property.
        private void OnBackColorChange(object h, string propertyName, object value)
        {
            var host = h as ElementHost;
            var wpfButton =
                host.Child as Button;

            var b = new ImageBrush(new BitmapImage(
                new Uri(@"file:///C:\WINDOWS\Santa Fe Stucco.bmp")));
            wpfButton.Background = b;
        }
    }
}

// </snippet1>

<|start_filename|>Animation/Per-FrameAnimation/ParticleEffects/OverlayRenderDecoratorOverlayVisual.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Media;

namespace PerFrameAnimation
{
    /// <summary>
    ///     This class is used internally to delegate it's rendering to the parent OverlayRenderDecorator.
    /// </summary>
    internal class OverlayRenderDecoratorOverlayVisual : DrawingVisual
    {
        internal bool IsHitTestVisible { get; set; } = false;
        //dont hit test, these are just overlay graphics
        protected override GeometryHitTestResult HitTestCore(GeometryHitTestParameters hitTestParameters)
        {
            if (IsHitTestVisible)
                return base.HitTestCore(hitTestParameters);
            return null;
        }

        //dont hit test, these are just overlay graphics
        protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
        {
            if (IsHitTestVisible)
                return base.HitTestCore(hitTestParameters);
            return null;
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/cmykpixelformatconverter.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------
//  Description: Declaration of CmykPixelFormatConverter
//----------------------------------------------------------------------------------------
#pragma once

// {B312A459-2A44-4833-AA45-0F50BC669A28}
extern const GUID CLSID_CmykPixelFormatConverter;

class CmykPixelFormatConverter : public BasePixelFormatConverter
{
public:
    CmykPixelFormatConverter();

    STDMETHOD(CanConvert)( 
        /* [in] */ REFWICPixelFormatGUID srcPixelFormat,
        /* [in] */ REFWICPixelFormatGUID dstPixelFormat,
        /* [out] */ BOOL *pfCanConvert);   

    STDMETHOD(CopyPixels)( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels);

    //Additional Functions
private :
    HRESULT ConvertCmykToRgb( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels);
    HRESULT ConvertRgbToCmyk( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels);    
};

<|start_filename|>Input and Commands/HandlingEventOnCommandUsingCode/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace HandlingEventOnCommandUsingCode
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // Creating the main panel
            var mainStackPanel = new StackPanel();
            AddChild(mainStackPanel);

            // Button used to invoke the command
            var commandButton = new Button
            {
                Command = ApplicationCommands.Open,
                Content = "Open (KeyBindings: Ctrl-R, Ctrl-0)"
            };
            mainStackPanel.Children.Add(commandButton);

            // Creating CommandBinding and attaching an Executed and CanExecute handler
            var openCmdBinding = new CommandBinding(
                ApplicationCommands.Open,
                OpenCmdExecuted,
                OpenCmdCanExecute);

            CommandBindings.Add(openCmdBinding);

            // Creating a KeyBinding between the Open command and Ctrl-R
            var openCmdKeyBinding = new KeyBinding(
                ApplicationCommands.Open,
                Key.R,
                ModifierKeys.Control);

            InputBindings.Add(openCmdKeyBinding);
        }

        private void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("The command has been invoked.");
        }

        private void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    }
}

<|start_filename|>Documents/Flow Content/FlowDocumentProperties/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace FlowDocumentProperties
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // For quick access to the underlying DynamicPageinator.
        private DynamicDocumentPaginator _dynPaginator;
        private TextEffectTarget[] _textEffectTargets;

        public MainWindow()
        {
            InitializeComponent();
        }

        public void WindowLoaded(object sender, RoutedEventArgs e)
        {
            _dynPaginator = ((IDocumentPaginatorSource) fd1).DocumentPaginator as DynamicDocumentPaginator;
            if (_dynPaginator == null)
                throw new NullReferenceException("Can't get a DynamicDocumentPaginator for FlowDocument fd1.");
        }

        public void MakebgVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            backgroundProp.Visibility = Visibility.Visible;
            tb2.Text =
                "If you set the Foreground and Background colors to the same color, TextContent will no longer be visible.";
        }

        public void MakecgVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            columngapProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakecrbVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            columnrulebrushProp.Visibility = Visibility.Visible;
            tb2.Text = "This property will have no effect if ColumnRuleWidth is not set.";
        }

        public void MakecrwVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            columnrulewidthProp.Visibility = Visibility.Visible;
            tb2.Text = "This property will have no effect if ColumnRuleBrush is not set.";
        }

        public void MakecwVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            columnwidthProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakeceVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            contentendProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakecsVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            contentstartProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakefdVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            flowdirectionProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakeffVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            fontfamilyProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakefsVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            fontsizeProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakefstVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            fontstretchProp.Visibility = Visibility.Visible;
            tb2.Text = "Some fonts do not support all FontStretch values.";
        }

        public void MakefstyleVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            fontstyleProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakefwVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            fontweightProp.Visibility = Visibility.Visible;
            tb2.Text = "Not all FontWeight values result in unique rendering.";
        }

        public void MakebpeVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            isbackgroundpaginationenabledProp.Visibility = Visibility.Visible;
            tb2.Text = "This setting will not effect visual rendering of content.";
        }

        public void MakecwfVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            iscolumnwidthflexibleProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakepcfVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            ispagecountfinalProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakefgVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp1.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            foregroundProp.Visibility = Visibility.Visible;
            tb2.Text =
                "If you set the Foreground and Background colors to the same color, TextContent will no longer be visible.";
        }

        public void MakelhVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            lineheightProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakemaxphVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            maxpageheightProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakemaxpwVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            maxpagewidthProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakeminphVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            minpageheightProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakeminpwVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            minpagewidthProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakepcountVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            pagecountProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakephVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            pageheightProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakeppVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            pagepaddingProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakepsVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            pagesizeProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MakepwVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            pagewidthProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        public void MaketaVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            textalignmentProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        /*
        public void makettVisible(object sender, System.Windows.RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            texttrimmingProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }
        */

        public void MaketeVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            texteffectsProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }

        /*
        public void maketwVisible(object sender, System.Windows.RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            textwrapProp.Visibility = Visibility.Visible;
            tb2.Text = "";
        }
        */

        public void MaketpVisible(object sender, RoutedEventArgs e)
        {
            foreach (UIElement child in sp2.Children)
            {
                child.Visibility = Visibility.Collapsed;
            }
            typographyProp.Visibility = Visibility.Visible;
            fd1.FontFamily = new FontFamily("Palatino Linotype");
            tb2.Text =
                "FontFamily has been changed to Palatino as it is an OpenType font and supports Typography features.";
        }

        // Begin Background change methods
        public void SetBackgroundRed(object sender, RoutedEventArgs e)
        {
            fd1.Background = Brushes.Red;
        }

        public void SetBackgroundBlue(object sender, RoutedEventArgs e)
        {
            fd1.Background = Brushes.Blue;
        }

        public void SetBackgroundGreen(object sender, RoutedEventArgs e)
        {
            fd1.Background = Brushes.Green;
        }

        public void SetBackgroundPurple(object sender, RoutedEventArgs e)
        {
            fd1.Background = Brushes.Purple;
        }

        public void SetBackgroundWhite(object sender, RoutedEventArgs e)
        {
            fd1.Background = Brushes.White;
        }

        // Begin ColumnGap change methods
        public void Cg5(object sender, RoutedEventArgs e)
        {
            fd1.ColumnGap = 5;
        }

        public void Cg10(object sender, RoutedEventArgs e)
        {
            fd1.ColumnGap = 10;
        }

        public void Cg15(object sender, RoutedEventArgs e)
        {
            fd1.ColumnGap = 15;
        }

        public void Cg20(object sender, RoutedEventArgs e)
        {
            fd1.ColumnGap = 20;
        }

        // Begin ColumnRuleBrush change methods
        public void SetcolruleGray(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleBrush = Brushes.Gray;
        }

        public void SetcolruleBlack(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleBrush = Brushes.Black;
        }

        public void SetcolruleRed(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleBrush = Brushes.Red;
        }

        public void SetcolruleBlue(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleBrush = Brushes.Blue;
        }

        // Begin ColumnRuleWidth change methods
        public void Crw1(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleWidth = 1;
        }

        public void Crw3(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleWidth = 3;
        }

        public void Crw5(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleWidth = 5;
        }

        public void Crw10(object sender, RoutedEventArgs e)
        {
            fd1.ColumnRuleWidth = 10;
        }

        // Begin ColumnWidth change methods
        public void Cw100(object sender, RoutedEventArgs e)
        {
            fd1.ColumnWidth = 100;
        }

        public void Cw150(object sender, RoutedEventArgs e)
        {
            fd1.ColumnWidth = 150;
        }

        public void Cw200(object sender, RoutedEventArgs e)
        {
            fd1.ColumnWidth = 200;
        }

        public void Cw250(object sender, RoutedEventArgs e)
        {
            fd1.ColumnWidth = 250;
        }

        // Begin ContentEnd method
        public void GetCeValue(object sender, RoutedEventArgs e)
        {
            var para1 = new Paragraph();
            fd1.Blocks.Add(para1);
            para1.Inlines.Add(new Run(" " + "Text added to the end of the FlowDocument."));
        }

        // Begin ContentStart method
        public void GetCsValue(object sender, RoutedEventArgs e)
        {
            var para2 = new Paragraph();
            fd1.Blocks.Add(para2);
            para2.Inlines.Add(new Run(" " + "Text added to the beginning of the FlowDocument."));
        }

        // Begin FlowDirection change methods
        public void Fdirection1(object sender, RoutedEventArgs e)
        {
            fd1.FlowDirection = FlowDirection.LeftToRight;
        }

        public void Fdirection2(object sender, RoutedEventArgs e)
        {
            fd1.FlowDirection = FlowDirection.RightToLeft;
        }

        // Begin FontFamily change methods
        public void FfTimes(object sender, RoutedEventArgs e)
        {
            fd1.FontFamily = new FontFamily("Times New Roman");
        }

        public void FfVerdana(object sender, RoutedEventArgs e)
        {
            fd1.FontFamily = new FontFamily("Verdana");
        }

        public void FfPalatino(object sender, RoutedEventArgs e)
        {
            fd1.FontFamily = new FontFamily("Palatino Linotype");
        }

        public void FfCourier(object sender, RoutedEventArgs e)
        {
            fd1.FontFamily = new FontFamily("Courier New");
        }

        // Begin FontSize change methods
        public void Fs10(object sender, RoutedEventArgs e)
        {
            fd1.FontSize = 10;
        }

        public void Fs15(object sender, RoutedEventArgs e)
        {
            fd1.FontSize = 15;
        }

        public void Fs20(object sender, RoutedEventArgs e)
        {
            fd1.FontSize = 20;
        }

        public void Fs25(object sender, RoutedEventArgs e)
        {
            fd1.FontSize = 25;
        }

        // Begin FontStretch change methods
        public void FstNormal(object sender, RoutedEventArgs e)
        {
            fd1.FontStretch = FontStretches.Normal;
        }

        public void FstCondensed(object sender, RoutedEventArgs e)
        {
            fd1.FontStretch = FontStretches.Condensed;
        }

        public void FstExpanded(object sender, RoutedEventArgs e)
        {
            fd1.FontStretch = FontStretches.Expanded;
        }

        public void FstMedium(object sender, RoutedEventArgs e)
        {
            fd1.FontStretch = FontStretches.Medium;
        }

        // Begin FontWeight change methods
        public void FwNormal(object sender, RoutedEventArgs e)
        {
            fd1.FontWeight = FontWeights.Normal;
        }

        public void FwLight(object sender, RoutedEventArgs e)
        {
            fd1.FontWeight = FontWeights.Light;
        }

        public void FwMedium(object sender, RoutedEventArgs e)
        {
            fd1.FontWeight = FontWeights.Medium;
        }

        public void FwBold(object sender, RoutedEventArgs e)
        {
            fd1.FontWeight = FontWeights.Bold;
        }

        public void FwUltraBold(object sender, RoutedEventArgs e)
        {
            fd1.FontWeight = FontWeights.UltraBold;
        }

        // Begin FontStyle change methods
        public void FstyleNormal(object sender, RoutedEventArgs e)
        {
            fd1.FontStyle = FontStyles.Normal;
        }

        public void FstyleItalic(object sender, RoutedEventArgs e)
        {
            fd1.FontStyle = FontStyles.Italic;
        }

        public void FstyleOblique(object sender, RoutedEventArgs e)
        {
            fd1.FontStyle = FontStyles.Oblique;
        }

        // Begin Foreground change methods
        public void ForegroundWhite(object sender, RoutedEventArgs e)
        {
            fd1.Foreground = Brushes.White;
        }

        public void ForegroundBlack(object sender, RoutedEventArgs e)
        {
            fd1.Foreground = Brushes.Black;
        }

        public void ForegroundBlue(object sender, RoutedEventArgs e)
        {
            fd1.Foreground = Brushes.Blue;
        }

        public void ForegroundRed(object sender, RoutedEventArgs e)
        {
            fd1.Foreground = Brushes.Red;
        }

        // Begin IsBackgroundPaginationEnabled change methods
        public void BpeTrue(object sender, RoutedEventArgs e)
        {
            _dynPaginator.IsBackgroundPaginationEnabled = true;
            tb2.Text = "IsBackgroundPaginationEnabled property is set to " +
                       _dynPaginator.IsBackgroundPaginationEnabled;
        }

        public void BpeFalse(object sender, RoutedEventArgs e)
        {
            _dynPaginator.IsBackgroundPaginationEnabled = false;
            tb2.Text = "IsBackgroundPaginationEnabled property is set to " +
                       _dynPaginator.IsBackgroundPaginationEnabled;
        }

        // Begin IsColumnWidthFlexible change methods
        public void CwfTrue(object sender, RoutedEventArgs e)
        {
            fd1.IsColumnWidthFlexible = true;
            tb2.Text = "IsColumnWidthFlexible property is set to " + fd1.IsColumnWidthFlexible;
        }

        public void CwfFalse(object sender, RoutedEventArgs e)
        {
            fd1.IsColumnWidthFlexible = false;
            tb2.Text = "IsColumnWidthFlexible property is set to " + fd1.IsColumnWidthFlexible;
        }

        // Begin IsPageCountFinal get method
        public void GetpcfValue(object sender, RoutedEventArgs e)
        {
            tb2.Text = "IsPageCountFinal value is " + _dynPaginator.IsPageCountValid;
        }

        // Begin Lineheight change methods
        public void Lineheight10(object sender, RoutedEventArgs e)
        {
            fd1.LineHeight = 10;
        }

        public void Lineheight20(object sender, RoutedEventArgs e)
        {
            fd1.LineHeight = 20;
        }

        public void Lineheight30(object sender, RoutedEventArgs e)
        {
            fd1.LineHeight = 30;
        }

        public void Lineheight40(object sender, RoutedEventArgs e)
        {
            fd1.LineHeight = 40;
        }

        // Begin MaxPageHeight change methods
        public void Maxpageheight500(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageHeight = 500;
            tb2.Text = "MaxPageHeight property is set to " + fd1.MaxPageHeight;
        }

        public void Maxpageheight600(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageHeight = 600;
            tb2.Text = "MaxPageHeight property is set to " + fd1.MaxPageHeight;
        }

        public void Maxpageheight700(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageHeight = 700;
            tb2.Text = "MaxPageHeight property is set to " + fd1.MaxPageHeight;
        }

        public void Maxpageheight800(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageHeight = 800;
            tb2.Text = "MaxPageHeight property is set to " + fd1.MaxPageHeight;
        }

        // Begin MaxPageWidth change methods
        public void Maxpagewidth300(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageWidth = 300;
            tb2.Text = "MaxPageWidth property is set to " + fd1.MaxPageWidth;
        }

        public void Maxpagewidth400(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageWidth = 400;
            tb2.Text = "MaxPageWidth property is set to " + fd1.MaxPageWidth;
        }

        public void Maxpagewidth500(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageWidth = 500;
            tb2.Text = "MaxPageWidth property is set to " + fd1.MaxPageWidth;
        }

        public void Maxpagewidth600(object sender, RoutedEventArgs e)
        {
            fd1.MaxPageWidth = 600;
            tb2.Text = "MaxPageWidth property is set to " + fd1.MaxPageWidth;
        }

        // Begin MinPageHeight change methods
        public void Minpageheight200(object sender, RoutedEventArgs e)
        {
            fd1.MinPageHeight = 200;
            tb2.Text = "MinPageHeight property is set to " + fd1.MinPageHeight;
        }

        public void Minpageheight300(object sender, RoutedEventArgs e)
        {
            fd1.MinPageHeight = 300;
            tb2.Text = "MaxPageHeight property is set to " + fd1.MinPageHeight;
        }

        public void Minpageheight400(object sender, RoutedEventArgs e)
        {
            fd1.MinPageHeight = 400;
            tb2.Text = "MinPageHeight property is set to " + fd1.MinPageHeight;
        }

        public void Minpageheight500(object sender, RoutedEventArgs e)
        {
            fd1.MinPageHeight = 500;
            tb2.Text = "MinPageHeight property is set to " + fd1.MinPageHeight;
        }

        // Begin MinPageWidth change methods
        public void Minpagewidth200(object sender, RoutedEventArgs e)
        {
            fd1.MinPageWidth = 200;
            tb2.Text = "MinPageWidth property is set to " + fd1.MinPageWidth;
        }

        public void Minpagewidth300(object sender, RoutedEventArgs e)
        {
            fd1.MinPageWidth = 300;
            tb2.Text = "MaxPageWidth property is set to " + fd1.MinPageWidth;
        }

        public void Minpagewidth400(object sender, RoutedEventArgs e)
        {
            fd1.MinPageWidth = 400;
            tb2.Text = "MinPageWidth property is set to " + fd1.MinPageWidth;
        }

        public void Minpagewidth500(object sender, RoutedEventArgs e)
        {
            fd1.MinPageWidth = 500;
            tb2.Text = "MinPageWidth property is set to " + fd1.MinPageWidth;
        }

        // Begin PageCount get method
        public void GetpcValue(object sender, RoutedEventArgs e)
        {
            tb2.Text = "PageCount value is " + _dynPaginator.PageCount;
        }

        // Begin PageHeight change methods
        public void Pageheight200(object sender, RoutedEventArgs e)
        {
            fd1.PageHeight = 200;
            tb2.Text = "PageHeight property is set to " + fd1.PageHeight;
        }

        public void Pageheight400(object sender, RoutedEventArgs e)
        {
            fd1.PageHeight = 400;
            tb2.Text = "PageHeight property is set to " + fd1.PageHeight;
        }

        public void Pageheight600(object sender, RoutedEventArgs e)
        {
            fd1.PageHeight = 600;
            tb2.Text = "PageHeight property is set to " + fd1.PageHeight;
        }

        public void Pageheight800(object sender, RoutedEventArgs e)
        {
            fd1.PageHeight = 800;
            tb2.Text = "PageHeight property is set to " + fd1.PageHeight;
        }

        // Begin PagePadding change methods
        public void Pagepadding5(object sender, RoutedEventArgs e)
        {
            fd1.PagePadding = new Thickness(5);
            tb2.Text = "PagePadding property is set to " + fd1.PagePadding;
        }

        public void Pagepadding10(object sender, RoutedEventArgs e)
        {
            fd1.PagePadding = new Thickness(10);
            tb2.Text = "PagePadding property is set to " + fd1.PagePadding;
        }

        public void Pagepadding15(object sender, RoutedEventArgs e)
        {
            fd1.PagePadding = new Thickness(15);
            tb2.Text = "PagePadding property is set to " + fd1.PagePadding;
        }

        public void Pagepadding20(object sender, RoutedEventArgs e)
        {
            fd1.PagePadding = new Thickness(20);
            tb2.Text = "PagePadding property is set to " + fd1.PagePadding;
        }

        // Begin PageSize change methods
        public void Pagesize200(object sender, RoutedEventArgs e)
        {
            // fd1.PageSize = new Size(200, 200);
            // tb2.Text = "PageSize property is set to " + fd1.PageSize.ToString();
            _dynPaginator.PageSize = new Size(200, 200);
            tb2.Text = "PageSize is set to " + _dynPaginator.PageSize;
        }

        public void Pagesize400(object sender, RoutedEventArgs e)
        {
            _dynPaginator.PageSize = new Size(400, 400);
            tb2.Text = "PageSize property is set to " + _dynPaginator.PageSize;
        }

        public void Pagesize600(object sender, RoutedEventArgs e)
        {
            _dynPaginator.PageSize = new Size(600, 600);
            tb2.Text = "PageSize property is set to " + _dynPaginator.PageSize;
        }

        public void Pagesize800(object sender, RoutedEventArgs e)
        {
            _dynPaginator.PageSize = new Size(800, 800);
            tb2.Text = "PageSize property is set to " + _dynPaginator.PageSize;
        }

        // Begin PageWidth change methods
        public void Pagewidth200(object sender, RoutedEventArgs e)
        {
            fd1.PageWidth = 200;
            tb2.Text = "PageWidth property is set to " + fd1.PageWidth;
        }

        public void Pagewidth400(object sender, RoutedEventArgs e)
        {
            fd1.PageWidth = 400;
            tb2.Text = "PageWidth property is set to " + fd1.PageWidth;
        }

        public void Pagewidth600(object sender, RoutedEventArgs e)
        {
            fd1.PageWidth = 600;
            tb2.Text = "PageWidth property is set to " + fd1.PageWidth;
        }

        // Begin TextAlignment change methods
        public void TalignLeft(object sender, RoutedEventArgs e)
        {
            fd1.TextAlignment = TextAlignment.Left;
        }

        public void TalignRight(object sender, RoutedEventArgs e)
        {
            fd1.TextAlignment = TextAlignment.Right;
        }

        public void TalignCenter(object sender, RoutedEventArgs e)
        {
            fd1.TextAlignment = TextAlignment.Center;
        }

        public void TalignJustify(object sender, RoutedEventArgs e)
        {
            fd1.TextAlignment = TextAlignment.Justify;
        }

        // Begin Typography change methods
        public void Typo1(object sender, RoutedEventArgs e)
        {
            Typography.SetHistoricalForms(fd1, false);
            Typography.SetVariants(fd1, FontVariants.Normal);
            Typography.SetCapitals(fd1, FontCapitals.SmallCaps);
        }

        public void Typo2(object sender, RoutedEventArgs e)
        {
            Typography.SetHistoricalForms(fd1, false);
            Typography.SetCapitals(fd1, FontCapitals.Normal);
            Typography.SetVariants(fd1, FontVariants.Subscript);
        }

        public void Typo3(object sender, RoutedEventArgs e)
        {
            Typography.SetVariants(fd1, FontVariants.Normal);
            Typography.SetCapitals(fd1, FontCapitals.Normal);
            Typography.SetHistoricalForms(fd1, true);
        }

        // Begin TextEffect methods
        public void TeTranslate(object sender, RoutedEventArgs e)
        {
            DisableTextEffects();

            var myEffect = new TextEffect
            {
                PositionStart = 0,
                PositionCount = 999
            };
            var myTranslateTransform = new TranslateTransform(50, 50);
            myEffect.Transform = myTranslateTransform;

            EnableTextEffects(fd1, myEffect);
            tb2.Text = "The TranslateTransform applied moved the TextBlock to an offset position of 50,50.";
        }

        public void TeScale(object sender, RoutedEventArgs e)
        {
            DisableTextEffects();

            var myEffect = new TextEffect
            {
                PositionStart = 0,
                PositionCount = 999
            };
            var myScaleTransform = new ScaleTransform(5, 5);
            myEffect.Transform = myScaleTransform;

            EnableTextEffects(fd1, myEffect);
            tb2.Text = "The ScaleTransform applied scaled the text by a factor of 5.";
        }

        public void TeRotate(object sender, RoutedEventArgs e)
        {
            DisableTextEffects();

            var myEffect = new TextEffect
            {
                PositionStart = 0,
                PositionCount = 999
            };
            var myRotateTransform = new RotateTransform(45);
            myEffect.Transform = myRotateTransform;

            EnableTextEffects(fd1, myEffect);
            tb2.Text = "The RotateTransform applied rotated the text by 45 degrees.";
        }

        private void DisableTextEffects()
        {
            if (_textEffectTargets != null)
            {
                foreach (var target in _textEffectTargets)
                    target.Disable();
            }
        }

        private void EnableTextEffects(FlowDocument fd, TextEffect effect)
        {
            _textEffectTargets = TextEffectResolver.Resolve(fd.ContentStart, fd.ContentEnd, effect);
            foreach (var target in _textEffectTargets)
                target.Enable();
        }
    }
}

<|start_filename|>Windows/ShowWindowWithoutActivation/ChildWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace ShowWindowWithoutActivation
{
    /// <summary>
    ///     Interaction logic for ChildWindow.xaml
    /// </summary>
    public partial class ChildWindow : Window
    {
        public ChildWindow()
        {
            InitializeComponent();
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            activationStatusTextBlock.Text = "Activated";
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            activationStatusTextBlock.Text = "Deactivated";
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/baseencoder.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Declaration of BaseEncoder
//----------------------------------------------------------------------------------------
#include "precomp.hpp"

//----------------------------------------------------------------------------------------
// FRAME ENCODE
//----------------------------------------------------------------------------------------

BaseFrameEncode::BaseFrameEncode(IWICImagingFactory *pIFactory, IStream *pIStream, UINT num)
    : factory(pIFactory)
    , stream(pIStream)
    , frameNumber(num)
    , destSource(NULL)
    , destWidth(0), destHeight(0)
    , destDpiX(0), destDpiY(0)
    , destPixelFormat(GUID_WICPixelFormatUndefined)    
    , destPalette(NULL)
    , destThumbnail(NULL)
    , destPreview(NULL)
{
    if (NULL != factory)
    {
        factory->AddRef();
    }
    if (NULL != stream)
    {
        stream->AddRef();
    }
}

BaseFrameEncode::~BaseFrameEncode()
{
    ReleaseMembers();
}


//IUnknown Interface
STDMETHODIMP_(ULONG) BaseFrameEncode::AddRef()
    {
        return unknownImpl.AddRef();
    }
STDMETHODIMP_(ULONG) BaseFrameEncode::Release()
    {
        ULONG result = unknownImpl.Release();
        if (0 == result)
        {
            delete this;
        }
        return result;
    }
STDMETHODIMP BaseFrameEncode::QueryInterface(REFIID iid, void **ppvObject)
{
    HRESULT result = E_INVALIDARG;

    if (ppvObject)
    {
        if (iid == IID_IUnknown)
        {
            *ppvObject = static_cast<IUnknown*>(this);
            AddRef();

            result = S_OK;
        }
        else if (iid == IID_IWICBitmapFrameEncode)
        {
            *ppvObject = static_cast<IWICBitmapFrameEncode*>(this);
            AddRef();

            result = S_OK;
        }
        else
        {
            result = E_NOINTERFACE;
        }
    }

    return result;
}


// IWICBitmapFrameEncode
void BaseFrameEncode::ReleaseMembers()
{
    if (NULL != factory)
    {
        factory->Release();
    }
    if (NULL != stream)
    {
        stream->Release();
    }
    if (NULL != destSource)
    {
        destSource->Release();
    }
    for (size_t i = 0; i < colorContexts.size(); i++)
    {
        if (NULL != colorContexts[i])
        {
            colorContexts[i]->Release();
        }
    }
    if (NULL != destPalette)
    {
        destPalette->Release();
    }
    if (NULL != destThumbnail)
    {
        destThumbnail->Release();
    }
    if (NULL != destPreview)
    {
        destPreview->Release();
    }
}
STDMETHODIMP BaseFrameEncode::Initialize(IPropertyBag2 *pIEncoderOptions)
{
    return S_OK;
}

STDMETHODIMP BaseFrameEncode::SetSize(UINT width, UINT height)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        destWidth = width;
        destHeight = height;
    }

    return result;
}

STDMETHODIMP BaseFrameEncode::SetResolution(double dpiX, double dpiY)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        destDpiX = dpiX;
        destDpiY = dpiY;
    }

    return result;
}

STDMETHODIMP BaseFrameEncode::SetPixelFormat(WICPixelFormatGUID *pPixelFormat)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        if (NULL == pPixelFormat)
        {
            result = E_INVALIDARG;
        }

        if (SUCCEEDED(result))
        {
            destPixelFormat = *pPixelFormat;
        }
    }

    return result;
}

STDMETHODIMP BaseFrameEncode::SetColorContexts(UINT cCount, IWICColorContext **ppIColorContext)
{
    HRESULT result = S_OK;
    if (stream)
    {
        if (ppIColorContext != NULL)
        {
            int i; 
            for (i = 0; i < (UINT)colorContexts.size(); i++)
            {
                colorContexts[i]->Release();
            }  
            colorContexts.clear();
            for (i = 0; i < cCount; i++)
            {
                colorContexts.push_back(ppIColorContext[i]);
                ppIColorContext[i]->AddRef();
            }
        }
        else
        {
            result = E_INVALIDARG;
        }
    }
    else
    {
        result = E_INVALIDARG;
    }
    return result;
}

STDMETHODIMP BaseFrameEncode::SetPalette(IWICPalette *pIPalette)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        if (NULL != destPalette)
        {
            destPalette->Release();
        }

        destPalette = pIPalette;

        if (NULL != pIPalette)
        {
            pIPalette->AddRef();
        }
    }

    return result;
}

STDMETHODIMP BaseFrameEncode::SetThumbnail(IWICBitmapSource *pIThumbnail)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        if (NULL != destThumbnail)
        {
            destThumbnail->Release();
        }

        destThumbnail = pIThumbnail;

        if (NULL != pIThumbnail)
        {
            pIThumbnail->AddRef();
        }
    }

    return result;
}


STDMETHODIMP BaseFrameEncode::WritePixels(UINT lineCount, UINT cbStride, UINT cbBufferSize, BYTE *pbPixels)
{
    HRESULT result = E_UNEXPECTED;

    if (stream && (destWidth > 0) && (destHeight > 0) &&
        (destPixelFormat != GUID_WICPixelFormatUndefined))
    {
        result = S_OK;

        if (NULL != destSource)
        {
            destSource->Release();
            destSource = NULL;
        }

        IWICBitmap *bitmap = NULL;

        result = factory->CreateBitmapFromMemory(destWidth, destHeight,
            destPixelFormat, cbStride, cbBufferSize, pbPixels, &bitmap);

        if (SUCCEEDED(result))
        {
            destSource = bitmap;
        }
    }

    return result;
}

STDMETHODIMP BaseFrameEncode::WriteSource(IWICBitmapSource *pIWICBitmapSource, WICRect *prc)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        if (NULL != destSource)
        {
            destSource->Release();
        }

        destSource = pIWICBitmapSource;

        if (NULL != prc)
        {
            IWICBitmapClipper *clipper = NULL;

            result = factory->CreateBitmapClipper(&clipper);

            if (SUCCEEDED(result))
            {
                result = clipper->Initialize(pIWICBitmapSource, prc);

                if (FAILED(result))
                {
                    clipper->Release();
                }
            }

            if (SUCCEEDED(result))
            {
                destSource = clipper;
            }
        }
        else
        {
            if (NULL != pIWICBitmapSource)
            {
                pIWICBitmapSource->AddRef();
            }
        }
    }

    return result;
}



STDMETHODIMP BaseFrameEncode::Commit()
{
    HRESULT result = S_OK;
    
    IWICBitmapScaler *scaler = NULL;
    IWICFormatConverter *formatConverter = NULL;

    result = S_OK;

    // Create a scaler to match the requested width and height
    if (SUCCEEDED(result))
        {
        result = factory->CreateBitmapScaler(&scaler);
    }

    if (SUCCEEDED(result))
    {
        result = scaler->Initialize(destSource, destWidth, destHeight, WICBitmapInterpolationModeFant);
    }

    // Create a format converter to output into the proper format
    if (SUCCEEDED(result))
    {
        result = factory->CreateFormatConverter(&formatConverter);
    }
    if (SUCCEEDED(result))
    {
        result = formatConverter->Initialize(scaler, destPixelFormat, WICBitmapDitherTypeErrorDiffusion,
            destPalette, 50.0, WICBitmapPaletteTypeCustom);
    }

    // Cleanup
    if (formatConverter)
    {
        destSource->Release();
        destSource = formatConverter;
    }    
    return result;
}

STDMETHODIMP BaseFrameEncode::GetMetadataQueryWriter(IWICMetadataQueryWriter **ppIMetadataQueryWriter)
{
    return E_NOTIMPL;
}

//----------------------------------------------------------------------------------------
// ENCODER
//----------------------------------------------------------------------------------------

BaseEncoder::BaseEncoder(GUID Me, GUID Container)
    : factory(NULL)
    , stream(NULL)
    , destPalette(NULL)    
    , destThumbnail(NULL)
    , destPreview(NULL)
{
    CLSID_This = Me;
    CLSID_Container = Container;
}

BaseEncoder::~BaseEncoder()
{
    ReleaseMembers();
}


//IUnknown Interface
STDMETHODIMP_(ULONG) BaseEncoder::AddRef()
    {
        return unknownImpl.AddRef();
    }

STDMETHODIMP_(ULONG) BaseEncoder::Release()
    {
        ULONG result = unknownImpl.Release();
        if (0 == result)
        {
            delete this;
        }
        return result;
    }
STDMETHODIMP BaseEncoder::QueryInterface(REFIID iid, void **ppvObject)
{
    HRESULT result = E_INVALIDARG;

    if (ppvObject)
    {
        if (iid == IID_IUnknown)
        {
            *ppvObject = static_cast<IUnknown*>(this);
            AddRef();

            result = S_OK;
        }
        else if (iid == IID_IWICBitmapEncoder)
        {
            *ppvObject = static_cast<IWICBitmapEncoder*>(this);
            AddRef();

            result = S_OK;
        }
        else
        {
            result = E_NOINTERFACE;
        }
    }

    return result;
}

// IWICBitmapEncoder Interface
HRESULT BaseEncoder::VerifyFactory()
{
    if (NULL == factory)
    {
        return CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*) &factory);
    }
    else
    {
        return S_OK;
    }
}


void BaseEncoder::ReleaseMembers()
{
    if (factory)
    {
        factory->Release();
    }
    if (destPalette)
    {
        destPalette->Release();
    }
    for (size_t i = 0; i < colorContexts.size(); i++)
    {
        if (NULL != colorContexts[i])
        {
            colorContexts[i]->Release();
        }
    }
    if (destThumbnail)
    {
        destThumbnail->Release();
    }
    if (destPreview)
    {
        destPreview->Release();
    }
    for (size_t i = 0; i < frames.size(); ++i)
    {
        frames[i]->Release();
    }
}
STDMETHODIMP BaseEncoder::GetContainerFormat(GUID *pguidContainerFormat)
{
    HRESULT result = E_INVALIDARG;

    if (NULL != pguidContainerFormat)
    {
        result = S_OK;

        *pguidContainerFormat = CLSID_Container;
    }

    return result;
}

STDMETHODIMP BaseEncoder::GetEncoderInfo(IWICBitmapEncoderInfo **ppIEncoderInfo)
{
    HRESULT result = S_OK;

    IWICComponentInfo *compInfo = NULL;

    if (SUCCEEDED(result))
    {
        result = VerifyFactory();
    }

    if (SUCCEEDED(result))
    {
        result = factory->CreateComponentInfo(CLSID_This, &compInfo);
    }

    if (SUCCEEDED(result))
    {
        result = compInfo->QueryInterface(IID_IWICBitmapEncoderInfo, (void**)ppIEncoderInfo);
    }

    if (compInfo)
    {
        compInfo->Release();
    }

    return result;
}

STDMETHODIMP BaseEncoder::SetColorContexts(UINT cCount, IWICColorContext **ppIColorContext)
{
    HRESULT result = S_OK;
    if (stream)
    {
        if (ppIColorContext != NULL)
        {
            int i; 
            for (i = 0; i < (UINT)colorContexts.size(); i++)
            {
                colorContexts[i]->Release();
            }  
            colorContexts.clear();
            for (i = 0; i < cCount; i++)
            {
                colorContexts.push_back(ppIColorContext[i]);
                ppIColorContext[i]->AddRef();
            }
        }
        else
        {
            result = E_INVALIDARG;
        }
    }
    else
    {
        result = E_INVALIDARG;
    }
    return result;
}

STDMETHODIMP BaseEncoder::SetPalette(IWICPalette *pIPalette)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        if (NULL != destPalette)
        {
            destPalette->Release();
        }

        destPalette = pIPalette;

        if (NULL != pIPalette)
        {
            pIPalette->AddRef();
        }
    }

    return result;
}

STDMETHODIMP BaseEncoder::SetThumbnail(IWICBitmapSource *pIThumbnail)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        if (NULL != destThumbnail)
        {
            destThumbnail->Release();
        }

        destThumbnail = pIThumbnail;

        if (NULL != pIThumbnail)
        {
            pIThumbnail->AddRef();
        }
    }

    return result;
}

STDMETHODIMP BaseEncoder::SetPreview(IWICBitmapSource *pIPreview)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        result = S_OK;

        if (NULL != destPreview)
        {
            destPreview->Release();
        }

        destPreview = pIPreview;

        if (NULL != pIPreview)
        {
            pIPreview->AddRef();
        }
    }

    return result;
}


STDMETHODIMP BaseEncoder::CreateNewFrame(IWICBitmapFrameEncode **ppIFrameEncode, IPropertyBag2 **ppIEncoderOptions)
{
    HRESULT result = E_UNEXPECTED;

    if (stream)
    {
        BaseFrameEncode *frameEncode = NULL;

        result = S_OK;

        if (NULL == ppIFrameEncode)
        {
            result = E_INVALIDARG;
        }
        if (SUCCEEDED(result))
        {
            result = VerifyFactory();
        }
        if (SUCCEEDED(result))
        {
            frameEncode = CreateNewEncoderFrame(factory, stream, frames.size());

            if (NULL == frameEncode)
            {
                result = E_OUTOFMEMORY;
            }
        }
        if (SUCCEEDED(result))
        {
            AddEncoderFrame(frameEncode);
            result = frameEncode->QueryInterface(IID_IWICBitmapFrameEncode, (void**)ppIFrameEncode);
        }
        if (ppIEncoderOptions != NULL)
        {
            *ppIEncoderOptions = NULL;
        }        
    }
    return result;
}

void BaseEncoder::AddEncoderFrame(BaseFrameEncode* frame)
{
     frames.push_back(frame);
     frames.back()->AddRef();
}


<|start_filename|>Elements/WidthProperties/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace WidthProperties
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ChangeWidth(object sender, SelectionChangedEventArgs args)
        {
            var li = ((sender as ListBox).SelectedItem as ListBoxItem);
            var sz1 = double.Parse(li.Content.ToString());
            rect1.Width = sz1;
            rect1.UpdateLayout();
            txt1.Text = "ActualWidth is set to " + rect1.ActualWidth;
            txt2.Text = "Width is set to " + rect1.Width;
            txt3.Text = "MinWidth is set to " + rect1.MinWidth;
            txt4.Text = "MaxWidth is set to " + rect1.MaxWidth;
        }

        private void ChangeMinWidth(object sender, SelectionChangedEventArgs args)
        {
            var li = ((sender as ListBox).SelectedItem as ListBoxItem);
            var sz1 = double.Parse(li.Content.ToString());
            rect1.MinWidth = sz1;
            rect1.UpdateLayout();
            txt1.Text = "ActualWidth is set to " + rect1.ActualWidth;
            txt2.Text = "Width is set to " + rect1.Width;
            txt3.Text = "MinWidth is set to " + rect1.MinWidth;
            txt4.Text = "MaxWidth is set to " + rect1.MaxWidth;
        }

        private void ChangeMaxWidth(object sender, SelectionChangedEventArgs args)
        {
            var li = ((sender as ListBox).SelectedItem as ListBoxItem);
            var sz1 = double.Parse(li.Content.ToString());
            rect1.MaxWidth = sz1;
            rect1.UpdateLayout();
            txt1.Text = "ActualWidth is set to " + rect1.ActualWidth;
            txt2.Text = "Width is set to " + rect1.Width;
            txt3.Text = "MinWidth is set to " + rect1.MinWidth;
            txt4.Text = "MaxWidth is set to " + rect1.MaxWidth;
        }

        private void ClipRect(object sender, RoutedEventArgs args)
        {
            myCanvas.ClipToBounds = true;
            txt5.Text = "Canvas.ClipToBounds is set to " + myCanvas.ClipToBounds;
        }

        private void UnclipRect(object sender, RoutedEventArgs args)
        {
            myCanvas.ClipToBounds = false;
            txt5.Text = "Canvas.ClipToBounds is set to " + myCanvas.ClipToBounds;
        }
    }
}

<|start_filename|>Clipboard/ClipboardSpy/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace ClipboardSpy
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private IDataObject _dataObject;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void WindowLoaded(object sender, RoutedEventArgs args)
        {
            CheckStatus(null, null);
        }

        private void GetClipboard(object sender, RoutedEventArgs args)
        {
            _dataObject = Clipboard.GetDataObject();
            CheckCurrentDataObject();
        }

        private void CheckStatus(object sender, RoutedEventArgs args)
        {
            cbContainsAudio.IsChecked = Clipboard.ContainsAudio();
            cbContainsFileDropList.IsChecked = Clipboard.ContainsFileDropList();
            cbContainsImage.IsChecked = Clipboard.ContainsImage();
            cbContainsText.IsChecked = Clipboard.ContainsText();
        }

        private void ClearClipboard(object sender, RoutedEventArgs args)
        {
            Clipboard.Clear();
            CheckStatus(null, null);
            GetClipboard(null, null);
        }

        private void CheckCurrentDataObject()
        {
            CheckStatus(null, null);

            tbInfo.Clear();

            if (_dataObject == null)
            {
                tbInfo.Text = "DataObject is null.";
            }
            else
            {
                tbInfo.AppendText("Clipboard DataObject Type: ");
                tbInfo.AppendText(_dataObject.GetType().ToString());

                tbInfo.AppendText("\n\n****************************************************\n\n");

                var formats = _dataObject.GetFormats();

                tbInfo.AppendText(
                    "The following data formats are present in the data object obtained from the clipboard:\n");

                if (formats.Length > 0)
                {
                    foreach (var format in formats)
                    {
                        if (_dataObject.GetDataPresent(format, false))
                            tbInfo.AppendText("\t- " + format + " (native)\n");
                        else tbInfo.AppendText("\t- " + format + " (autoconvertable)\n");
                    }
                }
                else tbInfo.AppendText("\t- no data formats are present\n");

                foreach (var format in formats)
                {
                    tbInfo.AppendText("\n\n****************************************************\n");
                    tbInfo.AppendText(format + " data:\n");
                    tbInfo.AppendText("****************************************************\n\n");
                    tbInfo.AppendText(_dataObject.GetData(format, true).ToString());
                }
            }
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/NegateExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     An expression which holds onto and negates a single child expression.
    ///     All of its functions call into the child functions and return the
    ///     negation.
    /// </summary>
    public sealed class NegateExpression : UnaryExpression
    {
        public NegateExpression(IExpression child) : base(child)
        {
        }

        protected override double Operate(double d) => -d;

        public override IExpression Differentiate(string byVar) => new NegateExpression(child.Differentiate(byVar));

        public override IExpression Simplify()
        {
            var newChild = child.Simplify();
            var childConst = newChild as ConstantExpression;

            if (childConst != null)
            {
                // child is constant;  just evaluate it;
                return new ConstantExpression(-childConst.Value);
            }
            return new NegateExpression(newChild);
        }

        public override string ToString() => "(-" + child.ToString() + ")";
    }
}

<|start_filename|>Documents/Annotations/AnnotationsStyling/StyleMetaData.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace AnnotationsStyling
{
    /// <summary>
    ///     Provides a simple wrapper that associates a
    ///     Style with its ResourceDictionary key.
    /// </summary>
    public class StyleMetaData : DependencyObject
    {
        public static DependencyProperty KeyProperty =
            DependencyProperty.Register("Key", typeof (string), typeof (StyleMetaData));

        public Style Value;

        public StyleMetaData(string key, Style value)
        {
            Key = key;
            Value = value;
        }

        public string Key
        {
            get { return (string) GetValue(KeyProperty); }
            set { SetValue(KeyProperty, value); }
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/NullXamlWriter.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Xaml;

namespace BamlTools
{
    public class NullWriter : XamlWriter
    {
        public NullWriter(XamlSchemaContext xamlSchemaContext)
        {
            this._xamlSchemaContext = xamlSchemaContext;
        }

        public override void WriteStartObject(XamlType type)
        {
        }

        public override void WriteGetObject()
        {
        }

        public override void WriteEndObject()
        {
        }

        public override void WriteStartMember(XamlMember property)
        {
        }

        public override void WriteEndMember()
        {
        }

        public override void WriteValue(object value)
        {
        }

        public override void WriteNamespace(NamespaceDeclaration namespaceDeclaration)
        {
        }

        private XamlSchemaContext _xamlSchemaContext;
        public override XamlSchemaContext SchemaContext
        {
            get
            {
                return this._xamlSchemaContext;
            }
        }
    }
}


<|start_filename|>Elements/SettingMargins/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace SettingMargins
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            // Get the current value of the property.
            var marginThickness = btn1.Margin;
            // If the current leftlength value of margin is set to 10 then change it to a new value.
            // Otherwise change it back to 10.
            btn1.Margin = marginThickness.Left == 10 ? new Thickness(60) : new Thickness(10);
        }
    }
}

<|start_filename|>Application Management/CodeOnlyWindowsApplication/App.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace CodeOnlyWindowsApplication
{
    /// <summary>
    ///     App derives from Application to inherit application services,
    ///     and because developers typically need to influence its behavior
    ///     such as handling events or overriding members. The most common
    ///     reason is to configure the default UI resource to load, which
    ///     App does by overriding Startup.
    ///     NOTE: Since App is code-only (no markup) there is no need to
    ///     call the InitializeComponent method eg:
    ///     public partial class App : Application {
    ///     public App() {
    ///     this.InitializeComponent();
    ///     }
    ///     }
    ///     InitializeComponent is a method that is generated by the compiler
    ///     when markup  exists to apply the App XAML to the actual App instance,
    ///     eg to register event handlers. If XAML were used, this class
    ///     would also need to be a partial class, to merge with the
    ///     partial class definition that implements the InitializeComponent,
    ///     method that's generated by the compiler.
    /// </summary>
    public class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Show main application window.
            // NOTE: this window is automatically set as
            //       App.Current.MainWindow and App.Current.Windows[0]
            var window = new MainWindow();
            window.Show();
        }
    }
}

<|start_filename|>Data Binding/SimpleBinding/Person.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;

namespace SimpleBinding
{
    // This class implements INotifyPropertyChanged
    // to support one-way and two-way bindings
    // (such that the UI element updates when the source
    // has been changed dynamically)
    public class Person : INotifyPropertyChanged
    {
        private string _name;

        public Person()
        {
        }

        public Person(string value)
        {
            _name = value;
        }

        public string PersonName
        {
            get { return _name; }
            set
            {
                _name = value;
                // Call OnPropertyChanged whenever the property is updated
                OnPropertyChanged("PersonName");
            }
        }

        // Declare the event
        public event PropertyChangedEventHandler PropertyChanged;
        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string name)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}

<|start_filename|>Data Binding/Colors/ColorItemList.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;
using System.Reflection;
using System.Windows.Media;

namespace Colors
{
    public class ColorItemList : ObservableCollection<ColorItem>
    {
        public ColorItemList()
        {
            var type = typeof (Brushes);
            foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Static))
            {
                if (propertyInfo.PropertyType == typeof (SolidColorBrush))
                    Add(new ColorItem(propertyInfo.Name, (SolidColorBrush) propertyInfo.GetValue(null, null)));
            }
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/Token.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    //--------------------------------------------------------------

    public struct Token
    {
        public readonly TokenType Type;
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public readonly string Value;
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public Token(string value, TokenType type)
        {
            Value = value;
            Type = type;
        }
    }
}

<|start_filename|>Sample Applications/ParticlesDemo/Particle.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Media.Media3D;

namespace ParticlesDemo
{
    public class Particle
    {
        public double Decay;
        public double Life;
        public Point3D Position;
        public double Size;
        public double StartLife;
        public double StartSize;
        public Vector3D Velocity;
    }
}

<|start_filename|>Graphics/AITCodec/cpp/utility.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------
//  Description: Declaration of Utility/Helper functions
//----------------------------------------------------------------------------------------
#pragma once

//----------------------------------------------------------------------------------------
// MISC UTILITY FUNCTIONS
//----------------------------------------------------------------------------------------
UINT GetScanlineStride(UINT width, REFWICPixelFormatGUID pixelFormat);

//----------------------------------------------------------------------------------------
// STREAM UTILITY FUNCTIONS
//----------------------------------------------------------------------------------------
template< typename T >
static HRESULT InputValue(IStream *stream, T &val)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    ULONG numRead = 0;

    if (SUCCEEDED(result))
    {
        result = stream->Read(&val, sizeof(T), &numRead);
    }

    if (SUCCEEDED(result))
    {
        result = (sizeof(T) == numRead) ? S_OK : E_UNEXPECTED;
    }

    return result;
}

template< typename T >
static HRESULT InputValues(IStream *stream, T ptr, UINT count)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    ULONG numRead = 0;
    ULONG numToRead = sizeof(*ptr) * count;

    if (SUCCEEDED(result))
    {
        result = stream->Read(ptr, numToRead, &numRead);
    }

    if (SUCCEEDED(result))
    {
        result = (numToRead == numRead) ? S_OK : E_UNEXPECTED;
    }

    return result;
}

template< typename T >
static HRESULT OutputValue(IStream *stream, T val)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    ULONG numWritten = 0;

    if (SUCCEEDED(result))
    {
        result = stream->Write(&val, sizeof(T), &numWritten);
    }

    if (SUCCEEDED(result))
    {
        result = (sizeof(T) == numWritten) ? S_OK : E_UNEXPECTED;
    }

    return result;
}

template< typename T >
static HRESULT OutputValues(IStream *stream, T ptr, UINT count)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    ULONG numWritten = 0;
    ULONG numToWritten = sizeof(*ptr) * count;

    if (SUCCEEDED(result))
    {
        result = stream->Write(ptr, numToWritten, &numWritten);
    }

    if (SUCCEEDED(result))
    {
        result = (numToWritten == numWritten) ? S_OK : E_UNEXPECTED;
    }

    return result;
}


<|start_filename|>Accessibility/InvokePattern/Target/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace Target
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            var targetButton = sender as Button;
            MessageBox.Show(targetButton?.Content + " invoked.");
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/VariableExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Expression based on a single variable.
    ///     Variables must be set before they can be evaluated
    /// </summary>
    public sealed class VariableExpression : IExpression
    {
        private static readonly SortedList Environment;
        private readonly string _identifier;

        static VariableExpression()
        {
            Environment = new SortedList {{"pi", Math.PI}, {"e", Math.E}};
        }

        public VariableExpression(string identifier)
        {
            _identifier = identifier.ToLowerInvariant();
        }

        public bool HasValue => Environment.ContainsKey(_identifier.ToLowerInvariant());

        public double Value
        {
            get
            {
                if (HasValue)
                {
                    return (double) Environment[_identifier];
                }
                throw new UndefinedVariableException(_identifier + " is not defined");
            }
        }

        /// <summary>
        ///     Return the value this variable represents
        /// </summary>
        public double Evaluate() => Value;

        /// <summary>
        ///     Differentiate the Variable by input variable.
        /// </summary>
        public IExpression Differentiate(string byVar)
        {
            if (byVar == _identifier)
            {
                //      f(x) = x;
                // d( f(x) ) = 1 * d( x );
                //    d( x ) = 1;
                //     f'(x) = 1;
                return new ConstantExpression(1);
            }
            //      f(x) = c;
            // d( f(x) ) = c * d( c );
            //    d( c ) = 0;
            //     f'(x) = 0;
            return new ConstantExpression(0);
        }

        public IExpression Simplify()
        {
            if (_identifier == "t" || _identifier == "u" || _identifier == "v" || _identifier == "x" ||
                _identifier == "y")
            {
                // special iteration variables
                return new VariableExpression(_identifier);
            }
            if (HasValue)
            {
                return new ConstantExpression(Value);
            }
            return new VariableExpression(_identifier);
        }

        string IExpression.ToString() => _identifier;

        public static void Define(string variableName, double value)
        {
            variableName = variableName.ToLowerInvariant();
            if (Environment.ContainsKey(variableName))
            {
                Environment[variableName] = value;
            }
            else
            {
                Environment.Add(variableName, value);
            }
        }

        public static void Undefine(string variableName)
        {
            variableName = variableName.ToLowerInvariant();
            if (Environment.ContainsKey(variableName))
            {
                Environment.Remove(variableName);
            }
        }
    }
}

<|start_filename|>Data Binding/DataTemplatingIntro/TaskType.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DataTemplatingIntro
{
    public enum TaskType
    {
        Home,
        Work
    }
}

<|start_filename|>Application Management/SkinnedApplication/App.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace SkinnedApplication
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void App_Startup(object sender, StartupEventArgs e)
        {
            Properties["Blue"] = (ResourceDictionary) LoadComponent(new Uri("BlueSkin.xaml", UriKind.Relative));
            Properties["Yellow"] = (ResourceDictionary) LoadComponent(new Uri("YellowSkin.xaml", UriKind.Relative));

            // Note: you can also use the following syntax:
            //   Skins["Yellow"] = new YellowSkin()
            // But only as long as you implement the ResourceDictionary using markup and code-behind,
            // use the x:Class attribute in markup, and call InitializeComponent() from code-behind, eg:
            //
            //   <!-- Markup -->
            //   <ResourceDictionary
            //     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            //     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            //     xmlns:local="clr-namespace:SDKSample" 
            //     x:Class="SDKSample.YellowSkin">
            //        ...
            //   </ResourceDictionary>
            //
            //   // Code-behind
            //   public partial class YellowSkin : ResourceDictionary
            //   {
            //     public YellowSkin() { InitializeComponent(); }
            //   }
        }
    }
}

<|start_filename|>Accessibility/SelectionPattern/SelectionPatternSample/TargetHandler.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Text;
using System.Windows.Automation;

namespace SelectionPatternSample
{
    /// --------------------------------------------------------------------
    /// <summary>
    ///     UI Automation worker class.
    /// </summary>
    /// --------------------------------------------------------------------
    internal class TargetHandler
    {
        private readonly MainWindow _clientApp;
        private readonly AutomationElement _targetApp;
        private StringBuilder _feedbackText;
        private AutomationElement _rootElement;
        private AutomationEventHandler _targetCloseListener;

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Constructor.
        /// </summary>
        /// <param name="client">The client application.</param>
        /// <param name="target">The target application.</param>
        /// <remarks>
        ///     Initializes components.
        /// </remarks>
        /// --------------------------------------------------------------------
        internal TargetHandler(MainWindow client, AutomationElement target)
        {
            // Initialize member variables.
            _clientApp = client;
            _targetApp = target;
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The collection of Selection controls in the target.
        /// </summary>
        /// --------------------------------------------------------------------
        internal AutomationElementCollection TargetControls { get; private set; }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Start the UI Automation worker.
        /// </summary>
        /// --------------------------------------------------------------------
        internal void StartWork()
        {
            // Get UI Automation root element.
            _rootElement = AutomationElement.RootElement;

            // Position the target relative to the client.
            var clientLocationTop = _clientApp.Top;
            var clientLocationRight = _clientApp.Width + _clientApp.Left + 100;
            var transformPattern =
                _targetApp.GetCurrentPattern(TransformPattern.Pattern)
                    as TransformPattern;
            transformPattern?.Move(clientLocationRight, clientLocationTop);

            RegisterTargetClosedListener();

            // Get the target controls.
            CompileTargetControls();
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Register the target closed event listener.
        /// </summary>
        /// --------------------------------------------------------------------
        private void RegisterTargetClosedListener()
        {
            _targetCloseListener = OnTargetClosed;
            Automation.AddAutomationEventHandler(
                WindowPattern.WindowClosedEvent,
                _targetApp,
                TreeScope.Element,
                _targetCloseListener);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     The target closed event handler.
        /// </summary>
        /// <param name="src">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// <remarks>
        ///     Changes the state of client controls and removes event listeners.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void OnTargetClosed(object src, AutomationEventArgs e)
        {
            Feedback("Target has been closed. Please wait.");
            // Automation.RemoveAllEventHandlers is not used here since we don't
            // want to lose the window closed event listener for the target.
            RemoveTargetSelectionEventHandlers();

            Automation.RemoveAutomationEventHandler(
                WindowPattern.WindowClosedEvent, _targetApp, _targetCloseListener);
            _clientApp.SetClientControlState(MainWindow.ControlState.UIAStopped);

            Feedback(null);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Finds the selection and selection item controls of interest
        ///     and initializes necessary event listeners.
        /// </summary>
        /// <remarks>
        ///     Handles the special case of two Selection controls being returned
        ///     for a ComboBox control.
        /// </remarks>
        /// --------------------------------------------------------------------
        private void CompileTargetControls()
        {
            var condition =
                new PropertyCondition(
                    AutomationElement.IsSelectionPatternAvailableProperty, true);
            // A ComboBox is an aggregate control containing a ListBox 
            // as a child. 
            // Both the ComboBox and its child ListBox support the 
            // SelectionPattern control pattern but all related 
            // functionality is delegated to the child.
            // For the purposes of this sample we can filter the child 
            // as we do not need to display the redundant information.
            var andCondition = new AndCondition(
                condition,
                new NotCondition(
                    new PropertyCondition(
                        AutomationElement.ClassNameProperty, "ComboLBox")));
            TargetControls =
                _targetApp.FindAll(TreeScope.Children |
                                   TreeScope.Descendants, andCondition);
            _clientApp.EchoTargetControls();
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Gets the currently selected SelectionItem objects from target.
        /// </summary>
        /// <param name="selectionContainer">
        ///     The target Selection container.
        /// </param>
        /// --------------------------------------------------------------------
        internal AutomationElement[] GetTargetCurrentSelection(
            AutomationElement selectionContainer)
        {
            try
            {
                var selectionPattern =
                    selectionContainer.GetCurrentPattern(
                        SelectionPattern.Pattern) as SelectionPattern;
                return selectionPattern.Current.GetSelection();
            }
            catch (InvalidOperationException exc)
            {
                Feedback(exc.Message);
                return null;
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Subscribe to the selection events.
        /// </summary>
        /// <remarks>
        ///     The events are raised by the SelectionItem elements,
        ///     not the Selection container.
        /// </remarks>
        /// --------------------------------------------------------------------
        internal void SetTargetSelectionEventHandlers()
        {
            foreach (AutomationElement control in TargetControls)
            {
                var selectionHandler =
                    new AutomationEventHandler(TargetSelectionHandler);
                Automation.AddAutomationEventHandler(
                    SelectionItemPattern.ElementSelectedEvent,
                    control,
                    TreeScope.Element | TreeScope.Descendants,
                    selectionHandler);
                Automation.AddAutomationEventHandler(
                    SelectionItemPattern.ElementAddedToSelectionEvent,
                    control,
                    TreeScope.Element | TreeScope.Descendants,
                    selectionHandler);
                Automation.AddAutomationEventHandler(
                    SelectionItemPattern.ElementRemovedFromSelectionEvent,
                    control,
                    TreeScope.Element | TreeScope.Descendants,
                    selectionHandler);
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Unsubscribe from the selection events.
        /// </summary>
        /// <remarks>
        ///     The events are raised by the SelectionItem elements,
        ///     not the Selection container.
        /// </remarks>
        /// --------------------------------------------------------------------
        internal void RemoveTargetSelectionEventHandlers()
        {
            foreach (AutomationElement control in TargetControls)
            {
                var selectionHandler =
                    new AutomationEventHandler(TargetSelectionHandler);
                Automation.RemoveAutomationEventHandler(
                    SelectionItemPattern.ElementSelectedEvent,
                    control,
                    selectionHandler);
                Automation.RemoveAutomationEventHandler(
                    SelectionItemPattern.ElementAddedToSelectionEvent,
                    control,
                    selectionHandler);
                Automation.RemoveAutomationEventHandler(
                    SelectionItemPattern.ElementRemovedFromSelectionEvent,
                    control,
                    selectionHandler);
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Handles user input in the target.
        /// </summary>
        /// <param name="src">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        /// --------------------------------------------------------------------
        private void TargetSelectionHandler(
            object src, AutomationEventArgs e)
        {
            _feedbackText = new StringBuilder();

            // Get the name of the item, which is equivalent to its text.
            var sourceItem = src as AutomationElement;

            var selectionItemPattern =
                sourceItem.GetCurrentPattern(SelectionItemPattern.Pattern)
                    as SelectionItemPattern;

            AutomationElement sourceContainer;

            // Special case handling for composite controls.
            var treeWalker = new TreeWalker(new PropertyCondition(
                AutomationElement.IsSelectionPatternAvailableProperty,
                true));
            sourceContainer =
                (treeWalker.GetParent(
                    selectionItemPattern.Current.SelectionContainer) == null)
                    ? selectionItemPattern.Current.SelectionContainer
                    : treeWalker.GetParent(
                        selectionItemPattern.Current.SelectionContainer);

            switch (e.EventId.ProgrammaticName)
            {
                case
                    "SelectionItemPatternIdentifiers.ElementSelectedEvent":
                    _feedbackText.Append(sourceItem.Current.Name)
                        .Append(" of the ")
                        .Append(sourceContainer.Current.AutomationId)
                        .Append(" control was selected.");
                    break;
                case
                    "SelectionItemPatternIdentifiers.ElementAddedToSelectionEvent":
                    _feedbackText.Append(sourceItem.Current.Name)
                        .Append(" of the ")
                        .Append(sourceContainer.Current.AutomationId)
                        .Append(" control was added to the selection.");
                    break;
                case
                    "SelectionItemPatternIdentifiers.ElementRemovedFromSelectionEvent":
                    _feedbackText.Append(sourceItem.Current.Name)
                        .Append(" of the ")
                        .Append(sourceContainer.Current.AutomationId)
                        .Append(" control was removed from the selection.");
                    break;
            }
            Feedback(_feedbackText.ToString());

            for (var controlCounter = 0;
                controlCounter < TargetControls.Count;
                controlCounter++)
            {
                _clientApp.SetControlPropertiesText(controlCounter);
                _clientApp.EchoTargetControlSelections(
                    TargetControls[controlCounter],
                    controlCounter);
                _clientApp.EchoTargetControlProperties(
                    TargetControls[controlCounter],
                    controlCounter);
            }
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Gets the selection items from each target control.
        /// </summary>
        /// <param name="selectionContainer">
        ///     The target Selection container.
        /// </param>
        /// <returns>
        ///     Automation elements that satisfy the specified conditions.
        /// </returns>
        /// --------------------------------------------------------------------
        internal AutomationElementCollection
            GetSelectionItemsFromTarget(AutomationElement selectionContainer)
        {
            var condition =
                new PropertyCondition(
                    AutomationElement.IsSelectionItemPatternAvailableProperty,
                    true);
            return selectionContainer.FindAll(TreeScope.Children |
                                              TreeScope.Descendants, condition);
        }

        /// --------------------------------------------------------------------
        /// <summary>
        ///     Prints a line of text to the textbox.
        /// </summary>
        /// <param name="outputStr">The string to print.</param>
        /// --------------------------------------------------------------------
        private void Feedback(string outputStr)
        {
            _clientApp.Feedback(outputStr);
        }
    }
}

<|start_filename|>Animation/KeyFrameAnimation/KeyFramesIntroduction.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;

namespace KeyFrameAnimation
{
    public partial class KeyFramesIntroduction : Page
    {
        public void PageLoaded(object sender, RoutedEventArgs args)
        {
            myVisualBrush.Visual = myImage;
        }

        private void ExampleCanvasLayoutUpdated(object sender, EventArgs args)
        {
            myVisualBrush.Viewbox =
                new Rect(
                    Canvas.GetLeft(myRectangle),
                    Canvas.GetTop(myRectangle),
                    myRectangle.ActualWidth,
                    myRectangle.ActualHeight
                    );
        }
    }
}

<|start_filename|>Documents/Flow Content/FlowDocumentNewsClient/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace FlowDocumentNewsClient
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Application _app;

        public MainWindow()
        {
            InitializeComponent();
        }

        public void MenuExit(object sender, RoutedEventArgs args)
        {
            _app = Application.Current;
            _app.Shutdown();
        }

        public void PrintPage(object sender, RoutedEventArgs args)
        {
            var pDialog = new PrintDialog();
            pDialog.ShowDialog();
        }

        private void OnLoaded(object sender, EventArgs e)
        {
            todayDate.Text += DateTime.Now.ToString(CultureInfo.InvariantCulture);
        }

        private void Nav1(object sender, MouseButtonEventArgs e)
        {
            frame1.Source = new Uri("document.xaml", UriKind.Relative);
        }

        private void Nav2(object sender, MouseButtonEventArgs e)
        {
            frame1.Source = new Uri("document1.xaml", UriKind.Relative);
        }

        private void Nav3(object sender, MouseButtonEventArgs e)
        {
            frame1.Source = new Uri("document2.xaml", UriKind.Relative);
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlReflector/Window1.xaml.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BamlTools;
using Microsoft.Win32;
using System;
using System.Reflection;
using System.Windows;

namespace BamlReflector
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private readonly BamlReflectorContext _context;

        public Window1()
        {
            _context = new BamlReflectorContext();
            this.DataContext = _context;
            InitializeComponent();
        }

        private void OnOpen_Executed(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog
            {
                Filter = "WPF Assemblies(*.exe *.dll)|*.exe;*.dll",
                Multiselect = true
            };
            bool isFileChoosen = (bool)dlg.ShowDialog(this);
            Assembly assembly = null;
            String[] assemblyNames;

            if (isFileChoosen)
            {
                assemblyNames = dlg.FileNames;
                foreach (String name in assemblyNames)
                {
                    try
                    {
                        assembly = Assembly.LoadFrom(name);
                    }
                    catch (Exception ex)
                    {
                        Window window = new Window
                        {
                            Content = ex
                        };
                        window.ShowDialog();
                    }
                    if (assembly != null)
                    {
                        _context.ReferenceAssemblies.Add(new ReferenceAssembly_VM(assembly));
                    }
                }
            }
        }

        private void OnExit_Executed(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void Treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is BamlResource baml)
            {
                // Set the Assembly before the Baml resource
                // so that the BAML read has a current assembly.
                _context.LocalAssembly = baml.Assembly;
                _context.CurrentBamlResource = baml;
            }
            else if (e.NewValue is ApplicationResource appResource)
            {
                _context.LocalAssembly = appResource.Assembly;
                _context.CurrentBamlResource = null;
            }
            else if (e.NewValue is ReferenceAssembly_VM refAsm)
            {
                _context.LocalAssembly = refAsm.LoadedAssembly;
                _context.CurrentBamlResource = null;
            }
        }
    }
}


<|start_filename|>Sample Applications/DataBindingDemo/SpecialFeatures.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace DataBindingDemo
{
    public enum SpecialFeatures
    {
        None,
        Color,
        Highlight
    }
}

<|start_filename|>PerMonitorDPI/FormattedTextExample/MainWindow.xaml.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 FormattedTextExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {            
            DrawFormattedText(VisualTreeHelper.GetDpi(this));
        }

        protected override void OnDpiChanged(DpiScale oldDpiScaleInfo, DpiScale newDpiScaleInfo)
        {
            DrawFormattedText(newDpiScaleInfo);
        }

        private void DrawFormattedText(DpiScale dpiInfo)
        {
            FormattedText formattedText = new FormattedText(
                "FABLE",
                new System.Globalization.CultureInfo("en-US"),
                FlowDirection.LeftToRight,
                new Typeface(
                    new System.Windows.Media.FontFamily("Segoe UI"),
                    FontStyles.Normal,
                    FontWeights.Bold,
                    FontStretches.Normal),
                120,
                System.Windows.Media.Brushes.Red,
                dpiInfo.PixelsPerDip);

            // Build a geometry out of the text.
            Geometry geometry = new PathGeometry();
            geometry = formattedText.BuildGeometry(new System.Windows.Point(0, 0));

            // Adjust the geometry to fit the aspect ration of the video by scaling it.
            ScaleTransform myScaleTransform = new ScaleTransform();
            myScaleTransform.ScaleX = .85;
            myScaleTransform.ScaleY = 2.0;
            geometry.Transform = myScaleTransform;

            // Flatten the geometry and create a PathGeometry out of it.
            PathGeometry pathGeometry = new PathGeometry();
            pathGeometry = geometry.GetFlattenedPathGeometry();

            // Use the PathGeometry for the empty placeholder Path element in XAML.
            path.Data = pathGeometry;

            // Use the PathGeometry for the animated ball that follows the path of the text outline.
            matrixAnimation.PathGeometry = pathGeometry;
        }
    }
}


<|start_filename|>Sample Applications/DataBindingDemo/App.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;
using System.Windows;

namespace DataBindingDemo
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public User CurrentUser { get; set; }
        public ObservableCollection<AuctionItem> AuctionItems { get; set; } = new ObservableCollection<AuctionItem>();

        private void AppStartup(object sender, StartupEventArgs args)
        {
            LoadAuctionData();
        }

        private void LoadAuctionData()
        {
            CurrentUser = new User("John", 12, new DateTime(2003, 4, 20));

            #region Add Products to the auction

            var userMary = new User("Mary", 10, new DateTime(2000, 5, 2));
            var userAnna = new User("Anna", 5, new DateTime(2001, 9, 13));
            var userMike = new User("Mike", 13, new DateTime(1999, 11, 23));
            var userMark = new User("Mark", 15, new DateTime(2004, 6, 3));

            var camera = new AuctionItem("Digital camera - good condition", ProductCategory.Electronics, 300,
                new DateTime(2005, 8, 23), userAnna, SpecialFeatures.None);
            camera.AddBid(new Bid(310, userMike));
            camera.AddBid(new Bid(312, userMark));
            camera.AddBid(new Bid(314, userMike));
            camera.AddBid(new Bid(320, userMark));

            var snowBoard = new AuctionItem("Snowboard and bindings", ProductCategory.Sports, 120,
                new DateTime(2005, 7, 12),
                userMike, SpecialFeatures.Highlight);
            snowBoard.AddBid(new Bid(140, userAnna));
            snowBoard.AddBid(new Bid(142, userMary));
            snowBoard.AddBid(new Bid(150, userAnna));

            var insideCSharp = new AuctionItem("Inside C#, second edition", ProductCategory.Books, 10,
                new DateTime(2005, 5, 29),
                CurrentUser, SpecialFeatures.Color);
            insideCSharp.AddBid(new Bid(11, userMark));
            insideCSharp.AddBid(new Bid(13, userAnna));
            insideCSharp.AddBid(new Bid(14, userMary));
            insideCSharp.AddBid(new Bid(15, userAnna));

            var laptop = new AuctionItem("Laptop - only 1 year old", ProductCategory.Computers, 500,
                new DateTime(2005, 8, 15),
                userMark, SpecialFeatures.Highlight);
            laptop.AddBid(new Bid(510, CurrentUser));

            var setOfChairs = new AuctionItem("Set of 6 chairs", ProductCategory.Home, 120, new DateTime(2005, 2, 20),
                userMike,
                SpecialFeatures.Color);

            var myDvdCollection = new AuctionItem("My DVD Collection", ProductCategory.DvDs, 5, new DateTime(2005, 8, 3),
                userMary, SpecialFeatures.Highlight);
            myDvdCollection.AddBid(new Bid(6, userMike));
            myDvdCollection.AddBid(new Bid(8, CurrentUser));

            var tvDrama = new AuctionItem("TV Drama Series", ProductCategory.DvDs, 40, new DateTime(2005, 7, 28),
                userAnna,
                SpecialFeatures.None);
            tvDrama.AddBid(new Bid(42, userMike));
            tvDrama.AddBid(new Bid(45, userMark));
            tvDrama.AddBid(new Bid(50, userMike));
            tvDrama.AddBid(new Bid(51, CurrentUser));

            var squashRacket = new AuctionItem("Squash racket", ProductCategory.Sports, 60, new DateTime(2005, 4, 4),
                userMark,
                SpecialFeatures.Highlight);
            squashRacket.AddBid(new Bid(62, userMike));
            squashRacket.AddBid(new Bid(65, userAnna));

            AuctionItems.Add(camera);
            AuctionItems.Add(snowBoard);
            AuctionItems.Add(insideCSharp);
            AuctionItems.Add(laptop);
            AuctionItems.Add(setOfChairs);
            AuctionItems.Add(myDvdCollection);
            AuctionItems.Add(tvDrama);
            AuctionItems.Add(squashRacket);

            #endregion
        }
    }
}

<|start_filename|>Data Binding/CollectionBinding/People.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.ObjectModel;

namespace CollectionBinding
{
    public class People : ObservableCollection<Person>
    {
        public People()
        {
            Add(new Person("Michael", "Alexander", "Bellevue"));
            Add(new Person("Jeff", "Hay", "Redmond"));
            Add(new Person("Christina", "Lee", "Kirkland"));
            Add(new Person("Samantha", "Smith", "Seattle"));
        }
    }
}

<|start_filename|>Application Management/SingleInstanceDetection/SingleInstanceManager.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.VisualBasic.ApplicationServices;

namespace SingleInstanceDetection
{
    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        private SingleInstanceApplication _app;

        public SingleInstanceManager()
        {
            IsSingleInstance = true;
        }

        protected override bool OnStartup(StartupEventArgs e)
        {
            // First time app is launched
            _app = new SingleInstanceApplication();
            _app.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // Subsequent launches
            base.OnStartupNextInstance(eventArgs);
            _app.Activate();
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/ycbcrpixelformatconverter.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of YCbCrPixelFormatConverter
//----------------------------------------------------------------------------------------
#include "precomp.hpp"

// The YCbCr format GUID {9D14B98B-4427-41f0-A7AC-92CC96AE0BEB}
static const GUID GUID_TestPixelFormat24bppYCbCr = 
{ 0x9d14b98b, 0x4427, 0x41f0, { 0xa7, 0xac, 0x92, 0xcc, 0x96, 0xae, 0xb, 0xeb } };

static const GUID CLSID_YCbCrPixelFormatConverter = 
{ 0x49CC393E, 0xCE46, 0x11D9, { 0x8B, 0xDE, 0xF6, 0x6B, 0xAD, 0x1E, 0x3F, 0x3A}};



YCbCrPixelFormatConverter::YCbCrPixelFormatConverter()
: BasePixelFormatConverter()
{}

STDMETHODIMP YCbCrPixelFormatConverter::CanConvert( 
        /* [in] */ REFWICPixelFormatGUID srcPixelFormat,
        /* [in] */ REFWICPixelFormatGUID dstPixelFormat,
        /* [out] */ BOOL *pfCanConvert)
{
    HRESULT result = E_INVALIDARG;

    if (NULL != pfCanConvert)
    {
        result = S_OK;

        //In thuis case the canonical format would be GUID_WICPixelFormat32bppBGRA

        // I can convert from YCbCr to RGB and back only
        if ((GUID_WICPixelFormat32bppBGRA   == srcPixelFormat) &&
            (GUID_TestPixelFormat24bppYCbCr == dstPixelFormat))
        {
            *pfCanConvert = TRUE;
        }
        else if ((GUID_TestPixelFormat24bppYCbCr   == srcPixelFormat) &&
            (GUID_WICPixelFormat32bppBGRA == dstPixelFormat))
        {
            *pfCanConvert = TRUE;
        }
        else
        {
            *pfCanConvert = FALSE;
        }
    }
    return result;
}

STDMETHODIMP YCbCrPixelFormatConverter::CopyPixels( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels)
{
    HRESULT result = E_UNEXPECTED;

    if (NULL != bitmapSource)
    {
        //Do the actual conversion
        if (destPixelFormat == GUID_WICPixelFormat32bppBGRA)
        {
            //Convert back to canonical 32ARGB            
            result = ConvertYCbCrToRgb(prc, cbStride, cbPixelsSize, pbPixels);
        }
        else if (destPixelFormat == GUID_TestPixelFormat24bppYCbCr)
        {
            //Convert back to newly supported YCbCr
            result = ConvertRgbToYCbCr(prc, cbStride, cbPixelsSize, pbPixels);
        }
    }
    return result;
}

    BYTE Clamp(BYTE min, BYTE max, double value)
    {
        if (value > max)
            return max;
        if (value < min)
            return min;
        return (BYTE)value;
    }

    HRESULT YCbCrPixelFormatConverter::ConvertYCbCrToRgb( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels)
    {
        HRESULT result = S_OK;
        
        //Sanity check
        WICPixelFormatGUID srcPixelFormat;
        bitmapSource->GetPixelFormat(&srcPixelFormat);
        if (srcPixelFormat != GUID_TestPixelFormat24bppYCbCr)
        {
             result = E_UNEXPECTED;                  
        }  

        UINT width, height;

        if (prc == NULL)
        {
            if (SUCCEEDED(result))
            {
                result = bitmapSource->GetSize(&width, &height);
            }
        }else
        {
            width = prc->Width;
            height = prc->Height;
        }
        
        BYTE* tempPixels = NULL;
        if (SUCCEEDED(result))
        {
            //Get the YCbCr pixels
            tempPixels = new BYTE[height*width*3];
            result = bitmapSource->CopyPixels(prc, width*3, height*width*3, tempPixels);
        }
        
        //Loop on the data and do the conversion
        //We cannot do an inplace conversion here since the pixel formats have different
        //number of bytes
        if (SUCCEEDED(result))
        {
            BYTE *srcPos = NULL;
            BYTE *destPos = NULL;
            srcPos = tempPixels;
            destPos = pbPixels;
            for (int i = 0 ; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    BYTE R, G ,B;
                    BYTE Y, Cb, Cr;

                    Cr = *srcPos;
                    Cb = *(srcPos+1);
                    Y = *(srcPos+2);      

                    //Do the maths
                    R = Clamp(0, 255, 1.164*(Y - 16) + 1.596*(Cr - 128));
                    G = Clamp(0, 255, 1.164*(Y - 16) - 0.813*(Cr - 128) - 0.392*(Cb - 128));
                    B = Clamp(0, 255, 1.164*(Y - 16) + 2.017*(Cb - 128));

                    *destPos = B;
                    *(destPos+1) = G;
                    *(destPos+2) = R;                     
                    *(destPos+3) = 255;      
                       
                    //Advance to next pixel
                    srcPos += 3;
                    destPos += 4;
                }
                destPos += (cbStride - (width * 4));
            }
        }
        
        delete[] tempPixels;        
        return result;    
    }


    HRESULT YCbCrPixelFormatConverter::ConvertRgbToYCbCr( 
        /* [in] */ const WICRect *prc,
        /* [in] */ UINT cbStride,
        /* [in] */ UINT cbPixelsSize,
        /* [out] */ BYTE *pbPixels)
    {
        HRESULT result = S_OK;
        
        //Sanity check
        WICPixelFormatGUID srcPixelFormat;
        bitmapSource->GetPixelFormat(&srcPixelFormat);
        if (srcPixelFormat != GUID_WICPixelFormat32bppBGRA)
        {
             result = E_UNEXPECTED;
             return result;
        }

        IWICImagingFactory *codecFactory = NULL;
        IWICFormatConverter *formatConverter = NULL;    

        if (SUCCEEDED(result))
        {
            result = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*) &codecFactory);
        }

        if (SUCCEEDED(result))
        {             
            result = codecFactory->CreateFormatConverter(&formatConverter);        
        }
        
        if (SUCCEEDED(result))
        {
            //We will convert to 24RGB first, since it is easier to convert to YCbCr from there
            result = formatConverter->Initialize(bitmapSource,
                GUID_WICPixelFormat24bppBGR, WICBitmapDitherTypeSolid, NULL, 1.0, WICBitmapPaletteTypeFixedWebPalette);
        }

        if (SUCCEEDED(result))
        {
            result = formatConverter->CopyPixels(prc, cbStride, cbPixelsSize, pbPixels);
        }
        //Since the two formats have same number of bytes, we will do an inplace conversion
        UINT width, height;
        if (prc == NULL)
        {
            if (SUCCEEDED(result))
            {
                result = bitmapSource->GetSize(&width, &height);
            }
        }
        else
        {
            width = prc->Width;
            height = prc->Height;
        }

        if (SUCCEEDED(result))
        {
            //Loop on the data and do the conversion
            BYTE *curPos = NULL;            
            curPos = pbPixels;
            for (int i = 0 ; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                BYTE R, G ,B;
                BYTE Y, Cb, Cr;

                B = *curPos;
                G = *(curPos+1);
                R = *(curPos+2);      

                //Do the maths
                Y = Clamp(0, 255, (0.257*R) + (0.504*G) + (0.098*B) + 16);
                Cb = Clamp(0, 255, (-0.148*R) - (0.291*G) + (0.439*B) + 128);
                Cr = Clamp(0, 255, (0.439*R) - (0.368*G) - (0.071*B) + 128);

                *curPos = Cr;
                *(curPos+1) = Cb;
                *(curPos+2) = Y;      
                   
                //Advance to next pixel
                curPos += 3;
                }
                curPos += (cbStride - (width * 3)); //Fast forward remaining part of the stride
            }
        }
        if (formatConverter)
        {
            formatConverter->Release();
        }

        if (codecFactory)
        {
            codecFactory->Release();
        }
        return result;
       }  



<|start_filename|>Drag and Drop/DragDropTextOps/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace DragDropTextOps
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void TextSelectionToDataObject(object sender, RoutedEventArgs e)
        {
            // Create a new data object using one of the overloaded constructors.  This particular
            // overload accepts a string specifying the data format (provided by the DataFormats class),
            // and an Object (in this case a string) that represents the data to be stored in the data object.
            var dataObject = new DataObject(DataFormats.Text, sourceTextBox.SelectedText);

            dataObjectInfoTextBox.Clear();

            // Get and display the native data formats (filtering out auto-convertable data formats).
            dataObjectInfoTextBox.Text = "\nNative data formats present:\n";
            foreach (var format in dataObject.GetFormats(false /*autoconvert*/))
                dataObjectInfoTextBox.Text += format + "\n";

            // Display the data in the data object.
            dataObjectInfoTextBox.Text += "\nData contents:\n";
            dataObjectInfoTextBox.Text += dataObject.GetData(DataFormats.Text, false /*autoconvert*/).ToString();
        }
    }
}

<|start_filename|>Windows/ShowWindowWithoutActivation/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace ShowWindowWithoutActivation
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ShowWindowActivateButton_Click(object sender, RoutedEventArgs e)
        {
            var tw = new ChildWindow();
            // tw.ShowActivated = true; // true is the default value
            tw.Show();
        }

        private void ShowWindowNoActivateButton_Click(object sender, RoutedEventArgs e)
        {
            var tw = new ChildWindow {ShowActivated = false};
            tw.Show();
        }

        // This option doesn't make sense
        private void ShowDialogBoxActivateButton_Click(object sender, RoutedEventArgs e)
        {
            var tw = new ChildWindow();
            // tw.ShowActivated = true; // true is the default value
            tw.ShowDialog();
        }

        // This option doesn't make sense
        private void ShowDialogBoxNoActivateButton_Click(object sender, RoutedEventArgs e)
        {
            var tw = new ChildWindow {ShowActivated = false};
            tw.ShowDialog();
        }
    }
}

<|start_filename|>Animation/Per-FrameAnimation/ParticleEffects/ParticleEffectsTimeTracker.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace PerFrameAnimation
{
    //uielement
    //visual operations

    //animation effect stuff

    public class ParticleEffectsTimeTracker
    {
        #region Constructors

        public ParticleEffectsTimeTracker()
        {
            ElapsedTime = DateTime.Now;
        }

        #endregion

        #region Events

        public event EventHandler TimerFired;

        #endregion

        public double Update()
        {
            var currentTime = DateTime.Now;


            //get the difference in time
            var diffTime = currentTime - ElapsedTime;
            DeltaSeconds = diffTime.TotalSeconds;


            //does the user want a callback on regular intervals?
            if (TimerInterval > 0.0)
            {
                /*
                    //compute the intervals for this and previous update
                    int currInterval = (int)(currentTime / TimeSpan.FromSeconds(_timerInterval));
                    int prevInterval = (int)(_lastTime / TimeSpan.FromSeconds(_timerInterval));

                    //has the interval changed since last update?
                    if (currInterval != prevInterval)
                    {
                        //fire interval event
                        //note that this will only be called once per frame at most
                        // so if they interval is too small, you wont get 2+ fires per frame
                        TimerFired(this, null);
                    } */

                if (currentTime != ElapsedTime)
                {
                    TimerFired?.Invoke(this, null);
                }
            }


            //cycle old time
            ElapsedTime = currentTime;

            return DeltaSeconds;
        }

        #region Private Memebers

        #endregion

        #region Properties

        public double TimerInterval { get; set; } = -1;

        public DateTime ElapsedTime { get; private set; }

        public double DeltaSeconds { get; private set; }

        #endregion
    }
}

<|start_filename|>Animation/Per-FrameAnimation/ReusableFollow/ReusableFollowTracker.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Media.Animation;

namespace PerFrameAnimation
{
    //uielement
    //visual operations

    //animation effect stuff

    public class ReusableFollowTracker
    {
        #region Constructors

        public ReusableFollowTracker()
        {
            _timeline = new ParallelTimeline(null, Duration.Forever);
            _timeClock = _timeline.CreateClock();
            _timeClock.Controller?.Begin();
            _lastTime = TimeSpan.FromSeconds(0);
        }

        #endregion

        #region Events

        public event EventHandler TimerFired;

        #endregion

        public double Update()
        {
            var currentTime = _timeClock.CurrentTime;

            //we're working with nullables, so just to be safe we should check for values
            if (currentTime.HasValue && _lastTime.HasValue)
            {
                //get the difference in time
                var diffTime = currentTime.Value - _lastTime.Value;
                DeltaSeconds = diffTime.TotalSeconds;

                //does the user want a callback on regular intervals?
                if (TimerInterval > 0.0)
                {
                    //compute the intervals for this and previous update
                    var currInterval = (int) (currentTime.Value.TotalSeconds/TimerInterval);
                    var prevInterval = (int) (_lastTime.Value.TotalSeconds/TimerInterval);

                    //has the interval changed since last update?
                    if (currInterval != prevInterval)
                    {
                        //fire interval event
                        //note that this will only be called once per frame at most
                        // so if they interval is too small, you wont get 2+ fires per frame
                        TimerFired?.Invoke(this, null);
                    }
                }
            }

            //cycle old time
            _lastTime = currentTime;

            return DeltaSeconds;
        }

        #region Private Members

        private readonly Timeline _timeline;
        private readonly Clock _timeClock;
        private TimeSpan? _lastTime;

        #endregion

        #region Properties

        public double TimerInterval { get; set; } = -1;

        public TimeSpan ElapsedTime
        {
            get
            {
                if (_lastTime.HasValue)
                    return _lastTime.Value;
                return new TimeSpan(0);
            }
        }

        public double DeltaSeconds { get; private set; }

        #endregion
    }
}

<|start_filename|>Documents/Fixed Documents/DocumentMerge/RollupDocument.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Xps.Packaging;

namespace DocumentMerge
{
    public class RollUpDocument
    {
        private readonly List<RollUpFixedDocument> _documents;
        private FixedDocumentSequence _fixedDocumentSequence;

        public RollUpDocument()
        {
            _documents = new List<RollUpFixedDocument>();
        }

        public Uri Uri { get; set; }

        public int DocumentCount => _documents.Count;

        public FixedDocumentSequence FixedDocumentSequence
        {
            get
            {
                if (_fixedDocumentSequence == null)
                {
                    ReCreateFixedDocumentSequence();
                }
                return _fixedDocumentSequence;
            }
        }

        public int AddDocument()
        {
            _documents.Add(new RollUpFixedDocument());
            _fixedDocumentSequence = null;
            return DocumentCount - 1;
        }

        public int AddDocument(FixedDocument fixedDocument)
        {
            _documents.Add(new RollUpFixedDocument(fixedDocument));
            _fixedDocumentSequence = null;
            return DocumentCount - 1;
        }

        public int AddDocument(Uri source, Uri uri)
        {
            _documents.Add(new RollUpFixedDocument(source, uri));
            _fixedDocumentSequence = null;
            return DocumentCount - 1;
        }

        public void InsertDocument(int insertAfterDocIndex)
        {
            _documents.Insert(insertAfterDocIndex, new RollUpFixedDocument());
            _fixedDocumentSequence = null;
        }

        public void InsertDocument(int insertAfterDocIndex, FixedDocument fixedDocument)
        {
            _documents.Insert(insertAfterDocIndex, new RollUpFixedDocument(fixedDocument));
            _fixedDocumentSequence = null;
        }

        public void InsertDocument(int insertAfterDocIndex, Uri source, Uri uri)
        {
            _documents.Insert(insertAfterDocIndex, new RollUpFixedDocument(source, uri));
            _fixedDocumentSequence = null;
        }

        public void RemoveDocument(int docIndex)
        {
            _documents.RemoveAt(docIndex);
            _fixedDocumentSequence = null;
        }

        public void AddPage(int docIndex, FixedPage page)
        {
            var rollUpFixedDocument = _documents[docIndex];
            TestForExistingPages(rollUpFixedDocument);
            rollUpFixedDocument.Pages.Add(new RollUpFixedPage(page));
            _fixedDocumentSequence = null;
        }

        private void TestForExistingPages(RollUpFixedDocument rollUpFixedDocument)
        {
            if (rollUpFixedDocument.BaseUri != null)
            {
                rollUpFixedDocument.CreatePagesFromSource();
            }
            else if (rollUpFixedDocument.FixedDocument != null)
            {
                rollUpFixedDocument.CreatePagesFromFixedDocument();
            }
        }

        public void AddPage(int docIndex, Uri source, Uri uri)
        {
            var rollUpFixedDocument = _documents[docIndex];
            TestForExistingPages(rollUpFixedDocument);
            rollUpFixedDocument.Pages.Add(new RollUpFixedPage(source, uri));
            _fixedDocumentSequence = null;
        }

        public void InsertPage(int docIndex, int insertAfterPageIndex, FixedPage page)
        {
            var rollUpFixedDocument = _documents[docIndex];
            TestForExistingPages(rollUpFixedDocument);
            rollUpFixedDocument.Pages.Insert(docIndex, new RollUpFixedPage(page));
            _fixedDocumentSequence = null;
        }

        public void InsertPage(int docIndex, int insertAfterPageIndex, Uri source, Uri uri)
        {
            var rollUpFixedDocument = _documents[docIndex];
            TestForExistingPages(rollUpFixedDocument);
            rollUpFixedDocument.Pages.Insert(insertAfterPageIndex, new RollUpFixedPage(source, uri));
            _fixedDocumentSequence = null;
        }

        public void RemovePage(int docIndex, int pageIndex)
        {
            var rollUpFixedDocument = _documents[docIndex];
            TestForExistingPages(rollUpFixedDocument);
            rollUpFixedDocument.Pages.RemoveAt(pageIndex);
            _fixedDocumentSequence = null;
        }

        public int GetPageCount(int docIndex)
        {
            var fixedDocument = _documents[docIndex];
            if (fixedDocument.BaseUri != null)
            {
                fixedDocument.CreatePagesFromSource();
            }
            return fixedDocument.Pages.Count;
        }

        public PageContent GetPage(int docIndex, int pageIndex)
        {
            var fixedDocument = _documents[docIndex];
            if (fixedDocument.BaseUri != null)
            {
                fixedDocument.CreatePagesFromSource();
            }

            var pageContent = new PageContent();
            var fixedPage = fixedDocument.Pages[pageIndex];
            pageContent.Source = fixedPage.Source;
            ((IUriContext) pageContent).BaseUri = fixedPage.BaseUri;
            return pageContent;
        }

        public void Save()
        {
            if (Uri == null)
            {
                throw new ArgumentException("Uri has not been specified");
            }

            var xpsDocument = new XpsDocument(Uri.OriginalString, FileAccess.ReadWrite);
            var xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
            xpsDocumentWriter.Write(FixedDocumentSequence);
            xpsDocument.Close();
        }

        private void ReCreateFixedDocumentSequence()
        {
            _fixedDocumentSequence = new FixedDocumentSequence();
            foreach (var document in _documents)
            {
                var documentReference = new DocumentReference();
                FillDocumentReference(documentReference, document);
                var fixedDocument = documentReference.GetDocument(true);
                _fixedDocumentSequence.References.Add(documentReference);
            }
        }

        private void FillDocumentReference(DocumentReference documentReference, RollUpFixedDocument document)
        {
            if (document.BaseUri != null)
            {
                documentReference.Source = document.Source;
                (documentReference as IUriContext).BaseUri = document.BaseUri;
            }
            else if (document.FixedDocument != null)
            {
                documentReference.SetDocument(document.FixedDocument);
            }
            else
            {
                AddPages(documentReference, document);
            }
        }

        private void AddPages(DocumentReference documentReference, RollUpFixedDocument document)
        {
            var fixedDocument = new FixedDocument();
            documentReference.SetDocument(fixedDocument);
            foreach (var page in document.Pages)
            {
                var pageContent = new PageContent();
                if (page.BaseUri == null)
                {
                    ((IAddChild) pageContent).AddChild(page.FixedPage);
                }
                else
                {
                    pageContent.Source = page.Source;
                    ((IUriContext) pageContent).BaseUri = page.BaseUri;
                }
                pageContent.GetPageRoot(true);
                fixedDocument.Pages.Add(pageContent);
            }
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/NullWrappingXamlReader.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Xaml;

namespace BamlTools
{
    public class NullWrappingXamlReader : XamlReader
    {
        XamlReader _wrappedReader;

        XamlNodeQueue _pipe;

        // cached from the PIPE.
        XamlReader _reader;
        XamlWriter _writer;

        bool _done;

        public NullWrappingXamlReader(XamlReader wrappedReader)
        {
            _wrappedReader = wrappedReader;

            _pipe = new XamlNodeQueue(wrappedReader.SchemaContext);
            _reader = _pipe.Reader;
            _writer = _pipe.Writer;
        }

        public override bool Read()
        {
            if (_done)
            {
                return false;
            }

            if (!_wrappedReader.Read())
            {
                _done = true;
            }

            _writer.WriteNode(_wrappedReader);
            _reader.Read();
            return true;
        }

        public override XamlNodeType NodeType
        {
            get { return _reader.NodeType; }
        }

        public override bool IsEof
        {
            get { return _reader.IsEof; }
        }

        public override NamespaceDeclaration Namespace
        {
            get { return _reader.Namespace; }
        }

        public override XamlType Type
        {
            get { return _reader.Type; }
        }

        public override object Value
        {
            get { return _reader.Value; }
        }

        public override XamlMember Member
        {
            get { return _reader.Member; }
        }

        public override XamlSchemaContext SchemaContext
        {
            get { return _reader.SchemaContext; }
        }
    }
}


<|start_filename|>Application Management/ExceptionHandlingSecondaryWorkerThread/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace ExceptionHandlingSecondaryWorkerThread
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Title = $"Running on Main UI Thread {Thread.CurrentThread.ManagedThreadId}";
        }

        private void startSecondaryWorkerThreadButton_Click(object sender, RoutedEventArgs e)
        {
            // Creates and starts a secondary thread in a single threaded apartment (STA)
            var thread = new Thread(MethodRunningOnSecondaryWorkerThread);
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = true;
            thread.Start();
        }

        // THIS METHOD RUNS ON A SECONDARY WORKER THREAD (THREAD WITHOUT A DISPATCHER)
        private void MethodRunningOnSecondaryWorkerThread()
        {
            try
            {
                WorkerMethod();
            }
            catch (Exception ex)
            {
                // Dispatch the exception back to the main UI thread. Then, reraise
                // the exception on the main UI thread and handle it from the handler 
                // the Application object's DispatcherUnhandledException event.
                var secondaryWorkerThreadId = Thread.CurrentThread.ManagedThreadId;
                Application.Current.Dispatcher.Invoke(
                    DispatcherPriority.Send,
                    (DispatcherOperationCallback) delegate
                    {
                        // THIS CODE RUNS BACK ON THE MAIN UI THREAD
                        string msg = $"Exception forwarded from secondary worker thread {secondaryWorkerThreadId}.";
                        throw new Exception(msg, ex);
                    }
                    , null);

                // NOTE - Application execution will only continue from this point
                //        onwards if the exception was handled on the main UI thread.
                //        by Application.DispatcherUnhandledException
            }
        }

        private void WorkerMethod()
        {
            // This method would do real processing on the secondary worker thread.
            // For the purposes of this sample, it throws an exception
            string msg =
                $"Exception raised secondary on worker thread {Dispatcher.CurrentDispatcher.Thread.ManagedThreadId}.";
            throw new Exception(msg);
        }
    }
}

<|start_filename|>Animation/KeySplineAnimations/SplineExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace KeySplineAnimations
{
    public partial class SplineExample : Page
    {
        private Point _controlPoint1 = new Point(0, 100);
        private Point _controlPoint2 = new Point(0, 100);

        private void OnSliderChanged(object sender, RoutedEventArgs e)
        {
            // Retrieve the name of slider.
            var name = ((Slider) sender).Name;

            var args = e as RoutedPropertyChangedEventArgs<double>;

            switch (name)
            {
                case "SliderControlPoint1X":
                    mySplineKeyFrame.KeySpline.ControlPoint1 = new Point(args.NewValue,
                        mySplineKeyFrame.KeySpline.ControlPoint1.Y);
                    _controlPoint1.X = 100*args.NewValue;
                    break;
                case "SliderControlPoint1Y":
                    mySplineKeyFrame.KeySpline.ControlPoint1 = new Point(mySplineKeyFrame.KeySpline.ControlPoint1.X,
                        args.NewValue);
                    _controlPoint1.Y = 100 - (100*args.NewValue);
                    break;
                case "SliderControlPoint2X":
                    mySplineKeyFrame.KeySpline.ControlPoint2 = new Point(args.NewValue,
                        mySplineKeyFrame.KeySpline.ControlPoint2.Y);
                    _controlPoint2.X = 100*args.NewValue;
                    break;
                case "SliderControlPoint2Y":
                    mySplineKeyFrame.KeySpline.ControlPoint2 = new Point(mySplineKeyFrame.KeySpline.ControlPoint2.X,
                        args.NewValue);
                    _controlPoint2.Y = 100 - (100*args.NewValue);
                    break;
            }


            // Update the animations and illustrations.
            myVector3DSplineKeyFrame.KeySpline.ControlPoint1 = mySplineKeyFrame.KeySpline.ControlPoint1;
            myVector3DSplineKeyFrame.KeySpline.ControlPoint2 = mySplineKeyFrame.KeySpline.ControlPoint2;


            SplineIllustrationSegment.Point1 = _controlPoint1;
            SplineIllustrationSegment.Point2 = _controlPoint2;
            SplineControlPoint1Marker.Center = _controlPoint1;
            SplineControlPoint2Marker.Center = _controlPoint2;

            keySplineText.Text =
                "KeySpline=\"" + mySplineKeyFrame.KeySpline.ControlPoint1.X.ToString("N") + "," +
                mySplineKeyFrame.KeySpline.ControlPoint1.Y.ToString("N") + " " +
                mySplineKeyFrame.KeySpline.ControlPoint2.X.ToString("N") + "," +
                mySplineKeyFrame.KeySpline.ControlPoint2.Y.ToString("N") + "\"";


            // Determine the storyboard's current time.
            TimeSpan? oldTime = (TimeSpan) ExampleStoryboard.GetCurrentTime(this);

            // Generate new clocks for the animations by calling 
            // the Begin method.
            ExampleStoryboard.Begin(this, true);

            // Because the storyboard was reset, advance it to its previous
            // position using the Seek method.
            ExampleStoryboard.Seek(this, (TimeSpan) oldTime, TimeSeekOrigin.BeginTime);
        }
    }
}

<|start_filename|>Sample Applications/ParticlesDemo/ParticleSystem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;

namespace ParticlesDemo
{
    public class ParticleSystem
    {
        private readonly List<Particle> _particleList;
        private readonly GeometryModel3D _particleModel;
        private readonly Random _rand;

        public ParticleSystem(int maxCount, Color color)
        {
            MaxParticleCount = maxCount;

            _particleList = new List<Particle>();

            _particleModel = new GeometryModel3D {Geometry = new MeshGeometry3D()};

            var e = new Ellipse
            {
                Width = 32.0,
                Height = 32.0
            };
            var b = new RadialGradientBrush();
            b.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, color.R, color.G, color.B), 0.25));
            b.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, color.R, color.G, color.B), 1.0));
            e.Fill = b;
            e.Measure(new Size(32, 32));
            e.Arrange(new Rect(0, 0, 32, 32));

            Brush brush = null;

#if USE_VISUALBRUSH
            brush = new VisualBrush(e);
#else
            var renderTarget = new RenderTargetBitmap(32, 32, 96, 96, PixelFormats.Pbgra32);
            renderTarget.Render(e);
            renderTarget.Freeze();
            brush = new ImageBrush(renderTarget);
#endif

            var material = new DiffuseMaterial(brush);

            _particleModel.Material = material;

            _rand = new Random(brush.GetHashCode());
        }

        public int MaxParticleCount { get; set; }
        public int Count => _particleList.Count;
        public Model3D ParticleModel => _particleModel;

        public void Update(double elapsed)
        {
            var deadList = new List<Particle>();

            // Update all particles
            foreach (var p in _particleList)
            {
                p.Position += p.Velocity*elapsed;
                p.Life -= p.Decay*elapsed;
                p.Size = p.StartSize*(p.Life/p.StartLife);
                if (p.Life <= 0.0)
                    deadList.Add(p);
            }

            foreach (var p in deadList)
                _particleList.Remove(p);

            UpdateGeometry();
        }

        private void UpdateGeometry()
        {
            var positions = new Point3DCollection();
            var indices = new Int32Collection();
            var texcoords = new PointCollection();

            for (var i = 0; i < _particleList.Count; ++i)
            {
                var positionIndex = i*4;
                var indexIndex = i*6;
                var p = _particleList[i];

                var p1 = new Point3D(p.Position.X, p.Position.Y, p.Position.Z);
                var p2 = new Point3D(p.Position.X, p.Position.Y + p.Size, p.Position.Z);
                var p3 = new Point3D(p.Position.X + p.Size, p.Position.Y + p.Size, p.Position.Z);
                var p4 = new Point3D(p.Position.X + p.Size, p.Position.Y, p.Position.Z);

                positions.Add(p1);
                positions.Add(p2);
                positions.Add(p3);
                positions.Add(p4);

                var t1 = new Point(0.0, 0.0);
                var t2 = new Point(0.0, 1.0);
                var t3 = new Point(1.0, 1.0);
                var t4 = new Point(1.0, 0.0);

                texcoords.Add(t1);
                texcoords.Add(t2);
                texcoords.Add(t3);
                texcoords.Add(t4);

                indices.Add(positionIndex);
                indices.Add(positionIndex + 2);
                indices.Add(positionIndex + 1);
                indices.Add(positionIndex);
                indices.Add(positionIndex + 3);
                indices.Add(positionIndex + 2);
            }

            ((MeshGeometry3D) _particleModel.Geometry).Positions = positions;
            ((MeshGeometry3D) _particleModel.Geometry).TriangleIndices = indices;
            ((MeshGeometry3D) _particleModel.Geometry).TextureCoordinates = texcoords;
        }

        public void SpawnParticle(Point3D position, double speed, double size, double life)
        {
            if (_particleList.Count > MaxParticleCount)
                return;
            var p = new Particle
            {
                Position = position,
                StartLife = life,
                Life = life,
                StartSize = size,
                Size = size
            };

            var x = 1.0f - (float) _rand.NextDouble()*2.0f;
            var z = 1.0f - (float) _rand.NextDouble()*2.0f;

            var v = new Vector3D(x, z, 0.0);
            v.Normalize();
            v *= ((float) _rand.NextDouble() + 0.25f)*(float) speed;

            p.Velocity = new Vector3D(v.X, v.Y, v.Z);

            p.Decay = 1.0f; // 0.5 + rand.NextDouble();
            //if (p.Decay > 1.0)
            //    p.Decay = 1.0;

            _particleList.Add(p);
        }
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Data;

namespace PhotoViewerDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public sealed partial class MainWindow : Window
    {
        public PhotoCollection Photos;

        public MainWindow()
        {
            InitializeComponent();
            Photos = (PhotoCollection) (Application.Current.Resources["Photos"] as ObjectDataProvider)?.Data;
            Photos.Path = Environment.CurrentDirectory + "\\images";
        }

        private void OnPhotoClick(object sender, RoutedEventArgs e)
        {
            var pvWindow = new PhotoViewer {SelectedPhoto = (Photo) PhotosListBox.SelectedItem};
            pvWindow.Show();
        }

        private void EditPhoto(object sender, RoutedEventArgs e)
        {
            var pvWindow = new PhotoViewer {SelectedPhoto = (Photo) PhotosListBox.SelectedItem};
            pvWindow.Show();
        }

        private void OnImagesDirChangeClick(object sender, RoutedEventArgs e)
        {
            Photos.Path = ImagesDir.Text;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            ImagesDir.Text = Environment.CurrentDirectory + "\\images";
        }
    }
}

<|start_filename|>Sample Applications/EditingExaminerDemo/TreeViewhelper.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace EditingExaminerDemo
{
    /// <summary>
    ///     Provides help function for the document TreeView.
    /// </summary>
    internal class TreeViewhelper
    {
        /// <summary>
        ///     Create or fill up a TreeView of the document content
        /// </summary>
        /// <param name="treeView">Pass an TreeView control</param>
        /// <param name="document">Pass in an Document object</param>
        /// <returns></returns>
        public static TreeView SetupTreeView(TreeView treeView, FlowDocument document)
        {
            TreeViewItem root;
            if (treeView == null)
            {
                treeView = new TreeView {Visibility = Visibility.Visible};
            }
            if (document != null)
            {
                treeView.Items.Clear();
                root = new TreeViewItem
                {
                    Header = "Document",
                    IsExpanded = true
                };
                treeView.Items.Add(root);
                AddCollection(root, document.Blocks);
            }

            return treeView;
        }

        private static void AddCollection(TreeViewItem item, IList list)
        {
            foreach (var listItem in list)
            {
                var titem = new TreeViewItem();
                item.Items.Add(titem);
                titem.IsExpanded = true;
                titem.Header = listItem.GetType().Name;
                AddItem(titem, listItem as TextElement);
            }
        }

        private static void AddItem(TreeViewItem item, TextElement textElement)
        {
            TreeViewItem childItem;

            if (textElement is InlineUIContainer)
            {
                childItem = new TreeViewItem
                {
                    Header = ((InlineUIContainer) textElement).Child.GetType().Name,
                    IsExpanded = true
                };
                item.Items.Add(childItem);
            }
            else if (textElement is BlockUIContainer)
            {
                childItem = new TreeViewItem
                {
                    Header = ((BlockUIContainer) textElement).Child.GetType().Name,
                    IsExpanded = true
                };
                item.Items.Add(childItem);
            }
            else if (textElement is Span)
            {
                AddCollection(item, ((Span) textElement).Inlines);
            }
            else if (textElement is Paragraph)
            {
                AddCollection(item, ((Paragraph) textElement).Inlines);
            }
            else if (textElement is List)
            {
                AddCollection(item, ((List) textElement).ListItems);
            }
            else if (textElement is ListItem)
            {
                AddCollection(item, ((ListItem) textElement).Blocks);
            }
            else if (textElement is Table)
            {
                TableTreeView(item, textElement as Table);
            }
            else if (textElement is AnchoredBlock)
            {
                var floater = textElement as Floater;
                AddCollection(item, ((AnchoredBlock) textElement).Blocks);
            }

            //The element should be an inline (Run); try to display the text.
            else if (textElement is Inline)
            {
                var range = new TextRange(((Inline) textElement).ContentEnd, ((Inline) textElement).ContentStart);
                item.Header = item.Header + " - [" + range.Text + "]";
            }
        }

        private static void TableTreeView(TreeViewItem item, Table table)
        {
            TreeViewItem item1, item2;
            foreach (var rg in table.RowGroups)
            {
                foreach (var tr in rg.Rows)
                {
                    item1 = new TreeViewItem
                    {
                        IsExpanded = true,
                        Header = "TableRow"
                    };
                    item.Items.Add(item1);
                    foreach (var tc in tr.Cells)
                    {
                        item2 = new TreeViewItem {Header = "TableCell"};
                        item1.Items.Add(item2);
                        item2.IsExpanded = true;
                        AddCollection(item2, tc.Blocks);
                    }
                }
            }
        }
    }
}

<|start_filename|>Sample Applications/ConcentricRingsDemo/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace ConcentricRingsDemo
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly Random _rand;
        private int _lastTick;

        public MainWindow()
        {
            InitializeComponent();

            WindowState = WindowState.Maximized;
            WindowStyle = WindowStyle.None;
            ResizeMode = ResizeMode.NoResize;

            var frameTimer = new DispatcherTimer();
            frameTimer.Tick += OnFrame;
            frameTimer.Interval = TimeSpan.FromSeconds(1.0/60.0);
            frameTimer.Start();

            _lastTick = Environment.TickCount;

            _rand = new Random(GetHashCode());

            Show();

            KeyDown += Window1_KeyDown;

            CreateCircles();
        }

        private void Window1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
                Close();
        }

        private void OnFrame(object sender, EventArgs e)
        {
        }

        private void CreateCircles()
        {
            var centerX = MainCanvas.ActualWidth/2.0;
            var centerY = MainCanvas.ActualHeight/2.0;

            Color[] colors = {Colors.White, Colors.Green, Colors.Green, Colors.Lime};

            for (var i = 0; i < 24; ++i)
            {
                var e = new Ellipse();
                var alpha = (byte) _rand.Next(96, 192);
                var colorIndex = _rand.Next(4);
                e.Stroke =
                    new SolidColorBrush(Color.FromArgb(alpha, colors[colorIndex].R, colors[colorIndex].G,
                        colors[colorIndex].B));
                e.StrokeThickness = _rand.Next(1, 4);
                e.Width = 0.0;
                e.Height = 0.0;
                double offsetX = 16 - _rand.Next(32);
                double offsetY = 16 - _rand.Next(32);

                MainCanvas.Children.Add(e);

                e.SetValue(Canvas.LeftProperty, centerX + offsetX);
                e.SetValue(Canvas.TopProperty, centerY + offsetY);

                var duration = 6.0 + 10.0*_rand.NextDouble();
                var delay = 16.0*_rand.NextDouble();

                var offsetTransform = new TranslateTransform();

                var offsetXAnimation = new DoubleAnimation(0.0, -256.0, new Duration(TimeSpan.FromSeconds(duration)))
                {
                    RepeatBehavior = RepeatBehavior.Forever,
                    BeginTime = TimeSpan.FromSeconds(delay)
                };
                offsetTransform.BeginAnimation(TranslateTransform.XProperty, offsetXAnimation);
                offsetTransform.BeginAnimation(TranslateTransform.YProperty, offsetXAnimation);

                e.RenderTransform = offsetTransform;


                var sizeAnimation = new DoubleAnimation(0.0, 512.0, new Duration(TimeSpan.FromSeconds(duration)))
                {
                    RepeatBehavior = RepeatBehavior.Forever,
                    BeginTime = TimeSpan.FromSeconds(delay)
                };
                e.BeginAnimation(WidthProperty, sizeAnimation);
                e.BeginAnimation(HeightProperty, sizeAnimation);

                var opacityAnimation = new DoubleAnimation(duration - 1.0, 0.0,
                    new Duration(TimeSpan.FromSeconds(duration)))
                {
                    BeginTime = TimeSpan.FromSeconds(delay),
                    RepeatBehavior = RepeatBehavior.Forever
                };
                e.BeginAnimation(OpacityProperty, opacityAnimation);
            }
        }
    }
}

<|start_filename|>PerMonitorDPI/TextFormatting/GenericTextProperties.cs<|end_filename|>
﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;

namespace TextFormatting
{
    /// <summary>
    /// Class to implement TextParagraphProperties, used by TextSource
    /// </summary>
    class GenericTextParagraphProperties : TextParagraphProperties
    {
        #region Constructors
        public GenericTextParagraphProperties(
           FlowDirection flowDirection,
           TextAlignment textAlignment,
           bool firstLineInParagraph,
           bool alwaysCollapsible,
           TextRunProperties defaultTextRunProperties,
           TextWrapping textWrap,
           double lineHeight,
           double indent)
        {
            _flowDirection = flowDirection;
            _textAlignment = textAlignment;
            _firstLineInParagraph = firstLineInParagraph;
            _alwaysCollapsible = alwaysCollapsible;
            _defaultTextRunProperties = defaultTextRunProperties;
            _textWrap = textWrap;
            _lineHeight = lineHeight;
            _indent = indent;
        }

        public GenericTextParagraphProperties(FontRendering newRendering, double pixelsPerDip)
        {
            _flowDirection = FlowDirection.LeftToRight;
            _textAlignment = newRendering.TextAlignment;
            _firstLineInParagraph = false;
            _alwaysCollapsible = false;
            _defaultTextRunProperties = new GenericTextRunProperties(
               newRendering.Typeface, pixelsPerDip, newRendering.FontSize, newRendering.FontSize,
               newRendering.TextDecorations, newRendering.TextColor, null,
               BaselineAlignment.Baseline, CultureInfo.CurrentUICulture);
            _textWrap = TextWrapping.Wrap;
            _lineHeight = 0;
            _indent = 0;
            _paragraphIndent = 0;
        }
        #endregion

        #region Properties
        public override FlowDirection FlowDirection
        {
            get { return _flowDirection; }
        }

        public override TextAlignment TextAlignment
        {
            get { return _textAlignment; }
        }

        public override bool FirstLineInParagraph
        {
            get { return _firstLineInParagraph; }
        }

        public override bool AlwaysCollapsible
        {
            get { return _alwaysCollapsible; }
        }

        public override TextRunProperties DefaultTextRunProperties
        {
            get { return _defaultTextRunProperties; }
        }

        public override TextWrapping TextWrapping
        {
            get { return _textWrap; }
        }

        public override double LineHeight
        {
            get { return _lineHeight; }
        }

        public override double Indent
        {
            get { return _indent; }
        }

        public override TextMarkerProperties TextMarkerProperties
        {
            get { return null; }
        }

        public override double ParagraphIndent
        {
            get { return _paragraphIndent; }
        }
        #endregion

        #region Private Fields
        private FlowDirection _flowDirection;
        private TextAlignment _textAlignment;
        private bool _firstLineInParagraph;
        private bool _alwaysCollapsible;
        private TextRunProperties _defaultTextRunProperties;
        private TextWrapping _textWrap;
        private double _indent;
        private double _paragraphIndent;
        private double _lineHeight;
        #endregion
    }

    /// <summary>
    /// Class used to implement TextRunProperties
    /// </summary>
    class GenericTextRunProperties : TextRunProperties
    {
        #region Constructors
        public GenericTextRunProperties(
           Typeface typeface,
           double pixelsPerDip,
           double size,
           double hintingSize,
           TextDecorationCollection textDecorations,
           Brush forgroundBrush,
           Brush backgroundBrush,
           BaselineAlignment baselineAlignment,
           CultureInfo culture)
        {
            if (typeface == null)
                throw new ArgumentNullException("typeface");

            ValidateCulture(culture);

            PixelsPerDip = pixelsPerDip;
            _typeface = typeface;
            _emSize = size;
            _emHintingSize = hintingSize;
            _textDecorations = textDecorations;
            _foregroundBrush = forgroundBrush;
            _backgroundBrush = backgroundBrush;
            _baselineAlignment = baselineAlignment;
            _culture = culture;
        }

        public GenericTextRunProperties(FontRendering newRender, double pixelsPerDip)
        {
            _typeface = newRender.Typeface;
            _emSize = newRender.FontSize;
            _emHintingSize = newRender.FontSize;
            _textDecorations = newRender.TextDecorations;
            _foregroundBrush = newRender.TextColor;
            _backgroundBrush = null;
            _baselineAlignment = BaselineAlignment.Baseline;
            _culture = CultureInfo.CurrentUICulture;
            PixelsPerDip = pixelsPerDip;
        }
        #endregion

        #region Private Methods
        private static void ValidateCulture(CultureInfo culture)
        {
            if (culture == null)
                throw new ArgumentNullException("culture");
            if (culture.IsNeutralCulture || culture.Equals(CultureInfo.InvariantCulture))
                throw new ArgumentException("Specific Culture Required", "culture");
        }

        private static void ValidateFontSize(double emSize)
        {
            if (emSize <= 0)
                throw new ArgumentOutOfRangeException("emSize", "Parameter Must Be Greater Than Zero.");
            //if (emSize > MaxFontEmSize)
            //   throw new ArgumentOutOfRangeException("emSize", "Parameter Is Too Large.");
            if (double.IsNaN(emSize))
                throw new ArgumentOutOfRangeException("emSize", "Parameter Cannot Be NaN.");
        }
        #endregion

        #region Properties
        public override Typeface Typeface
        {
            get { return _typeface; }
        }

        public override double FontRenderingEmSize
        {
            get { return _emSize; }
        }

        public override double FontHintingEmSize
        {
            get { return _emHintingSize; }
        }

        public override TextDecorationCollection TextDecorations
        {
            get { return _textDecorations; }
        }

        public override Brush ForegroundBrush
        {
            get { return _foregroundBrush; }
        }

        public override Brush BackgroundBrush
        {
            get { return _backgroundBrush; }
        }

        public override BaselineAlignment BaselineAlignment
        {
            get { return _baselineAlignment; }
        }

        public override CultureInfo CultureInfo
        {
            get { return _culture; }
        }

        public override TextRunTypographyProperties TypographyProperties
        {
            get { return null; }
        }

        public override TextEffectCollection TextEffects
        {
            get { return null; }
        }

        public override NumberSubstitution NumberSubstitution
        {
            get { return null; }
        }
        #endregion

        #region Private Fields
        private Typeface _typeface;
        private double _emSize;
        private double _emHintingSize;
        private TextDecorationCollection _textDecorations;
        private Brush _foregroundBrush;
        private Brush _backgroundBrush;
        private BaselineAlignment _baselineAlignment;
        private CultureInfo _culture;
        #endregion
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/MultExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Multiplies 2 expressions.
    /// </summary>
    public sealed class MultExpression : BinaryExpression
    {
        public MultExpression(IExpression left, IExpression right) : base(left, right)
        {
        }

        protected override double Operate(double d1, double d2) => d1 * d2;

        public override IExpression Differentiate(string byVar) => new AddExpression(new MultExpression(left, right.Differentiate(byVar)),
                new MultExpression(left.Differentiate(byVar), right));

        public override IExpression Simplify()
        {
            var newLeft = left.Simplify();
            var newRight = right.Simplify();

            var leftConst = newLeft as ConstantExpression;
            var rightConst = newRight as ConstantExpression;
            var leftNegate = newLeft as NegateExpression;
            var rightNegate = newRight as NegateExpression;

            if (leftConst != null && rightConst != null)
            {
                // two constants;  just evaluate it;
                return new ConstantExpression(leftConst.Value*rightConst.Value);
            }
            if (leftConst != null)
            {
                if (leftConst.Value == 0)
                {
                    // 0 * y;  return 0;
                    return new ConstantExpression(0);
                }
                if (leftConst.Value == 1)
                {
                    // 1 * y;  return y;
                    return newRight;
                }
                if (leftConst.Value == -1)
                {
                    // -1 * y;  return -y
                    if (rightNegate != null)
                    {
                        // y = -u (-y = --u);  return u;
                        return rightNegate.Child;
                    }
                    return new NegateExpression(newRight);
                }
            }
            else if (rightConst != null)
            {
                if (rightConst.Value == 0)
                {
                    // x * 0;  return 0;
                    return new ConstantExpression(0);
                }
                if (rightConst.Value == 1)
                {
                    // x * 1;  return x;
                    return newLeft;
                }
                if (rightConst.Value == -1)
                {
                    // x * -1;  return -x;
                    if (leftNegate != null)
                    {
                        // x = -u (-x = --u);  return u;
                        return leftNegate.Child;
                    }
                    return new NegateExpression(newLeft);
                }
            }
            else if (leftNegate != null && rightNegate != null)
            {
                // -x * -y;  return x * y;
                return new MultExpression(leftNegate.Child, rightNegate.Child);
            }
            // x * y;  no simplification
            return new MultExpression(newLeft, newRight);
        }

        public override string ToString() => "(" + left.ToString() + "*" + right.ToString() + ")";
    }
}

<|start_filename|>Application Management/UnhandledExceptionHandling/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace UnhandledExceptionHandling
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void raiseRecoverableException_Click(object sender, RoutedEventArgs e)
        {
            throw new DivideByZeroException("Recoverable Exception");
        }

        private void raiseUnecoverableException_Click(object sender, RoutedEventArgs e)
        {
            throw new ArgumentNullException(@"Unrecoverable Exception");
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/SubExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Subtracts 2 expressions.
    /// </summary>
    public sealed class SubExpression : BinaryExpression
    {
        public SubExpression(IExpression left, IExpression right) : base(left, right)
        {
        }

        protected override double Operate(double d1, double d2) => d1 - d2;

        public override IExpression Differentiate(string byVar) => new SubExpression(left.Differentiate(byVar), right.Differentiate(byVar));

        public override IExpression Simplify()
        {
            var newLeft = left.Simplify();
            var newRight = right.Simplify();

            var leftConst = newLeft as ConstantExpression;
            var rightConst = newRight as ConstantExpression;
            var rightNegate = newRight as NegateExpression;

            if (leftConst != null && rightConst != null)
            {
                // two constants;  just evaluate it;
                return new ConstantExpression(leftConst.Value - rightConst.Value);
            }
            if (leftConst != null && leftConst.Value == 0)
            {
                // 0 - y;  return -y;
                if (rightNegate != null)
                {
                    // y = -u (--u);  return u;
                    return rightNegate.Child;
                }
                return new NegateExpression(newRight);
            }
            if (rightConst != null && rightConst.Value == 0)
            {
                // x - 0;  return x;
                return newLeft;
            }
            if (rightNegate != null)
            {
                // x - -y;  return x + y;
                return new AddExpression(newLeft, rightNegate.Child);
            }
            // x - y;  no simplification
            return new SubExpression(newLeft, newRight);
        }

        public override string ToString() => "(" + left.ToString() + "-" + right.ToString() + ")";
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Settings.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo
{
    public class Settings
    {
        public const string UMin = "u Min";
        public const string UMax = "u Max";
        public const string UGrid = "u GridSections";
        public const string VMin = "v Min";
        public const string VMax = "v Max";
        public const string VGrid = "v GridSections";
        public const string XMin = "x Min";
        public const string XMax = "x Max";
        public const string YMin = "y Min";
        public const string YMax = "y Max";
        public const string XMin2D = "x Min";
        public const string XMax2D = "x Max";
        public const string YMin2D = "y Min";
        public const string YMax2D = "y Max";
        public const string Min2D = "t Min";
        public const string Max2D = "t Max";
        public const string Step2D = "t Step";
        public const string UMinReg = "uMin";
        public const string UMaxReg = "uMax";
        public const string UGridReg = "uGrid";
        public const string VMinReg = "vMin";
        public const string VMaxReg = "vMax";
        public const string VGridReg = "vGrid";
        public const string XMinReg = "xMin";
        public const string XMaxReg = "xMax";
        public const string YMinReg = "yMin";
        public const string YMaxReg = "yMax";
        public const string XMin2DReg = "xMin2D";
        public const string XMax2DReg = "xMax2D";
        public const string YMin2DReg = "yMin2D";
        public const string YMax2DReg = "yMax2D";
        public const string Min2DReg = "tMin2D";
        public const string Max2DReg = "tMax2D";
        public const string Step2DReg = "tStep2D";
        public const string UMinDefault = "-pi";
        public const string UMaxDefault = "pi";
        public const string UGridDefault = "24";
        public const string VMinDefault = "0";
        public const string VMaxDefault = "pi";
        public const string VGridDefault = "48";
        public const string XMinDefault = "-10";
        public const string XMaxDefault = "10";
        public const string YMinDefault = "-10";
        public const string YMaxDefault = "10";
        public const string XMin2DDefault = "-10";
        public const string XMax2DDefault = "10";
        public const string YMin2DDefault = "-10";
        public const string YMax2DDefault = "10";
        public const string Min2DDefault = "0";
        public const string Max2DDefault = "10pi";
        public const string Step2DDefault = "pi/16";
        public const string Fx = "x( u,v )=";
        public const string Fy = "y( u,v )=";
        public const string Fz = "z( u,v )=";
        public const string Y = "y=";
        public const string Xt = "x( t )=";
        public const string Yt = "y( t )=";
        public const string FxReg = "fx";
        public const string FyReg = "fy";
        public const string FzReg = "fz";
        public const string YReg = "y";
        public const string XtReg = "xt";
        public const string YtReg = "yt";
        public const string FxDefault = "cos(u)sin(v)";
        public const string FyDefault = "-cos(v)";
        public const string FzDefault = "sin(-u)sin(v)";
        public const string YDefault = "x*sin(x^2)+x";
        public const string XtDefault = "sin(t)*t/pi";
        public const string YtDefault = "cos(t)*t/pi";
        public const string Function = "2D";
        public const string Function2D = "2D Parametric";
        public const string Function3D = "3D Parametric";
        public const string FunctionNone = "None";
    }
}

<|start_filename|>Application Management/SkinnedApplication/ChildWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace SkinnedApplication
{
    /// <summary>
    ///     Interaction logic for ChildWindow.xaml
    /// </summary>
    public partial class ChildWindow : Window
    {
        public ChildWindow()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Graphics/PNGEncoderAndDecoder/App.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

[assembly: SecurityTransparent]

namespace PNGEncoderAndDecoder
{
    public class App : Application
    {
        private Window _mainWindow;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            CreateAndShowMainWindow();
        }

        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {Title = "PNG Imaging Sample"};
            var mySv = new ScrollViewer();

            var width = 128;
            var height = 128;
            var stride = width;
            var pixels = new byte[width*stride];

            // Define the image palette
            var myPalette = BitmapPalettes.Halftone256;

            // Creates a new empty image with the pre-defined palette

            var image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed8,
                myPalette,
                pixels,
                stride);

            var stream = new FileStream("new.png", FileMode.Create);
            var encoder = new PngBitmapEncoder();
            var myTextBlock = new TextBlock {Text = "Codec Author is: " + encoder.CodecInfo.Author};
            encoder.Interlace = PngInterlaceOption.On;
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);


            // Open a Stream and decode a PNG image
            Stream imageStreamSource = new FileStream("smiley.png", FileMode.Open, FileAccess.Read, FileShare.Read);
            var decoder = new PngBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];

            // Draw the Image
            var myImage = new Image
            {
                Source = bitmapSource,
                Stretch = Stretch.None,
                Margin = new Thickness(20)
            };


            // Open a Uri and decode a PNG image
            var myUri = new Uri("smiley.png", UriKind.RelativeOrAbsolute);
            var decoder2 = new PngBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);
            BitmapSource bitmapSource2 = decoder2.Frames[0];

            // Draw the Image
            var myImage2 = new Image
            {
                Source = bitmapSource2,
                Stretch = Stretch.None,
                Margin = new Thickness(20)
            };

            // Define a StackPanel to host the decoded PNG images
            var myStackPanel = new StackPanel
            {
                Orientation = Orientation.Vertical,
                VerticalAlignment = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch
            };

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            mySv.Content = myStackPanel;
            _mainWindow.Content = mySv;
            _mainWindow.Show();
        }
    }

    // Define a static entry class
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/BinaryExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Combines the results of 2 expressions, with the binary operation.
    /// </summary>
    public abstract class BinaryExpression : IExpression
    {
        protected IExpression left;
        protected IExpression right;

        protected BinaryExpression(IExpression left, IExpression right)
        {
            this.left = left;
            this.right = right;
        }

        public IExpression Left => left;
        public IExpression Right => right;

        public double Evaluate() => Operate(left.Evaluate(), right.Evaluate());

        string IExpression.ToString() => ToString();

        public abstract IExpression Differentiate(string byVar);
        public abstract IExpression Simplify();
        protected abstract double Operate(double d1, double d2);
        public abstract override string ToString();
    }
}

<|start_filename|>Graphics/SystemBrushesAndColors/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace SystemBrushesAndColors
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            ListSystemBrushes();
            ListGradientExamples();
        }

        // Demonstrates using system colors to fill rectangles and buttons.
        private void ListSystemBrushes()
        {
            // The window style (defined in Window1.xaml) is used to
            // specify the height and width of each of the System.Windows.Shapes.Rectangles.
            var t = new TextBlock {Text = "ActiveBorder"};
            var r = new Rectangle
            {
                Fill = SystemColors.ActiveBorderBrush
            };
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ActiveCaption"};
            r = new Rectangle {Fill = SystemColors.ActiveCaptionBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ActiveCaptionText"};
            r = new Rectangle {Fill = SystemColors.ActiveCaptionTextBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "AppWorkspace"};
            r = new Rectangle {Fill = SystemColors.AppWorkspaceBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "Control"};
            r = new Rectangle {Fill = SystemColors.ControlBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ControlDark"};
            r = new Rectangle {Fill = SystemColors.ControlDarkBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ControlDarkDark"};
            r = new Rectangle {Fill = SystemColors.ControlDarkDarkBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ControlLight"};
            r = new Rectangle {Fill = SystemColors.ControlLightBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ControlLightLight"};
            r = new Rectangle {Fill = SystemColors.ControlLightLightBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ControlText"};
            r = new Rectangle {Fill = SystemColors.ControlTextBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "Desktop"};
            r = new Rectangle();
            //r.Fill = SystemColors.DesktopBrush;
            r.SetResourceReference(Shape.FillProperty, SystemColors.DesktopBrushKey);

            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "GradientActiveCaption"};
            r = new Rectangle {Fill = SystemColors.GradientActiveCaptionBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "GradientInactiveCaption"};
            r = new Rectangle {Fill = SystemColors.GradientInactiveCaptionBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "GrayText"};
            r = new Rectangle {Fill = SystemColors.GrayTextBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "Highlight"};
            r = new Rectangle {Fill = SystemColors.HighlightBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "HighlightText"};
            r = new Rectangle {Fill = SystemColors.HighlightTextBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "HotTrack"};
            r = new Rectangle {Fill = SystemColors.HotTrackBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "InactiveBorder"};
            r = new Rectangle {Fill = SystemColors.InactiveBorderBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "InactiveCaption"};
            r = new Rectangle {Fill = SystemColors.InactiveCaptionBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "InactiveCaptionText"};
            r = new Rectangle {Fill = SystemColors.InactiveCaptionTextBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "Info"};
            r = new Rectangle {Fill = SystemColors.InfoBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "InfoText"};
            r = new Rectangle {Fill = SystemColors.InfoTextBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "Menu"};
            r = new Rectangle {Fill = SystemColors.MenuBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "MenuBar"};
            r = new Rectangle {Fill = SystemColors.MenuBarBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "MenuHighlight"};
            r = new Rectangle {Fill = SystemColors.MenuHighlightBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "MenuText"};
            r = new Rectangle {Fill = SystemColors.MenuTextBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "ScrollBar"};
            r = new Rectangle {Fill = SystemColors.ScrollBarBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            t = new TextBlock {Text = "Window"};
            r = new Rectangle {Fill = SystemColors.WindowBrush};
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(r);

            // Try it out on a button.
            t = new TextBlock {Text = "WindowFrame"};
            var b = new Button
            {
                Width = 120,
                Height = 20,
                Background = SystemColors.WindowFrameBrush
            };
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(b);

            t = new TextBlock {Text = "WindowText"};
            b = new Button
            {
                Width = 120,
                Height = 20,
                Background = SystemColors.WindowTextBrush
            };
            systemBrushesPanel.Children.Add(t);
            systemBrushesPanel.Children.Add(b);
        }

        // Demonstrates using system colors to create gradients.
        public void ListGradientExamples()
        {
            // The window style (defined in Window1.xaml) is used to
            // specify the height and width of each of the System.Windows.Shapes.Rectangles.

            var t = new TextBlock
            {
                Text = "System Color Gradient Examples",
                HorizontalAlignment = HorizontalAlignment.Left,
                FontWeight = FontWeights.Bold
            };
            gradientExamplePanel.Children.Add(t);

            t = new TextBlock {Text = "ControlDark to ControlLight"};
            var r = new Rectangle
            {
                Fill = new RadialGradientBrush(
                    SystemColors.ControlDarkColor, SystemColors.ControlLightColor)
            };
            gradientExamplePanel.Children.Add(t);
            gradientExamplePanel.Children.Add(r);

            t = new TextBlock {Text = "ControlDarkDark to ControlLightLight"};
            r = new Rectangle
            {
                Fill =
                    new LinearGradientBrush(SystemColors.ControlDarkDarkColor,
                        SystemColors.ControlLightLightColor, 45)
            };
            gradientExamplePanel.Children.Add(t);
            gradientExamplePanel.Children.Add(r);

            // Try it out on a button.
            t = new TextBlock {Text = "Desktop to AppWorkspace"};
            var b = new Button
            {
                Width = 120,
                Height = 20,
                Background =
                    new RadialGradientBrush(SystemColors.DesktopColor,
                        SystemColors.AppWorkspaceColor)
            };
            gradientExamplePanel.Children.Add(t);
            gradientExamplePanel.Children.Add(b);

            t = new TextBlock {Text = "Desktop to Control"};
            b = new Button
            {
                Width = 120,
                Height = 20,
                Background =
                    new RadialGradientBrush(SystemColors.DesktopColor,
                        SystemColors.ControlColor)
            };
            gradientExamplePanel.Children.Add(t);
            gradientExamplePanel.Children.Add(b);
        }
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/MailSettingsDialog.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace StickyNotesDemo
{
    /// <summary>
    ///     Interaction logic for MailSettingsDialog.xaml
    /// </summary>
    public class MailSettingsDialog : Window
    {
        private readonly DispatcherTimer _timerClock;

        public MailSettingsDialog()
        {
            WindowStyle = WindowStyle.None;
            Height = 250;
            Width = 600;
            Title = "SetUp Email Server";
            BorderBrush = Brushes.Transparent;
            BorderThickness = new Thickness(0);
            Background = Brushes.Transparent;


            var sp = new StackPanel {Background = Brushes.Transparent};

            var b = new Button
            {
                Background = Window2.ChangeBackgroundColor(Colors.SkyBlue),
                Height = 245
            };

            var tb = new TextBlock
            {
                Background = Brushes.Transparent,
                TextWrapping = TextWrapping.Wrap,
                FontFamily = new FontFamily("Bickham Script Pro")
            };
            tb.Typography.StylisticSet1 = true;
            tb.FontSize = 50;
            tb.HorizontalAlignment = HorizontalAlignment.Center;
            tb.TextAlignment = TextAlignment.Center;
            tb.Text = "Enter Mail Server Info In \r\nPreferences Window";

            b.Content = tb;
            b.Click += b_Click;

            sp.Children.Add(b);

            _timerClock = _timerClock = new DispatcherTimer();
            _timerClock.Interval = new TimeSpan(0, 0, 5);
            _timerClock.IsEnabled = true;
            _timerClock.Tick += TimerClock_Tick;

            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            Content = sp;
            Closing += MailSettingsDialog_Closing;
            ShowDialog();
        }

        private void MailSettingsDialog_Closing(object sender, CancelEventArgs e)
        {
        }

        private void b_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void TimerClock_Tick(object sender, EventArgs e)
        {
            _timerClock.IsEnabled = false;
            Close();
        }
    }
}

<|start_filename|>Accessibility/SelectionPattern/SelectionTarget/Target.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows.Forms;

namespace SelectionPatternTarget
{
    public partial class Target : Form
    {
        /// <summary>
        ///     The target application for the SelectionPattern Sample.
        /// </summary>
        public Target()
        {
            InitializeComponent();
        }

        /// <summary>
        ///     The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Target());
        }
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/FlashMode.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace PhotoViewerDemo
{
    public enum FlashMode
    {
        FlashFired,
        FlashDidNotFire
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/ExposureMode.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace PhotoViewerDemo
{
    public enum ExposureMode
    {
        Manual,
        NormalProgram,
        AperturePriority,
        ShutterPriority,
        LowSpeedMode,
        HighSpeedMode,
        PortraitMode,
        LandscapeMode,
        Unknown
    }
}

<|start_filename|>Accessibility/Highlighter/NativeMethods.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;

namespace Highlighter
{
    internal static class NativeMethods
    {
        internal const int GwlExstyle = -20;
        internal const int SwShowna = 8;
        internal const int WsExToolwindow = 0x00000080;
        // SetWindowPos constants (used by highlight rect)
        internal const int SwpNoactivate = 0x0010;
        internal static readonly IntPtr HwndTopmost = new IntPtr(-1);

        [DllImport("user32.dll")]
        internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        internal static extern bool SetWindowPos(
            IntPtr hWnd, IntPtr hwndAfter, int x, int y,
            int width, int height, int flags);

        [DllImport("user32.dll")]
        internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll")]
        internal static extern int SetWindowLong(IntPtr hWnd, int nIndex,
            int dwNewLong);

        [DllImport("user32.dll")]
        internal static extern bool SetProcessDPIAware();
    }
}

<|start_filename|>Windows/DialogBox/MarginValidationRule.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;
using System.Windows.Controls;

namespace DialogBox
{
    public class MarginValidationRule : ValidationRule
    {
        public double MinMargin { get; set; }
        public double MaxMargin { get; set; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            double margin;

            // Is a number?
            if (!double.TryParse((string) value, out margin))
            {
                return new ValidationResult(false, "Not a number.");
            }

            // Is in range?
            if ((margin < MinMargin) || (margin > MaxMargin))
            {
                var msg = $"Margin must be between {MinMargin} and {MaxMargin}.";
                return new ValidationResult(false, msg);
            }

            // Number is valid
            return new ValidationResult(true, null);
        }
    }
}

//</SnippetMarginValidationRuleCODE>

<|start_filename|>Data Binding/UpdateSource/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace UpdateSource
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Preview(object sender, RoutedEventArgs args)
        {
            // itemNameTextBox is an instance of a TextBox
            var be = itemNameTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            be = bidPriceTextBox.GetBindingExpression(TextBox.TextProperty);
            be.UpdateSource();

            userdata.Opacity = 1;
            Finish.Opacity = 1;
        }

        private void Submit(object sender, RoutedEventArgs args)
        {
            var userProfile = RootElem.DataContext as UserProfile;
            MessageBox.Show("Thank you for your bid of " + userProfile?.BidPrice
                            + " on item " + userProfile?.ItemName);
            userdata.Opacity = 0;
            Finish.Opacity = 0;
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/FunctionParser.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

//------------------------------------------------------------------

/*
    Metacharacters/Symbology:
    -------------------------
    < >    == Non-terminal
    { }*   == Kleene-star (0 or more occurrences)
    { }+   == Kleene-plus (1 or more occurrences)
    { }?   == Optional (0 or 1 occurrences)
    [ ]    == Madatory (1 must occur)
    |      == Vertical bar (logical OR)
    " "    == Terminal symbol (literal)

    The Grammar Rules:
    ------------------
    <start>        := <AddExp>
    <AddExp>       := <MultExp> { { "+" | "-" }? <MultExp> }*
    <MultExp>      := <ExpExp> { { "*" | "/" }? <ExpExp> }*
    <ExpExp>       := <UnaryExp> { { "^" }? <UnaryExp> }?
    <UnaryExp>     := { "-" }? <FactorPrefix>
    <FactorPrefix> := [ <Constant> { <Factor> }? | <Factor> ]
    <Factor>       := { <Variable> | <Function> | "(" <AddExp> ")" }+
    <Function>     := [ "sin" | "cos" | "tan" ] "(" <AddExp> ")"

    Non-terminals defined/parsed by Tokenizer:
    ------------------------------------------
    <Constant> := anything that can be parsed by Convert.ToDouble()
    <Variable> := any string containing only letters (a-z and A-Z)

    The algorithm:
    --------------
    Parsing is most easily performed when there is a 1:1 correspondence
    between non-terminals and functions.  Therefore, each private function
    below parses exactly one grammar rule.

    What do those odd "First" variables mean?
    -----------------------------------------
    The syntax checking algorithm decides whether syntax is correct
    by checking if the current token in the queue is expected.  I call
    the set of valid tokens to check against the "First" set because
    that's how we referred to it in my compiler class in school.  It
    could just as easily be referred to as the "NextValidTokenFor<blah>"
    set, but that's a little too verbose for code.
*/

namespace GraphingCalculatorDemo.Parser
{
    //--------------------------------------------------------------

    internal class FunctionParser
    {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static Tokenizer _tokenizer;
        private static Token _currentToken;
        private static TokenSet _firstAddExp;
        private static readonly TokenSet FirstMultExp;
        private static readonly TokenSet FirstExpExp;
        private static readonly TokenSet FirstUnaryExp;
        private static readonly TokenSet FirstFactorPrefix;
        private static readonly TokenSet FirstFactor;
        private static readonly TokenSet FirstFunction;
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        static FunctionParser()
        {
            FirstFunction = new TokenSet(TokenType.Sine | TokenType.Cosine | TokenType.Tangent);
            FirstFactor = FirstFunction + new TokenSet(TokenType.Variable | TokenType.OpenParen);
            FirstFactorPrefix = FirstFactor + TokenType.Constant;
            FirstUnaryExp = FirstFactorPrefix + TokenType.Minus;
            FirstExpExp = new TokenSet(FirstUnaryExp);
            FirstMultExp = new TokenSet(FirstUnaryExp);
            _firstAddExp = new TokenSet(FirstUnaryExp);
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        /// <summary>
        ///     Parse a string representation of a parametric function into an
        ///     expression tree that can be later evaluated.
        /// </summary>
        /// <param name="function">The function to parse</param>
        /// <returns>An expression tree representing the function parsed</returns>
        public static IExpression Parse(string function)
        {
            _tokenizer = new Tokenizer(function);
            _currentToken = new Token("", TokenType.None);

            if (!Next())
            {
                throw new InvalidExpressionException("Cannot parse an empty function");
            }
            var exp = ParseAddExpression();
            var leftover = string.Empty;
            while (_currentToken.Type != TokenType.Eof)
            {
                leftover += _currentToken.Value;
                Next();
            }
            if (!string.IsNullOrEmpty(leftover))
            {
                throw new TrailingTokensException("Trailing characters: " + leftover);
            }
            return exp;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static IExpression ParseAddExpression()
        {
            if (Check(FirstMultExp))
            {
                var exp = ParseMultExpression();

                while (Check(new TokenSet(TokenType.Plus | TokenType.Minus)))
                {
                    var opType = _currentToken.Type;
                    Eat(opType);
                    if (!Check(FirstMultExp))
                    {
                        throw new InvalidSyntaxException("Expected an expression after + or - operator");
                    }
                    var right = ParseMultExpression();

                    switch (opType)
                    {
                        case TokenType.Plus:
                            exp = new AddExpression(exp, right);
                            break;

                        case TokenType.Minus:
                            exp = new SubExpression(exp, right);
                            break;

                        default:
                            throw new UnexpectedBehaviorException("Expected plus or minus, got: " + opType);
                    }
                }

                return exp;
            }
            throw new InvalidSyntaxException("Invalid expression");
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static IExpression ParseMultExpression()
        {
            if (Check(FirstExpExp))
            {
                var exp = ParseExpExpression();

                while (Check(new TokenSet(TokenType.Multiply | TokenType.Divide)))
                {
                    var opType = _currentToken.Type;
                    Eat(opType);
                    if (!Check(FirstExpExp))
                    {
                        throw new InvalidSyntaxException("Expected an expression after * or / operator");
                    }
                    var right = ParseExpExpression();

                    switch (opType)
                    {
                        case TokenType.Multiply:
                            exp = new MultExpression(exp, right);
                            break;

                        case TokenType.Divide:
                            exp = new DivExpression(exp, right);
                            break;

                        default:
                            throw new UnexpectedBehaviorException("Expected mult or divide, got: " + opType);
                    }
                }

                return exp;
            }
            throw new InvalidSyntaxException("Invalid expression");
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static IExpression ParseExpExpression()
        {
            if (Check(FirstUnaryExp))
            {
                var exp = ParseUnaryExpression();

                if (Check(new TokenSet(TokenType.Exponent)))
                {
                    var opType = _currentToken.Type;
                    Eat(opType);
                    if (!Check(FirstUnaryExp))
                    {
                        throw new InvalidSyntaxException("Expected an expression after ^ operator");
                    }
                    var right = ParseUnaryExpression();

                    switch (opType)
                    {
                        case TokenType.Exponent:
                            exp = new ExpExpression(exp, right);
                            break;

                        default:
                            throw new UnexpectedBehaviorException("Expected exponent, got: " + opType);
                    }
                }

                return exp;
            }
            throw new InvalidSyntaxException("Invalid expression");
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static IExpression ParseUnaryExpression()
        {
            var negate = false;
            if (_currentToken.Type == TokenType.Minus)
            {
                Eat(TokenType.Minus);
                negate = true;
            }

            if (Check(FirstFactorPrefix))
            {
                var exp = ParseFactorPrefix();

                if (negate)
                {
                    return new NegateExpression(exp);
                }
                return exp;
            }
            throw new InvalidSyntaxException("Invalid expression");
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static IExpression ParseFactorPrefix()
        {
            IExpression exp = null;
            if (_currentToken.Type == TokenType.Constant)
            {
                exp = new ConstantExpression(Convert.ToDouble(_currentToken.Value));
                Eat(TokenType.Constant);
            }

            if (Check(FirstFactor))
            {
                if (exp == null)
                {
                    return ParseFactor();
                }
                return new MultExpression(exp, ParseFactor());
            }
            // This should be impossible because bad symbols are caught by Tokenizer,
            //  constants would have been parsed in the if-statement above, and
            //  anything else is treated as a Factor (UndefinedVariableException
            //  will be thrown when you try to evaluate the function).
            if (exp == null)
            {
                throw new InvalidSyntaxException("Invalid Expression");
            }
            return exp;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static IExpression ParseFactor()
        {
            IExpression exp = null;
            do
            {
                IExpression right = null;
                switch (_currentToken.Type)
                {
                    case TokenType.Variable:
                        right = new VariableExpression(_currentToken.Value);
                        Eat(TokenType.Variable);
                        break;

                    case TokenType.Sine:
                    case TokenType.Cosine:
                    case TokenType.Tangent:
                        right = ParseFunction();
                        break;

                    case TokenType.OpenParen:
                        Eat(TokenType.OpenParen);
                        right = ParseAddExpression();
                        Eat(TokenType.CloseParen);
                        break;

                    default:
                        throw new UnexpectedBehaviorException("Unexpected token in Factor: " + _currentToken.Type);
                }

                exp = (exp == null) ? right : new MultExpression(exp, right);
            } while (Check(FirstFactor));

            return exp;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private static IExpression ParseFunction()
        {
            var opType = _currentToken.Type;
            Eat(opType);
            Eat(TokenType.OpenParen);
            var exp = ParseAddExpression();
            Eat(TokenType.CloseParen);

            switch (opType)
            {
                case TokenType.Sine:
                    return new SineExpression(exp);

                case TokenType.Cosine:
                    return new CosineExpression(exp);

                case TokenType.Tangent:
                    return new TangentExpression(exp);

                default:
                    throw new UnexpectedBehaviorException("Unexpected Function type: " + opType);
            }
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        /// <summary>
        ///     Assign the next token in the queue to CurrentToken
        /// </summary>
        /// <returns>
        ///     true if there are still more tokens in the queue,
        ///     false if we have looked at all available tokens already
        /// </returns>
        private static bool Next()
        {
            if (_currentToken.Type == TokenType.Eof)
            {
                throw new OutOfTokensException("Parsed past the end of the function");
            }
            _currentToken = _tokenizer.Next();

            return _currentToken.Type != TokenType.Eof;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        /// <summary>
        ///     Assign the next token in the queue to CurrentToken if the CurrentToken's
        ///     type matches that of the specified parameter.  If the CurrentToken's
        ///     type does not match the parameter, throw a syntax exception
        /// </summary>
        /// <param name="type">The type that your syntax expects CurrentToken to be</param>
        private static void Eat(TokenType type)
        {
            if (_currentToken.Type != type)
            {
                throw new InvalidSyntaxException("Missing: " + type);
            }
            Next();
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        /// <summary>
        ///     Check if the CurrentToken is a member of a set Token types
        /// </summary>
        /// <param name="tokens">The set of Token types to check against</param>
        /// <returns>
        ///     true if the CurrentToken's type is in the set
        ///     false if it is not
        /// </returns>
        private static bool Check(TokenSet tokens) => tokens.Contains(_currentToken.Type);
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/Tokenizer.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Globalization;

namespace GraphingCalculatorDemo.Parser
{
    //--------------------------------------------------------------

    public class Tokenizer
    {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private readonly string _function;
        private int _index;
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public Tokenizer(string function)
        {
            if (function == null)
            {
                function = string.Empty;
            }
            _function = function;
            _index = 0;
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public Token Next()
        {
            while (_index < _function.Length)
            {
                if (IsNumber(_function[_index]))
                {
                    var val = string.Empty;
                    val += _function[_index++];
                    while (_index < _function.Length && IsNumber(_function[_index]))
                    {
                        val += _function[_index++];
                    }
                    return new Token(val, TokenType.Constant);
                }
                if (IsAlpha(_function[_index]))
                {
                    var var = string.Empty;
                    var += _function[_index++];
                    while (_index < _function.Length && IsAlpha(_function[_index]))
                    {
                        var += _function[_index++];
                    }
                    switch (var.ToLower(CultureInfo.InvariantCulture))
                    {
                        case "sin":
                            return new Token("sin", TokenType.Sine);
                        case "cos":
                            return new Token("cos", TokenType.Cosine);
                        case "tan":
                            return new Token("tan", TokenType.Tangent);
                        default:
                            return new Token(var, TokenType.Variable);
                    }
                }
                switch (_function[_index++])
                {
                    case ' ':
                    case '\t':
                    case '\r':
                    case '\n':
                        continue;

                    case '+':
                        return new Token("+", TokenType.Plus);
                    case '-':
                        return new Token("-", TokenType.Minus);
                    case '*':
                        return new Token("*", TokenType.Multiply);
                    case '/':
                        return new Token("/", TokenType.Divide);
                    case '^':
                        return new Token("^", TokenType.Exponent);
                    case '(':
                        return new Token("(", TokenType.OpenParen);
                    case ')':
                        return new Token(")", TokenType.CloseParen);
                    default:
                        throw new InvalidSyntaxException("Invalid token '" + _function[_index - 1] + "' in function: " +
                                                         _function);
                }
            }
            return new Token("", TokenType.Eof);
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private bool IsAlpha(char c) => (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'));

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        private bool IsNumber(char c) => ('.' == c || ('0' <= c && c <= '9'));
    }
}

<|start_filename|>Graphics/BitmapEffectsGallery/BevelInteractiveExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Effects;

namespace SDKSample
{
    public partial class BevelInteractiveExample : Page
    {
        private void ChangeSelection(object sender, RoutedEventArgs args)
        {
            var cb = (ComboBox) sender;
            var cbi = (ComboBoxItem) cb.SelectedValue;

            var s = cbi.Content.ToString();
            switch (s)
            {
                case "BulgedUp":
                    InteractiveEffect.EdgeProfile = EdgeProfile.BulgedUp;
                    break;
                case "CurvedIn":
                    InteractiveEffect.EdgeProfile = EdgeProfile.CurvedIn;
                    break;
                case "CurvedOut":
                    InteractiveEffect.EdgeProfile = EdgeProfile.CurvedOut;
                    break;
                case "Linear":
                    InteractiveEffect.EdgeProfile = EdgeProfile.Linear;
                    break;
            }
        }
    }
}

<|start_filename|>Sample Applications/StickyNotesDemo/Email.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace StickyNotesDemo
{
    internal class Email
    {
        private readonly SmtpClient _client;
        private readonly EmailDialog _dia;
        private readonly MailMessage _message;

        public Email(string server, string login, int port, bool sslCheck, string toAddr, string fromAddr,
            string password,
            string bodyMessage, EmailDialog emailDia, string subject)
        {
            _dia = emailDia;
            try
            {
                var nw = new NetworkCredential(login, password);
                // Command line argument must be the SMTP host.
                _client = new SmtpClient(server)
                {
                    Credentials = nw,
                    EnableSsl = sslCheck ? true : false
                };
                // Specify the e-mail sender.
                // Create a mailing address that includes a UTF8 character
                // in the display name.

                var from = new MailAddress(fromAddr, "", Encoding.UTF8);
                _client.Port = port;
                // Set destinations for the e-mail message.
                var to = new MailAddress(toAddr);
                // Specify the message content.
                _message = new MailMessage(from, to)
                {
                    Body = bodyMessage,
                    Subject = subject,
                    SubjectEncoding = Encoding.UTF8
                };


                // Set the method that is called back when the send operation ends.
                _client.SendCompleted += SendCompletedCallback;
                // The userState can be any object that allows your callback 
                // method to identify this send operation.
                // For this example, the userToken is a string constant.
                var userState = "Sticky note message";
                _client.SendAsync(_message, userState);
            }
            catch (Exception e)
            {
                CreateDialog(e.Message);
            }
        }

        public bool MailSent { get; private set; }

        public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            var token = (string) e.UserState;


            if (e.Error != null)
            {
                _client.SendAsyncCancel();
                CreateDialog(e.Error.ToString());
                MailSent = false;
            }
            else
            {
                CreateDialog("Message Sent");
                MailSent = true;
                _dia.Close();
            }
            _message.Dispose();
        }

        private static void CreateDialog(string msg)
        {
            var w = new Window();
            var sp = new StackPanel {Background = Brushes.Transparent};
            var tb = new TextBlock
            {
                Background = sp.Background,
                TextWrapping = TextWrapping.Wrap,
                Text = msg
            };
            sp.Children.Add(tb);

            w.Content = sp;
            w.WindowStyle = WindowStyle.ToolWindow;
            w.Background = Window2.ChangeBackgroundColor(Colors.Wheat);
            w.Height = 250;
            w.Width = 600;
            w.ShowDialog();
        }
    }
}

<|start_filename|>Graphics/Brushes/DoubleToStringConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace Brushes
{
    [ValueConversion(typeof (double), typeof (string))]
    public class DoubleToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var d = (double) value;
            return d.ToString("F4");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                return double.Parse((string) value);
            }
            catch (InvalidOperationException)
            {
                return null;
            }
        }
    }
}

<|start_filename|>Styles & Templates/IntroToStylingAndTemplating/Photo.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace IntroToStylingAndTemplating
{
    public class Photo
    {
        public Photo(string path)
        {
            Source = path;
        }

        public string Source { get; }

        public override string ToString() => Source;
    }
}

<|start_filename|>Graphics/AITCodec/cpp/registryvaluemanager.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------
//  Description: Declaration and Definition of RegistryValueManager
//----------------------------------------------------------------------------------------
#pragma once


class RegistryValueManager
{
public:
    HRESULT Register()
    {
        return PopulateValues();
    }

    HRESULT Unregister()
    {
        HRESULT result = S_OK;
        Register();
        while (keys.size() > 0)
        {
            RegDeleteKeyA(HKEY_CLASSES_ROOT, keys.back());
            keys.pop_back();
        }

        return result;
    }

protected:
    virtual HRESULT PopulateValues() = 0;

    HRESULT Val(LPCSTR keyName, LPCSTR valueName, LPCSTR value)
    {
        return Val(keyName, valueName, REG_SZ, reinterpret_cast<const BYTE*>(value), strlen(value) + 1);
    }

    HRESULT Val(LPCSTR keyName, LPCSTR valueName, DWORD value)
    {
        return Val(keyName, valueName, REG_DWORD, reinterpret_cast<const BYTE*>(&value), sizeof(DWORD));
    }

    HRESULT Val(LPCSTR keyName, LPCSTR valueName, const BYTE *data, DWORD size)
    {
        return Val(keyName, valueName, REG_BINARY, data, size);
    }

private:
    HRESULT Val(LPCSTR keyName, LPCSTR valueName, DWORD type, const BYTE *data, DWORD size)
    {
        HRESULT result = S_OK;
        HKEY hkey;

        keys.push_back(keyName);
        long err = RegCreateKeyA(HKEY_CLASSES_ROOT, keyName, &hkey);
        if (ERROR_SUCCESS == err)
        {
            err = RegSetValueExA(hkey, valueName, 0, type, data, size);
            RegCloseKey(hkey);
        }
        else
        {
            result = E_FAIL;
        }
        return result;
    }
    std::vector<LPCSTR> keys;
};


<|start_filename|>Application Management/ExceptionHandlingSecondaryUIThread/SecondaryUIThreadWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Threading;
using System.Windows;

namespace ExceptionHandlingSecondaryUIThread
{
    /// <summary>
    ///     Interaction logic for SecondaryUIThreadWindow.xaml
    /// </summary>
    public partial class SecondaryUIThreadWindow : Window
    {
        public SecondaryUIThreadWindow()
        {
            InitializeComponent();
            Title = $"Running on Secondary UI Thread {Thread.CurrentThread.ManagedThreadId}";
        }

        private void raiseExceptionOnSecondaryUIThreadButton_Click(object sender, RoutedEventArgs e)
        {
            // Raise an exception on the secondary UI thread
            string msg = $"Exception raised on secondary UI thread {Dispatcher.Thread.ManagedThreadId}.";
            throw new Exception(msg);
        }

        private void SecondaryUIThreadWindow_OnClosed(object sender, EventArgs e)
        {
            // End this thread of execution
            Dispatcher.InvokeShutdown();
        }
    }
}

<|start_filename|>Application Management/ProcessingCommandLineArguments/App.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Windows;

namespace ProcessingCommandLineArguments
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static Hashtable CommandLineArgs = new Hashtable();

        private void App_Startup(object sender, StartupEventArgs e)
        {
            // Don't bother if no command line args were passed
            // NOTE: e.Args is never null - if no command line args were passed, 
            //       the length of e.Args is 0.
            if (e.Args.Length == 0) return;

            // Parse command line args for args in the following format:
            //   /argname:argvalue /argname:argvalue /argname:argvalue ...
            //
            // Note: This sample uses regular expressions to parse the command line arguments.
            // For regular expressions, see:
            // http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconRegularExpressionsLanguageElements.asp
            var pattern = @"(?<argname>/\w+):(?<argvalue>\w+)";
            foreach (var arg in e.Args)
            {
                var match = Regex.Match(arg, pattern);

                // If match not found, command line args are improperly formed.
                if (!match.Success)
                    throw new ArgumentException(
                        "The command line arguments are improperly formed. Use /argname:argvalue.");

                // Store command line arg and value
                CommandLineArgs[match.Groups["argname"].Value] = match.Groups["argvalue"].Value;
            }
        }
    }
}

<|start_filename|>Getting Started/Concepts/samps/stretch_samp.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace myStretch //needs to match the .xaml page
{
    public partial class Page1 : Page
    {
        private ToolTip _ttp;
        // This function checks the language filter settings to see which code to filter and also grays out tabs with no content
        public void CheckLang(object sender, EventArgs e)
        {
            if (xcsharpCheck.Content == null) // grays out xaml + c# tab
            {
                xamlcsharp.Background = Brushes.Gainsboro;
                xamlcsharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlcsharp, true);
                _ttp.Content = "This sample is not available in XAML + C#.";
                xamlcsharp.ToolTip = (_ttp);
                xamlcsharp.IsEnabled = false;
            }
            else if (xcsharpCheck.Content != null)
            {
                xamlcsharp.IsEnabled = true;
            }

            if (xvbCheck.Content == null) // grays out xaml + vb tab
            {
                xamlvb.Background = Brushes.Gainsboro;
                xamlvb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlvb, true);
                _ttp.Content = "This sample is not available in XAML + Visual Basic.NET";
                xamlvb.ToolTip = (_ttp);
                xamlvb.IsEnabled = false;
            }
            else if (xvbCheck.Content != null)
            {
                xamlvb.IsEnabled = true;
            }

            if (xaml.Content == null) // grays out xaml
            {
                xaml.IsEnabled = false;
                xaml.Background = Brushes.Gainsboro;
                xaml.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xaml, true);
                _ttp.Content = "This sample is not available in XAML.";
                xaml.ToolTip = (_ttp);
            }
            else if (xaml.Content != null)
            {
                xaml.IsEnabled = true;
            }

            if (csharp.Content == null) // grays out c#
            {
                csharp.IsEnabled = false;
                csharp.Background = Brushes.Gainsboro;
                csharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(csharp, true);
                _ttp.Content = "This sample is not available in C#.";
                csharp.ToolTip = (_ttp);
            }
            else if (csharp.Content != null)
            {
                csharp.IsEnabled = true;
            }

            if (vb.Content == null) // grays out vb
            {
                vb.IsEnabled = false;
                vb.Background = Brushes.Gainsboro;
                vb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(vb, true);
                _ttp.Content = "This sample is not available in Visual Basic.NET.";
                vb.ToolTip = (_ttp);
            }
            else if (vb.Content != null)
            {
                vb.IsEnabled = true;
            }

            if (managedcpp.Content == null) // grays out cpp
            {
                managedcpp.IsEnabled = false;
                managedcpp.Background = Brushes.Gainsboro;
                managedcpp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(managedcpp, true);
                _ttp.Content = "This sample is not available in Managed C++.";
                managedcpp.ToolTip = (_ttp);
            }
            else if (managedcpp.Content != null)
            {
                managedcpp.IsEnabled = true;
            }
            if (Welcome.Page1.MyDouble == 1) // XAML only
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 2) // CSharp
            {
                csharp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 3) // Visual Basic
            {
                vb.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 4) // Managed CPP
            {
                managedcpp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 5) // No Filter
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Visible;
                vb.Visibility = Visibility.Visible;
                managedcpp.Visibility = Visibility.Visible;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Visible;
            }
            else if (Welcome.Page1.MyDouble == 6) // XAML + CSharp
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 7) // XAML + VB
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Visible;
            }
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/classfactory.h<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------

//----------------------------------------------------------------------------------------
//  Description: Declaration and Definition of TestClassFactory
//----------------------------------------------------------------------------------------
#pragma once

#include "UnknownImpl.h"

template< typename T >
class TestClassFactory : public IClassFactory
{
public:
    // IUnknown Interface
    STDMETHOD(QueryInterface)(REFIID riid, void **ppv)
    {
        HRESULT result = E_INVALIDARG;

        if (ppv)
        {
            if (riid == IID_IUnknown)
            {
                *ppv = static_cast<IUnknown*>(this);
                AddRef();

                result = S_OK;
            }
            else if (riid == IID_IClassFactory)
            {
                *ppv = static_cast<IClassFactory*>(this);
                AddRef();

                result = S_OK;
            }
            else
            {
                result = E_NOINTERFACE;
            }
        }

        return result;
    }

    STDMETHOD_(ULONG, AddRef)()
    {
        return unknownImpl.AddRef();
    
    }

    STDMETHOD_(ULONG, Release)()
    {
        ULONG result = unknownImpl.Release();
        if (0 == result)
        {
            delete this;
        }
        return result;
    }

    // IClassFactory Interface
    STDMETHOD(CreateInstance)(IUnknown *pUnkOuter, REFIID riid, void **ppv)
    {
        HRESULT result = E_INVALIDARG;

        if (NULL != ppv)
        {
            T *obj = new T();

            if (NULL != obj)
            {
                result = obj->QueryInterface(riid, ppv);
            }
            else
            {
                *ppv = NULL;
                result = E_OUTOFMEMORY;
            }
        }

        return result;
    }

    STDMETHOD(LockServer)(BOOL fLock)
    {
        return CoLockObjectExternal(this, fLock, FALSE);
    }

private:
    UnknownImpl unknownImpl;
};



<|start_filename|>Visual Layer/DrawingVisual/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;

namespace DrawingVisual
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private void WindowLoaded(object sender, EventArgs e)
        {
            var visualHost = new MyVisualHost();
            MyCanvas.Children.Add(visualHost);
        }
    }

    // Create a host visual derived from the FrameworkElement class.
    // This class provides layout, event handling, and container support for
    // the child visual objects.
}

<|start_filename|>Sample Applications/ExpenseIt/EditBoxControlLibrary/EditBox.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

// Type
// DependencyProperty, RoutedEventArgs, DependencyObject, FrameworkElement
// Control
// Debug
// AdornerLayer
// MouseEventArgs, MouseEventButtonArgs, KeyEventArgs, KeyboardFocusChangedEventArgs

// VisualTreeHelper

namespace EditBoxControlLibrary
{
    /// <summary>
    ///     EditBox is a custom cotrol that can switch between two modes:
    ///     editing and normal. When it is in editing mode, the content is
    ///     displayed in a TextBox that provides editing capbability. When
    ///     the EditBox is in normal, its content is displayed in a TextBlock
    ///     that is not editable.
    ///     This control is designed to be used in with a GridView View.
    /// </summary>
    public class EditBox : Control
    {
        #region Static Constructor

        /// <summary>
        ///     Static constructor
        /// </summary>
        static EditBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof (EditBox),
                new FrameworkPropertyMetadata(typeof (EditBox)));
        }

        #endregion

        #region Public Methods

        /// <summary>
        ///     Called when the tree for the EditBox has been generated.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            var textBlock = GetTemplateChild("PART_TextBlockPart") as TextBlock;
            Debug.Assert(textBlock != null, "No TextBlock!");

            _textBox = new TextBox();
            _adorner = new EditBoxAdorner(textBlock, _textBox);
            var layer = AdornerLayer.GetAdornerLayer(textBlock);
            layer.Add(_adorner);

            _textBox.KeyDown += OnTextBoxKeyDown;
            _textBox.LostKeyboardFocus +=
                OnTextBoxLostKeyboardFocus;

            //Receive notification of the event to handle the column 
            //resize. 
            HookTemplateParentResizeEvent();

            //Capture the resize event to  handle ListView resize cases.
            HookItemsControlEvents();

            _listViewItem = GetDependencyObjectFromVisualTree(this,
                typeof (ListViewItem)) as ListViewItem;

            Debug.Assert(_listViewItem != null, "No ListViewItem found");
        }

        #endregion

        #region Protected Methods

        /// <summary>
        ///     If the ListViewItem that contains the EditBox is selected,
        ///     when the mouse pointer moves over the EditBox, the corresponding
        ///     MouseEnter event is the first of two events (MouseUp is the second)
        ///     that allow the EditBox to change to editing mode.
        /// </summary>
        protected override void OnMouseEnter(MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            if (!IsEditing && IsParentSelected)
            {
                _canBeEdit = true;
            }
        }

        /// <summary>
        ///     If the MouseLeave event occurs for an EditBox control that
        ///     is in normal mode, the mode cannot be changed to editing mode
        ///     until a MouseEnter event followed by a MouseUp event occurs.
        /// </summary>
        protected override void OnMouseLeave(MouseEventArgs e)
        {
            base.OnMouseLeave(e);
            _isMouseWithinScope = false;
            _canBeEdit = false;
        }

        /// <summary>
        ///     An EditBox switches to editing mode when the MouseUp event occurs
        ///     for that EditBox and the following conditions are satisfied:
        ///     1. A MouseEnter event for the EditBox occurred before the
        ///     MouseUp event.
        ///     2. The mouse did not leave the EditBox between the
        ///     MouseEnter and MouseUp events.
        ///     3. The ListViewItem that contains the EditBox was selected
        ///     when the MouseEnter event occurred.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseUp(MouseButtonEventArgs e)
        {
            base.OnMouseUp(e);

            if (e.ChangedButton == MouseButton.Right ||
                e.ChangedButton == MouseButton.Middle)
                return;

            if (!IsEditing)
            {
                if (!e.Handled && (_canBeEdit || _isMouseWithinScope))
                {
                    IsEditing = true;
                }

                //If the first MouseUp event selects the parent ListViewItem,
                //then the second MouseUp event puts the EditBox in editing 
                //mode
                if (IsParentSelected)
                    _isMouseWithinScope = true;
            }
        }

        #endregion

        #region Public Properties

        #region Value

        /// <summary>
        ///     ValueProperty DependencyProperty.
        /// </summary>
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register(
                "Value",
                typeof (object),
                typeof (EditBox),
                new FrameworkPropertyMetadata(null));

        /// <summary>
        ///     Gets or sets the value of the EditBox
        /// </summary>
        public object Value
        {
            get { return GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        #endregion

        #region IsEditing

        /// <summary>
        ///     IsEditingProperty DependencyProperty
        /// </summary>
        public static DependencyProperty IsEditingProperty =
            DependencyProperty.Register(
                "IsEditing",
                typeof (bool),
                typeof (EditBox),
                new FrameworkPropertyMetadata(false));

        /// <summary>
        ///     Returns true if the EditBox control is in editing mode.
        /// </summary>
        public bool IsEditing
        {
            get { return (bool) GetValue(IsEditingProperty); }
            private set
            {
                SetValue(IsEditingProperty, value);
                _adorner.UpdateVisibilty(value);
            }
        }

        #endregion

        #region IsParentSelected

        /// <summary>
        ///     Gets whether the ListViewItem that contains the
        ///     EditBox is selected.
        /// </summary>
        private bool IsParentSelected
        {
            get
            {
                if (_listViewItem == null)
                    return false;
                return _listViewItem.IsSelected;
            }
        }

        #endregion

        #endregion

        #region Private Methods

        /// <summary>
        ///     When an EditBox is in editing mode, pressing the ENTER or F2
        ///     keys switches the EditBox to normal mode.
        /// </summary>
        private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
        {
            if (IsEditing && (e.Key == Key.Enter || e.Key == Key.F2))
            {
                IsEditing = false;
                _canBeEdit = false;
            }
        }

        /// <summary>
        ///     If an EditBox loses focus while it is in editing mode,
        ///     the EditBox mode switches to normal mode.
        /// </summary>
        private void OnTextBoxLostKeyboardFocus(object sender,
            KeyboardFocusChangedEventArgs e)
        {
            IsEditing = false;
        }

        /// <summary>
        ///     Sets IsEditing to false when the ListViewItem that contains an
        ///     EditBox changes its size
        /// </summary>
        private void OnCouldSwitchToNormalMode(object sender,
            RoutedEventArgs e)
        {
            IsEditing = false;
        }

        /// <summary>
        ///     Walk the visual tree to find the ItemsControl and
        ///     hook its some events on it.
        /// </summary>
        private void HookItemsControlEvents()
        {
            _itemsControl = GetDependencyObjectFromVisualTree(this,
                typeof (ItemsControl)) as ItemsControl;
            if (_itemsControl != null)
            {
                //Handle the Resize/ScrollChange/MouseWheel 
                //events to determine whether to switch to Normal mode
                _itemsControl.SizeChanged +=
                    OnCouldSwitchToNormalMode;
                _itemsControl.AddHandler(ScrollViewer.ScrollChangedEvent,
                    new RoutedEventHandler(OnScrollViewerChanged));
                _itemsControl.AddHandler(MouseWheelEvent,
                    new RoutedEventHandler(OnCouldSwitchToNormalMode), true);
            }
        }

        /// <summary>
        ///     If an EditBox is in editing mode and the content of a ListView is
        ///     scrolled, then the EditBox switches to normal mode.
        /// </summary>
        private void OnScrollViewerChanged(object sender, RoutedEventArgs args)
        {
            if (IsEditing && Mouse.PrimaryDevice.LeftButton ==
                MouseButtonState.Pressed)
            {
                IsEditing = false;
            }
        }

        /// <summary>
        ///     Walk visual tree to find the first DependencyObject
        ///     of the specific type.
        /// </summary>
        private DependencyObject
            GetDependencyObjectFromVisualTree(DependencyObject startObject,
                Type type)
        {
            //Walk the visual tree to get the parent(ItemsControl) 
            //of this control
            var parent = startObject;
            while (parent != null)
            {
                if (type.IsInstanceOfType(parent))
                    break;
                parent = VisualTreeHelper.GetParent(parent);
            }

            return parent;
        }

        /// <summary>
        ///     When the size of the column containing the EditBox changes
        ///     and the EditBox is in editing mode, switch the mode to normal mode
        /// </summary>
        private void HookTemplateParentResizeEvent()
        {
            var parent = TemplatedParent as FrameworkElement;
            if (parent != null)
            {
                parent.SizeChanged +=
                    OnCouldSwitchToNormalMode;
            }
        }

        #endregion

        #region private variable

        private EditBoxAdorner _adorner;
        //A TextBox in the visual tree
        private FrameworkElement _textBox;
        //Specifies whether an EditBox can switch to editing mode.
        //Set to true if the ListViewItem that contains the EditBox is
        //selected, and the mouse pointer moves over the EditBox.
        private bool _canBeEdit;
        //Specifies whether an EditBox can switch to editing mode.
        //Set to true if the ListViewItem that contains the EditBox is
        //selected, the mouse pointer is over the EditBox, and MouseUp
        //event occurs for the left mouse button.
        private bool _isMouseWithinScope;
        //The ListView control that contains the EditBox
        private ItemsControl _itemsControl;
        //The ListViewItem control that contains the EditBox
        private ListViewItem _listViewItem;

        #endregion
    }
}


<|start_filename|>Sample Applications/PhotoStoreDemo/Print.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Media.Imaging;

namespace PhotoStoreDemo
{
    public class Print : PrintBase
    {
        public Print(BitmapSource photo) : base(photo, "4x6 Print", 0.15)
        {
        }
    }
}

<|start_filename|>Animation/CustomAnimation/CustomAnimationExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace CustomAnimation
{
    /// <summary>
    ///     Interaction logic for Window1.xaml
    /// </summary>
    public partial class CustomAnimationExample : Window
    {
        public CustomAnimationExample()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Tools/BamlReflector/BamlReflector/BamlReflectorContext.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BamlTools;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xaml;

namespace BamlReflector
{
    public class BamlReflectorContext : INotifyPropertyChanged
    {
        Assembly _assembly = null;
        private readonly ObservableCollection<ReferenceAssembly_VM> _referenceAssemblies;
        private readonly ObservableCollection<ReferenceAssembly_VM> _loadedReferenceAssemblies;
        bool _hideTableDefinitions;
        BamlResource _currentBamlResource;
        bool _showAddresses;
        bool _showRecordNumbers;
        bool _showDebugRecords;
        bool _showTableRecords;

        NewDisassemblyCache _newDisassemblyCache;

        public BamlReflectorContext()
        {
            _referenceAssemblies = new ObservableCollection<ReferenceAssembly_VM>();
            _loadedReferenceAssemblies = new ObservableCollection<ReferenceAssembly_VM>();
            _referenceAssemblies.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ReferenceAssemblies_CollectionChanged);
            _showAddresses = true;
            _showRecordNumbers = true;
            _showDebugRecords = true;
            _showTableRecords = true;
        }

        //  INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;

        public Assembly LocalAssembly
        {
            get { return _assembly; }
            set
            {
                if (_assembly != value)
                {
                    _assembly = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("LocalAssembly"));
                }
            }
        }

        public ObservableCollection<ReferenceAssembly_VM> ReferenceAssemblies
        {
            get { return _referenceAssemblies; }
        }

        // Loaded Reference assemblies should be the same as reference asseblies  (todo remove dup functionality)
        public ObservableCollection<ReferenceAssembly_VM> LoadedReferenceAssemblies
        {
            get { return _loadedReferenceAssemblies; }
        }

        public bool HideTableDefinitions
        {
            get { return _hideTableDefinitions; }
            set
            {
                if (value != _hideTableDefinitions)
                {
                    _hideTableDefinitions = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("HideTableDefinitions"));
                }
            }
        }

        public BamlResource CurrentBamlResource
        {
            get { return _currentBamlResource; }
            set
            {
                _currentBamlResource = value;
                _newDisassemblyCache = null;
                PropertyChanged(this, new PropertyChangedEventArgs("HexDump"));
                PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_Old"));
                PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_New"));
                PropertyChanged(this, new PropertyChangedEventArgs("XamlNodeStream"));
                PropertyChanged(this, new PropertyChangedEventArgs("XamlText"));
                PropertyChanged(this, new PropertyChangedEventArgs("TypeInfoTable"));
                PropertyChanged(this, new PropertyChangedEventArgs("AttributeInfoTable"));
            }
        }

        public bool ShowAddresses
        {
            get { return _showAddresses; }
            set
            {
                if (_showAddresses != value)
                {
                    _showAddresses = value;
                    _newDisassemblyCache = null;
                    PropertyChanged(this, new PropertyChangedEventArgs("HexDump"));
                    PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_Old"));
                    PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_New"));
                }
            }
        }

        public bool ShowRecordNumbers
        {
            get { return _showRecordNumbers; }
            set
            {
                if (_showRecordNumbers != value)
                {
                    _showRecordNumbers = value;
                    _newDisassemblyCache = null;
                    PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_Old"));
                    PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_New"));
                }
            }
        }

        public bool ShowDebugRecords
        {
            get { return _showDebugRecords; }
            set
            {
                if (_showDebugRecords != value)
                {
                    _showDebugRecords = value;
                    _newDisassemblyCache = null;
                    PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_New"));
                }
            }
        }

        public bool ShowTableRecords
        {
            get { return _showTableRecords; }
            set
            {
                if (_showTableRecords != value)
                {
                    _showTableRecords = value;
                    _newDisassemblyCache = null;
                    PropertyChanged(this, new PropertyChangedEventArgs("BamlDisassembly_New"));
                }
            }
        }

        public string HexDump
        {
            get
            {
                if (CurrentBamlResource != null)
                {
                    Stream stream = CurrentBamlResource.Stream;
                    stream.Seek(0, SeekOrigin.Begin);
                    HexDumper dumper = new HexDumper(stream)
                    {
                        ShowAddresses = ShowAddresses
                    };
                    //dumper.ShowRecordNumbers = ShowRecordNumbers;  not-implemented on HexDumper
                    //dumper.ShowDebugRecords = ShowDebugRecords;    not-implemented on HexDumper
                    //dumper.ShowTableRecords = ShowTableRecords;    not-implemented on HexDumper
                    return dumper.DumpOneBigString();
                }
                return String.Empty;
            }
        }

        public string BamlDisassembly_Old
        {
            get
            {
                if (CurrentBamlResource != null && CurrentBamlResource.IsBaml)
                {
                    Stream stream = CurrentBamlResource.Stream;
                    stream.Seek(0, SeekOrigin.Begin);
                    OldBamlDisassembler dasm = new OldBamlDisassembler(stream)
                    {
                        ShowAddresses = ShowAddresses,
                        ShowRecordNumbers = ShowRecordNumbers,
                        ShowDebugRecords = ShowDebugRecords,  // Not implemented
                        ShowTableRecords = ShowTableRecords  // Not implemented
                    };
                    return dasm.DasmOneBigString();
                }
                return String.Empty;
            }
        }

        public string BamlDisassembly_New
        {
            get
            {
                if (CurrentBamlResource != null && CurrentBamlResource.IsBaml)
                {
                    EnsureBamlResourceLoad();
                    return _newDisassemblyCache.Disassembly;
                }

                return String.Empty;
            }
        }

        public string XamlNodeStream
        {
            get
            {
                if (CurrentBamlResource != null)
                {
                    Stream stream = CurrentBamlResource.Stream;
                    stream.Seek(0, SeekOrigin.Begin);

                    if (CurrentBamlResource.IsBaml)
                    {
                        BamlNodeStreamReader bamlNodeStreamReader = new BamlNodeStreamReader(stream, LocalAssembly);
                        return bamlNodeStreamReader.OneBigString();
                    }
                    else
                    {
                        using XamlXmlReader reader = new XamlXmlReader(stream);
                        StringBuilder sb = new StringBuilder();
                        DiagnosticWriter writer = new DiagnosticWriter(sb, reader.SchemaContext);
                        try
                        {
                            XamlServices.Transform(reader, writer);
                        }
                        catch (Exception ex)
                        {
                            sb.AppendLine(ex.ToString());
                        }
                        return sb.ToString();
                    }
                }
                return String.Empty;
            }
        }

        public string XamlText
        {
            get
            {
                if (CurrentBamlResource != null)
                {
                    Stream stream = CurrentBamlResource.Stream;
                    stream.Seek(0, SeekOrigin.Begin);

                    if (CurrentBamlResource.IsBaml)
                    {
                        BamlToXamlReader bamlToXamlReader = new BamlToXamlReader(stream, LocalAssembly);
                        string xamlOrError;
                        try
                        {
                            xamlOrError = bamlToXamlReader.OneBigString();
                        }
                        catch (Exception ex)
                        {
                            xamlOrError = ex.ToString();
                        }
                        return xamlOrError;
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(stream);
                        return sr.ReadToEnd();
                    }
                }
                return String.Empty;
            }
        }


        private void EnsureBamlResourceLoad()
        {
            if (_newDisassemblyCache == null)
            {
                _newDisassemblyCache = new NewDisassemblyCache();

                if (CurrentBamlResource != null && CurrentBamlResource.IsBaml)
                {
                    Stream stream = CurrentBamlResource.Stream;
                    stream.Seek(0, SeekOrigin.Begin);
                    NewBamlDisassembler dasm = new NewBamlDisassembler(stream)
                    {
                        ShowAddresses = ShowAddresses,
                        ShowRecordNumbers = ShowRecordNumbers,
                        ShowDebugRecords = ShowDebugRecords,
                        ShowTableRecords = ShowTableRecords
                    };
                    _newDisassemblyCache.Disassembly = dasm.DasmOneBigString();
                    _newDisassemblyCache.TypeInfoTable = dasm.TypeInfoTable;
                    _newDisassemblyCache.AttributeInfoTable = dasm.AttributeInfoTable;
                }
            }
        }

        public List<TypeInfoTableEntry> TypeInfoTable
        {
            get
            {
                if (CurrentBamlResource != null && CurrentBamlResource.IsBaml)
                {
                    EnsureBamlResourceLoad();
                    return _newDisassemblyCache.TypeInfoTable;
                }
                return null;
            }
        }

        public List<AttributeInfoTableEntry> AttributeInfoTable
        {
            get
            {
                if (CurrentBamlResource != null && CurrentBamlResource.IsBaml)
                {
                    EnsureBamlResourceLoad();
                    return _newDisassemblyCache.AttributeInfoTable;
                }
                return null;
            }
        }

        // ===========================================

        private void ReferenceAssemblies_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            foreach (ReferenceAssembly_VM refAsm in ReferenceAssemblies)
            {
                if (refAsm.IsLoaded)
                {
                    if (!_loadedReferenceAssemblies.Contains(refAsm))
                    {
                        _loadedReferenceAssemblies.Add(refAsm);
                    }
                }
            }
        }


    }
}


<|start_filename|>Sample Applications/SlidePuzzleDemo/Document.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Controls;

namespace SlidePuzzleDemo
{
    /// <summary>
    ///     Interaction logic for Document.xaml
    /// </summary>
    public partial class Document : FlowDocumentPageViewer
    {
        public Document()
        {
            InitializeComponent();
        }
    }
}

<|start_filename|>Windows/WindowActivationAndDeactivation/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.ComponentModel;
using System.Windows;

namespace WindowActivationAndDeactivation
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _isMediaElementPlaying;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            // Start media player
            mediaElement.Play();
            _isMediaElementPlaying = true;
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            // Stop media player
            mediaElement.Stop();
            _isMediaElementPlaying = false;
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            // Recommence playing media if window is activated
            if (_isMediaElementPlaying) mediaElement.Play();
        }

        private void Window_Deactivated(object sender, EventArgs e)
        {
            // Pause playing if media is being played and window is deactivated
            if (_isMediaElementPlaying) mediaElement.Pause();
        }

        private void ExitMenu_Click(object sender, RoutedEventArgs e)
        {
            // Close the window
            Close();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            // Ask user if they want to close the window
            if (_isMediaElementPlaying)
            {
                var msg = "Media is playing. Really close?";
                var title = "Custom Media Player?";
                var buttons = MessageBoxButton.YesNo;
                var icon = MessageBoxImage.Warning;

                // Show message box and get user's answer
                var result =
                    MessageBox.Show(msg, title, buttons, icon);

                // Don't close window if user clicked No
                e.Cancel = (result == MessageBoxResult.No);
            }
        }
    }
}

<|start_filename|>Migration and Interoperability/HostingAxInXaml/app.xaml.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;

namespace HostingAxInWpfWithXaml
{
    /// <summary>
    ///     Interaction logic for app.xaml
    /// </summary>
    public partial class app : Application
    {
        private void AppStartup(object sender, StartupEventArgs args)
        {
            Window1 mainWindow = new Window1();
            mainWindow.Show();
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/AddExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Adds 2 expressions
    /// </summary>
    public sealed class AddExpression : BinaryExpression
    {
        public AddExpression(IExpression left, IExpression right) : base(left, right)
        {
        }

        protected override double Operate(double d1, double d2) => d1 + d2;

        public override IExpression Differentiate(string byVar) => new AddExpression(left.Differentiate(byVar), right.Differentiate(byVar));

        public override IExpression Simplify()
        {
            var newLeft = left.Simplify();
            var newRight = right.Simplify();

            var leftConst = newLeft as ConstantExpression;
            var rightConst = newRight as ConstantExpression;
            var leftNegate = newLeft as NegateExpression;
            var rightNegate = newRight as NegateExpression;

            if (leftConst != null && rightConst != null)
            {
                // two constants;  just evaluate it;
                return new ConstantExpression(leftConst.Value + rightConst.Value);
            }
            if (leftConst != null && leftConst.Value == 0)
            {
                // 0 + y;  return y;
                return newRight;
            }
            if (rightConst != null && rightConst.Value == 0)
            {
                // x + 0;  return x;
                return newLeft;
            }
            if (rightNegate != null)
            {
                // x + -y;  return x - y;  (this covers -x + -y case too)
                return new SubExpression(newLeft, rightNegate.Child);
            }
            if (leftNegate != null)
            {
                // -x + y;  return y - x;
                return new SubExpression(newRight, leftNegate.Child);
            }
            // x + y;  no simplification
            return new AddExpression(newLeft, newRight);
        }

        public override string ToString() => "(" + left.ToString() + "+" + right.ToString() + ")";
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/PhotoSizeConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace PhotoViewerDemo
{
    /// <summary>
    ///     Converts an x,y size pair into a string value (e.g. 1600x1200)
    /// </summary>
    public class PhotoSizeConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if ((values[0] == null) || (values[1] == null))
            {
                return string.Empty;
            }
            return $"{values[0]}x{values[1]}";
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if ((string) value == string.Empty)
            {
                return new object[2];
            }
            string[] sSize;
            sSize = ((string) value).Split('x');

            var size = new object[2];
            size[0] = uint.Parse(sSize[0]);
            size[1] = uint.Parse(sSize[1]);
            return size;
        }
    }
}

<|start_filename|>Data Binding/MultiBinding/NameConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace MultiBinding
{
    public class NameConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            string name;

            switch ((string) parameter)
            {
                case "FormatLastFirst":
                    name = values[1] + ", " + values[0];
                    break;
                default:
                    name = values[0] + " " + values[1];
                    break;
            }

            return name;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            var splitValues = ((string) value).Split(' ');
            return splitValues;
        }
    }
}

<|start_filename|>Documents/Flow Content/TableBuilder/app.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace TableBuilder
{
    public class App : Application
    {
        private Window _mainWindow;
        private Table _table1;
        private FlowDocumentScrollViewer _tf1;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            CreateAndShowMainWindow();
        }

        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window();

            // Create the parent viewer...
            _tf1 = new FlowDocumentScrollViewer {Document = new FlowDocument()};

            // Create the Table...
            _table1 = new Table();
            // ...and add it as a content element of the TextFlow.
            _tf1.Document.Blocks.Add(_table1);
            // tf1.ContentStart.InsertTextElement(table1);

            // Set some global formatting properties for the table.
            _table1.CellSpacing = 10;
            _table1.Background = Brushes.White;

            // Create 6 columns and add them to the table's Columns collection.
            var numberOfColumns = 6;
            for (var x = 0; x < numberOfColumns; x++) _table1.Columns.Add(new TableColumn());

            // Set alternating background colors for the middle colums.
            _table1.Columns[1].Background =
                _table1.Columns[3].Background =
                    Brushes.LightSteelBlue;
            _table1.Columns[2].Background =
                _table1.Columns[4].Background =
                    Brushes.Beige;

            // Create and add an empty TableRowGroup to hold the table's Rows.
            _table1.RowGroups.Add(new TableRowGroup());

            // Add the first (title) row.
            _table1.RowGroups[0].Rows.Add(new TableRow());

            // Alias the current working row for easy reference.
            var currentRow = _table1.RowGroups[0].Rows[0];

            // Global formatting for the title row.
            currentRow.Background = Brushes.Silver;
            currentRow.FontSize = 40;
            currentRow.FontWeight = FontWeights.Bold;

            // Add the header row with content, 
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("2004 Sales Project"))));
            // and set the row to span all 6 columns.
            currentRow.Cells[0].ColumnSpan = 6;

            // Add the second (header) row.
            _table1.RowGroups[0].Rows.Add(new TableRow());
            currentRow = _table1.RowGroups[0].Rows[1];

            // Global formatting for the header row.
            currentRow.FontSize = 18;
            currentRow.FontWeight = FontWeights.Bold;

            // Add cells with content to the second row.
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Product"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 1"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 2"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 3"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 4"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("TOTAL"))));

            _table1.RowGroups[0].Rows.Add(new TableRow());
            currentRow = _table1.RowGroups[0].Rows[2];

            // Global formatting for the row.
            currentRow.FontSize = 12;
            currentRow.FontWeight = FontWeights.Normal;

            // Add cells with content to the third row.
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Widgets"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$50,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$55,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$60,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$65,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$230,000"))));

            // Bold the first cell.
            currentRow.Cells[0].FontWeight = FontWeights.Bold;

            // Add the fourth row.
            _table1.RowGroups[0].Rows.Add(new TableRow());
            currentRow = _table1.RowGroups[0].Rows[3];

            // Global formatting for the row.
            currentRow.FontSize = 12;
            currentRow.FontWeight = FontWeights.Normal;

            // Add cells with content to the third row.
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Wickets"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$100,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$120,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$160,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$200,000"))));
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$580,000"))));

            // Bold the first cell.
            currentRow.Cells[0].FontWeight = FontWeights.Bold;

            _table1.RowGroups[0].Rows.Add(new TableRow());
            currentRow = _table1.RowGroups[0].Rows[4];

            // Global formatting for the footer row.
            currentRow.Background = Brushes.LightGray;
            currentRow.FontSize = 18;
            currentRow.FontWeight = FontWeights.Normal;

            // Add the header row with content, 
            currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Projected 2004 Revenue: $810,000"))));
            // and set the row to span all 6 columns.
            currentRow.Cells[0].ColumnSpan = 6;

            _mainWindow.Title = "Table Sample";
            _mainWindow.Content = _tf1;
            _mainWindow.Show();
        }
    }
}

<|start_filename|>Graphics/AITCodec/cpp/aitdecoder.cpp<|end_filename|>
//----------------------------------------------------------------------------------------
// THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//  Description: Definition of AitDecoder
//----------------------------------------------------------------------------------------
#include "precomp.hpp"

static const GUID CLSID_AitContainer           = { 0xCCC50239, 0x14BB, 0x4F70, { 0xAD, 0x2A, 0xB7, 0x12, 0x62, 0x19, 0xA6, 0xDC } };
static const GUID CLSID_AitDecoder             = { 0xDEC50239, 0x14BB, 0x4F70, { 0xAD, 0x2A, 0xB7, 0x12, 0x62, 0x19, 0xA6, 0xDC } };

struct AitBlockHeader
{
    char Name[4];
    UINT FrameNumber;
    UINT Size;
};
//----------------------------------------------------------------------------------------
// SPECIAL UTILITY FUNCTIONS
//----------------------------------------------------------------------------------------
static HRESULT InputBitmapSource(IStream *stream, IWICImagingFactory *factory, IWICBitmapSource **bitmapSource)
{
    HRESULT result = S_OK;

    IWICBitmap *bitmap = NULL;
    IWICBitmapLock *bitmapLock = NULL;

    UINT width = 0, height = 0;
    double dpiX = 0, dpiY = 0;
    WICPixelFormatGUID pixelFormat = { 0 };
    UINT srcStride = 0;
    UINT destStride = 0;
    UINT cbBufferSize = 0;
    BYTE *data = NULL;

    if ((NULL == stream) || (NULL == factory) || (NULL == bitmapSource))
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        InputValue(stream, width);        
        InputValue(stream, height);
        InputValue(stream, dpiX);
        InputValue(stream, dpiY);
        InputValue(stream, srcStride);
        result = InputValue(stream, pixelFormat);
    }

    // Create the bitmap
    if (SUCCEEDED(result))
    {
        result = factory->CreateBitmap(width, height, pixelFormat, WICBitmapCacheOnLoad, &bitmap);
    }

    // Set the resolution
    if (SUCCEEDED(result))
    {
        result = bitmap->SetResolution(dpiX, dpiY);
    }

    // Lock it so that we can store the data
    if (SUCCEEDED(result))
    {
        WICRect rct;
        rct.X = 0;
        rct.Y = 0;
        rct.Width = width;
        rct.Height = height;

        result = bitmap->Lock(&rct, WICBitmapLockWrite, &bitmapLock);
    }

    if (SUCCEEDED(result))
    {
        result = bitmapLock->GetDataPointer(&cbBufferSize, &data);
    }

    if (SUCCEEDED(result))
    {
        result = bitmapLock->GetStride(&destStride);
    }

    // Read the data from the stream
    if (SUCCEEDED(result))
    {
        // We must read one scanline at a time because the input stride
        // may not equal the output stride
        for (UINT y = 0; y < height; y++)
        {
            InputValues(stream, data, srcStride);             
            // Prepare for the next scanline
            data += destStride;
        }
    }

    // Close the lock
    if (bitmapLock && bitmap)
    {
        if(bitmapLock)
        {
            bitmapLock->Release();
            bitmapLock = NULL;
        }
    }

    // Finish
    if (SUCCEEDED(result))
    {
        result = bitmap->QueryInterface(IID_IWICBitmapSource, (void**)bitmapSource);
        if (SUCCEEDED(result))
        {
            bitmap->Release();
        }
    }
    else
    {
        if (bitmap)
        {
            bitmap->Release();
        }
        *bitmapSource = NULL;
    }

    return result;
}

static HRESULT InputColorContext(IStream *stream, IWICImagingFactory *factory, IWICColorContext **colorContext)
{
    HRESULT result = S_OK;

    if ((NULL == stream) || (NULL == factory) || (NULL == colorContext))
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        // Once the unmanaged API fully supports color contexts,
        // implement this function.
        *colorContext = NULL;
    }

    return result;
}

static HRESULT InputBitmapPalette(IStream *stream, IWICImagingFactory *factory, IWICPalette **palette)
{
    HRESULT result = S_OK;

    WICColor *colors = NULL;

    UINT numColors = 0;

    if ((NULL == stream) || (NULL == factory) || (NULL == palette))
    {
        result = E_INVALIDARG;
    }

    // Create the palette
    if (SUCCEEDED(result))
    {
        result = factory->CreatePalette(palette);
    }

    // Read the colors
    if (SUCCEEDED(result))
    {
        result = InputValue(stream, numColors);
    }

    if (SUCCEEDED(result))
    {
        colors = new WICColor[numColors];

        if (NULL == colors)
        {
            result = E_OUTOFMEMORY;
        }
    }

    if (SUCCEEDED(result))
    {
        result = InputValues(stream, colors, numColors);
    }

    if (SUCCEEDED(result))
    {
        result = (*palette)->InitializeCustom(colors, numColors);
    }

    return result;
}


//----------------------------------------------------------------------------------------
// FRAME DECODE
//----------------------------------------------------------------------------------------

AitFrameDecode::AitFrameDecode(IWICImagingFactory *pIFactory, UINT num)
    : BaseFrameDecode(pIFactory, num) 
{    
}

AitFrameDecode::~AitFrameDecode()
{
}

HRESULT AitFrameDecode::InputColBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        colorContexts.push_back(NULL);
        result = InputColorContext(stream, factory, &colorContexts.back());
    }

    return result;
}

HRESULT AitFrameDecode::InputFraBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (bitmapSource)
        {
            bitmapSource->Release();
        }

        result = InputBitmapSource(stream, factory, &bitmapSource);
    }

    return result;
}

HRESULT AitFrameDecode::InputPalBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (palette)
        {
            palette->Release();
        }

        result = InputBitmapPalette(stream, factory, &palette);
    }

    return result;
}

HRESULT AitFrameDecode::InputPreBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (preview)
        {
            preview->Release();
        }
        result = InputBitmapSource(stream, factory, &preview);
    }

    return result;
}

HRESULT AitFrameDecode::InputThuBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (thumbnail)
        {
            thumbnail->Release();
        }

        result = InputBitmapSource(stream, factory, &thumbnail);
    }

    return result;
}




//----------------------------------------------------------------------------------------
// DECODER
//----------------------------------------------------------------------------------------

AitDecoder::AitDecoder()
    : BaseDecoder(CLSID_AitDecoder, CLSID_AitContainer)
{
}

AitDecoder::~AitDecoder()
{    
}

HRESULT AitDecoder::InputBlock(IStream *stream, AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        result = InputValue(stream, bh);
    }

    // Ensure that the name of this block is valid
    if (SUCCEEDED(result))
    {
        result = ('\0' == bh.Name[3]) ? S_OK : E_UNEXPECTED;
    }

    return result;
}

/// An AIT Block is the start of the image. It must come at the beginning of the file.
HRESULT AitDecoder::InputAitBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        result = E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        result = VerifyFactory();
    }

    // Get the number of frames
    UINT numFrames;

    if (SUCCEEDED(result))
    {
        result = InputValue(stream, numFrames);
    }

    if (SUCCEEDED(result))
    {
        ReleaseMembers(false);

        for (UINT i=0; i < numFrames; ++i)
        {
            AddDecoderFrame(CreateNewDecoderFrame(factory, i));            
        }
    }
    return result;
}

BaseFrameDecode* AitDecoder::CreateNewDecoderFrame(IWICImagingFactory* factory , UINT i){
    return new AitFrameDecode(factory, i);
}

HRESULT AitDecoder::InputColBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        result = VerifyFactory();
    }

    if (SUCCEEDED(result))
    {
        if (0xFFFFFFFF == bh.FrameNumber)
        {
            colorContexts.push_back(NULL);
            result = InputColorContext(stream, factory, &colorContexts.back());
        }
        else
        {
            if (bh.FrameNumber < static_cast<UINT>(frames.size()))
            {
                result = ((AitFrameDecode*)frames[bh.FrameNumber])->InputColBlock(stream, bh);
            }
            else
            {
                result = E_UNEXPECTED;
            }
        }
    }

    return result;
}

HRESULT AitDecoder::InputFraBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        if (0xFFFFFFFF == bh.FrameNumber)
        {
            result = E_UNEXPECTED;
        }
        else
        {
            if (bh.FrameNumber < static_cast<UINT>(frames.size()))
            {
                result = ((AitFrameDecode*)frames[bh.FrameNumber])->InputFraBlock(stream, bh);
            }
            else
            {
                result = E_UNEXPECTED;
            }
        }
    }

    return result;
}

HRESULT AitDecoder::InputPalBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        result = VerifyFactory();
    }

    if (SUCCEEDED(result))
    {
        if (0xFFFFFFFF == bh.FrameNumber)
        {
            if (palette)
            {
                palette->Release();
            }

            result = InputBitmapPalette(stream, factory, &palette);
        }
        else
        {
            if (bh.FrameNumber < static_cast<UINT>(frames.size()))
            {
                result = ((AitFrameDecode*)frames[bh.FrameNumber])->InputPalBlock(stream, bh);
            }
            else
            {
                result = E_UNEXPECTED;
            }
        }
    }

    return result;
}

HRESULT AitDecoder::InputPreBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        result = VerifyFactory();
    }

    if (SUCCEEDED(result))
    {
        if (0xFFFFFFFF == bh.FrameNumber)
        {
            if (preview)
            {
                preview->Release();
            }

            result = InputBitmapSource(stream, factory, &preview);
        }
        else
        {
            if (bh.FrameNumber < static_cast<UINT>(frames.size()))
            {
                result = ((AitFrameDecode*)frames[bh.FrameNumber])->InputPreBlock(stream, bh);
            }
            else
            {
                result = E_UNEXPECTED;
            }
        }
    }

    return result;
}

HRESULT AitDecoder::InputThuBlock(IStream *stream, const AitBlockHeader &bh)
{
    HRESULT result = S_OK;

    if (NULL == stream)
    {
        return E_INVALIDARG;
    }

    if (SUCCEEDED(result))
    {
        result = VerifyFactory();
    }

    if (SUCCEEDED(result))
    {
        if (0xFFFFFFFF == bh.FrameNumber)
        {
            if (thumbnail)
            {
                thumbnail->Release();
            }

            result = InputBitmapSource(stream, factory, &thumbnail);
        }
        else
        {
            if (bh.FrameNumber < static_cast<UINT>(frames.size()))
            {
                result = ((AitFrameDecode*)frames[bh.FrameNumber])->InputThuBlock(stream, bh);
            }
            else
            {
                result = E_UNEXPECTED;
            }
        }
    }

    return result;
}

STDMETHODIMP AitDecoder::QueryCapability(IStream *pIStream, DWORD *pCapability)
{
    HRESULT result = S_OK;

    ULARGE_INTEGER curPos = { 0 };    
    AitBlockHeader bh = { 0 };

    if ((NULL == pIStream) || (NULL == pCapability))
    {
        result = E_INVALIDARG;
    }

    // Remember the position of the stream
    if (SUCCEEDED(result))
    {        
        LARGE_INTEGER zero = { 0 };

        result = pIStream->Seek(zero, STREAM_SEEK_CUR, &curPos);
    }

    // Assume that we can't do anything
    if (SUCCEEDED(result))
    {
        *pCapability = 0;
    }

    // Prove ourselves wrong
    if (SUCCEEDED(result))
    {
        result = InputBlock(pIStream, bh);

        // Always seek back
        {
            LARGE_INTEGER cp;
            cp.QuadPart = static_cast<LONGLONG>(curPos.QuadPart);

            pIStream->Seek(cp, STREAM_SEEK_SET, NULL);
        }
    }

    if (SUCCEEDED(result))
    {
        // If this is our format, we can do everything
        if (strcmp(bh.Name, "AIT") == 0)
        {
            *pCapability = WICBitmapDecoderCapabilityCanDecodeAllImages ||
                           WICBitmapDecoderCapabilityCanDecodeThumbnail ||
                           WICBitmapDecoderCapabilityCanEnumerateMetadata ||
                           WICBitmapDecoderCapabilitySameEncoder;
        }
    }

    return result;
}

STDMETHODIMP AitDecoder::Initialize(IStream *pIStream, WICDecodeOptions cacheOptions)
{
    HRESULT result = E_INVALIDARG;

    ReleaseMembers(true);

    if (pIStream)
    {
        HRESULT blockRead = S_OK;
        AitBlockHeader bh = { 0 };

        result = S_OK;

        // Read blocks until we have reached the end or there was an error
        for (blockRead = InputBlock(pIStream, bh); SUCCEEDED(result) && SUCCEEDED(blockRead); blockRead = InputBlock(pIStream, bh))
        {
            ULARGE_INTEGER endPos = { 0 };

            // Store the end position
            if (SUCCEEDED(result))
            {
                LARGE_INTEGER zero = { 0 };

                result = pIStream->Seek(zero, STREAM_SEEK_CUR, &endPos);

                endPos.QuadPart += bh.Size;
            }

            // Dispatch on the block name
            if (strcmp(bh.Name, "AIT") == 0)
            {
                result = InputAitBlock(pIStream, bh);
            }
            else if (strcmp(bh.Name, "COL") == 0)
            {
                result = InputColBlock(pIStream, bh);
            }
            else if (strcmp(bh.Name, "FRA") == 0)
            {
                result = InputFraBlock(pIStream, bh);
            }
            else if (strcmp(bh.Name, "PAL") == 0)
            {
                result = InputPalBlock(pIStream, bh);
            }
            else if (strcmp(bh.Name, "PRE") == 0)
            {
                result = InputPreBlock(pIStream, bh);
            }
            else if (strcmp(bh.Name, "THU") == 0)
            {
                result = InputThuBlock(pIStream, bh);
            }

            // Ensure that we are at the end of the block no matter what happened
            if (0 != endPos.QuadPart)
            {
                LARGE_INTEGER ep;
                ep.QuadPart = static_cast<LONGLONG>(endPos.QuadPart);

                pIStream->Seek(ep, STREAM_SEEK_SET, NULL);
            }
        }
    }
    return result;
}



<|start_filename|>Getting Started/Concepts/samps/multibinding_samp.xaml.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace myMultiBinding //needs to match the .xaml page
{
    public partial class Page1 : Page
    {
        private ToolTip _ttp;
        // This function checks the language filter settings to see which code to filter and also grays out tabs with no content
        public void CheckLang(object sender, EventArgs e)
        {
            if (xcsharpCheck.Content == null) // grays out xaml + c# tab
            {
                xamlcsharp.Background = Brushes.Gainsboro;
                xamlcsharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlcsharp, true);
                _ttp.Content = "This sample is not available in XAML + C#.";
                xamlcsharp.ToolTip = (_ttp);
                xamlcsharp.IsEnabled = false;
            }
            else if (xcsharpCheck.Content != null)
            {
                xamlcsharp.IsEnabled = true;
            }

            if (xvbCheck.Content == null) // grays out xaml + vb tab
            {
                xamlvb.Background = Brushes.Gainsboro;
                xamlvb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xamlvb, true);
                _ttp.Content = "This sample is not available in XAML + Visual Basic.NET";
                xamlvb.ToolTip = (_ttp);
                xamlvb.IsEnabled = false;
            }
            else if (xvbCheck.Content != null)
            {
                xamlvb.IsEnabled = true;
            }

            if (xaml.Content == null) // grays out xaml
            {
                xaml.IsEnabled = false;
                xaml.Background = Brushes.Gainsboro;
                xaml.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(xaml, true);
                _ttp.Content = "This sample is not available in XAML.";
                xaml.ToolTip = (_ttp);
            }
            else if (xaml.Content != null)
            {
                xaml.IsEnabled = true;
            }

            if (csharp.Content == null) // grays out c#
            {
                csharp.IsEnabled = false;
                csharp.Background = Brushes.Gainsboro;
                csharp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(csharp, true);
                _ttp.Content = "This sample is not available in C#.";
                csharp.ToolTip = (_ttp);
            }
            else if (csharp.Content != null)
            {
                csharp.IsEnabled = true;
            }

            if (vb.Content == null) // grays out vb
            {
                vb.IsEnabled = false;
                vb.Background = Brushes.Gainsboro;
                vb.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(vb, true);
                _ttp.Content = "This sample is not available in Visual Basic.NET.";
                vb.ToolTip = (_ttp);
            }
            else if (vb.Content != null)
            {
                vb.IsEnabled = true;
            }

            if (managedcpp.Content == null) // grays out cpp
            {
                managedcpp.IsEnabled = false;
                managedcpp.Background = Brushes.Gainsboro;
                managedcpp.Foreground = Brushes.White;
                _ttp = new ToolTip();
                ToolTipService.SetShowOnDisabled(managedcpp, true);
                _ttp.Content = "This sample is not available in Managed C++.";
                managedcpp.ToolTip = (_ttp);
            }
            else if (managedcpp.Content != null)
            {
                managedcpp.IsEnabled = true;
            }
            if (Welcome.Page1.MyDouble == 1) // XAML only
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 2) // CSharp
            {
                csharp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 3) // Visual Basic
            {
                vb.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 4) // Managed CPP
            {
                managedcpp.Visibility = Visibility.Visible;
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 5) // No Filter
            {
                xaml.Visibility = Visibility.Visible;
                csharp.Visibility = Visibility.Visible;
                vb.Visibility = Visibility.Visible;
                managedcpp.Visibility = Visibility.Visible;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Visible;
            }
            else if (Welcome.Page1.MyDouble == 6) // XAML + CSharp
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Visible;
                xamlvb.Visibility = Visibility.Collapsed;
            }
            else if (Welcome.Page1.MyDouble == 7) // XAML + VB
            {
                xaml.Visibility = Visibility.Collapsed;
                csharp.Visibility = Visibility.Collapsed;
                vb.Visibility = Visibility.Collapsed;
                managedcpp.Visibility = Visibility.Collapsed;
                xamlcsharp.Visibility = Visibility.Collapsed;
                xamlvb.Visibility = Visibility.Visible;
            }
        }
    }


    public class NameConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            string name;

            switch ((string) parameter)
            {
                case "FormatLastFirst":
                    name = values[1] + ", " + values[0];
                    break;
                default:
                    name = values[0] + " " + values[1];
                    break;
            }

            return name;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            var splitValues = ((string) value).Split(' ');
            return splitValues;
        }
    }

    public class PersonName
    {
        public PersonName(string first, string last)
        {
            FirstName = first;
            LastName = last;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class NameList : ObservableCollection<PersonName>
    {
        public NameList()
        {
            Add(new PersonName("Willa", "Cather"));
            Add(new PersonName("Isak", "Dinesen"));
            Add(new PersonName("Victor", "Hugo"));
            Add(new PersonName("Jules", "Verne"));
        }
    }
}

<|start_filename|>Threading/MultiThreadingWebBrowser/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace MultiThreadingWebBrowser
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            placeHolder.Source = new Uri("http://www.msn.com");
        }

        private void Browse(object sender, RoutedEventArgs e)
        {
            placeHolder.Source = new Uri(newLocation.Text);
        }

        private void NewWindowHandler(object sender, RoutedEventArgs e)
        {
            var newWindowThread = new Thread(ThreadStartingPoint);
            newWindowThread.SetApartmentState(ApartmentState.STA);
            newWindowThread.IsBackground = true;
            newWindowThread.Start();
        }

        private void ThreadStartingPoint()
        {
            var tempWindow = new MainWindow();
            tempWindow.Show();
            Dispatcher.Run();
        }
    }
}

<|start_filename|>Graphics/ImageBrush/AlignmentExample.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Controls;

namespace Microsoft.Samples.Graphics.UsingImageBrush
{
    /// <summary>
    ///     Interaction logic for AlignmentExample.xaml
    /// </summary>
    public partial class AlignmentExample : Page
    {
    }
}

<|start_filename|>Tools/BamlReflector/BamlTools/KnownElements.cs<|end_filename|>
﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//using System.Xaml;

namespace BamlTools
{
    class KnownElement
    {
        public short BamlNumber { get; private set; }
        public string FullPath { get; private set; }
        public string ShortName { get; private set; }

        public KnownElement(short bamlNumber, string fullPath)
        {
            BamlNumber = bamlNumber;
            FullPath = fullPath;
            ShortName = fullPath.Substring(fullPath.LastIndexOf('.') + 1);
        }
    }

    class KnownElements
    {
        static public KnownElement[] _knownElements;

        static public KnownElement[] Elements
        {
            get
            {
                if (_knownElements == null)
                {
                    InitializeKnownElements();
                }
                return _knownElements;
            }
        }

        static private void InitializeKnownElements()
        {
            _knownElements = new KnownElement[]
        {
            new KnownElement(0,  "Error.Error0"),
            new KnownElement(1,  "System.Windows.Controls.AccessText"),
            new KnownElement(2,  "System.Windows.Controls.AdornedElementPlaceholder"),
            new KnownElement(3,  "System.Windows.Documents.Adorner"),
            new KnownElement(4,  "System.Windows.Documents.AdornerDecorator"),
            new KnownElement(5,  "System.Windows.Documents.AdornerLayer"),
            new KnownElement(6,  "System.Windows.Media.Media3D.AffineTransform3D"),
            new KnownElement(7,  "System.Windows.Media.Media3D.AmbientLight"),
            new KnownElement(8,  "System.Windows.Documents.AnchoredBlock"),
            new KnownElement(9,  "System.Windows.Media.Animation.Animatable"),
            new KnownElement(10,  "System.Windows.Media.Animation.AnimationClock"),
            new KnownElement(11,  "System.Windows.Media.Animation.AnimationTimeline"),
            new KnownElement(12,  "System.Windows.Application"),
            new KnownElement(13,  "System.Windows.Media.ArcSegment"),
            new KnownElement(14,  "System.Windows.Markup.ArrayExtension"),
            new KnownElement(15,  "System.Windows.Media.Media3D.AxisAngleRotation3D"),
            new KnownElement(16,  "System.Windows.Media.Converters.BaseIListConverter"),
            new KnownElement(17,  "System.Windows.Media.Animation.BeginStoryboard"),
            new KnownElement(18,  "System.Windows.Media.Effects.BevelBitmapEffect"),
            new KnownElement(19,  "System.Windows.Media.BezierSegment"),
            new KnownElement(20,  "System.Windows.Data.Binding"),
            new KnownElement(21,  "System.Windows.Data.BindingBase"),
            new KnownElement(22,  "System.Windows.Data.BindingExpression"),
            new KnownElement(23,  "System.Windows.Data.BindingExpressionBase"),
            new KnownElement(24,  "System.Windows.Data.BindingListCollectionView"),
            new KnownElement(25,  "System.Windows.Media.Imaging.BitmapDecoder"),
            new KnownElement(26,  "System.Windows.Media.Effects.BitmapEffect"),
            new KnownElement(27,  "System.Windows.Media.Effects.BitmapEffectCollection"),
            new KnownElement(28,  "System.Windows.Media.Effects.BitmapEffectGroup"),
            new KnownElement(29,  "System.Windows.Media.Effects.BitmapEffectInput"),
            new KnownElement(30,  "System.Windows.Media.Imaging.BitmapEncoder"),
            new KnownElement(31,  "System.Windows.Media.Imaging.BitmapFrame"),
            new KnownElement(32,  "System.Windows.Media.Imaging.BitmapImage"),
            new KnownElement(33,  "System.Windows.Media.Imaging.BitmapMetadata"),
            new KnownElement(34,  "System.Windows.Media.Imaging.BitmapPalette"),
            new KnownElement(35,  "System.Windows.Media.Imaging.BitmapSource"),
            new KnownElement(36,  "System.Windows.Documents.Block"),
            new KnownElement(37,  "System.Windows.Documents.BlockUIContainer"),
            new KnownElement(38,  "System.Windows.Media.Effects.BlurBitmapEffect"),
            new KnownElement(39,  "System.Windows.Media.Imaging.BmpBitmapDecoder"),
            new KnownElement(40,  "System.Windows.Media.Imaging.BmpBitmapEncoder"),
            new KnownElement(41,  "System.Windows.Documents.Bold"),
            new KnownElement(42,  "System.Windows.Media.Converters.BoolIListConverter"),
            new KnownElement(43,  "System.Boolean"),
            new KnownElement(44,  "System.Windows.Media.Animation.BooleanAnimationBase"),
            new KnownElement(45,  "System.Windows.Media.Animation.BooleanAnimationUsingKeyFrames"),
            new KnownElement(46,  "System.ComponentModel.BooleanConverter"),
            new KnownElement(47,  "System.Windows.Media.Animation.BooleanKeyFrame"),
            new KnownElement(48,  "System.Windows.Media.Animation.BooleanKeyFrameCollection"),
            new KnownElement(49,  "System.Windows.Controls.BooleanToVisibilityConverter"),
            new KnownElement(50,  "System.Windows.Controls.Border"),
            new KnownElement(51,  "System.Windows.Controls.BorderGapMaskConverter"),
            new KnownElement(52,  "System.Windows.Media.Brush"),
            new KnownElement(53,  "System.Windows.Media.BrushConverter"),
            new KnownElement(54,  "System.Windows.Controls.Primitives.BulletDecorator"),
            new KnownElement(55,  "System.Windows.Controls.Button"),
            new KnownElement(56,  "System.Windows.Controls.Primitives.ButtonBase"),
            new KnownElement(57,  "System.Byte"),
            new KnownElement(58,  "System.Windows.Media.Animation.ByteAnimation"),
            new KnownElement(59,  "System.Windows.Media.Animation.ByteAnimationBase"),
            new KnownElement(60,  "System.Windows.Media.Animation.ByteAnimationUsingKeyFrames"),
            new KnownElement(61,  "System.ComponentModel.ByteConverter"),
            new KnownElement(62,  "System.Windows.Media.Animation.ByteKeyFrame"),
            new KnownElement(63,  "System.Windows.Media.Animation.ByteKeyFrameCollection"),
            new KnownElement(64,  "System.Windows.Media.Imaging.CachedBitmap"),
            new KnownElement(65,  "System.Windows.Media.Media3D.Camera"),
            new KnownElement(66,  "System.Windows.Controls.Canvas"),
            new KnownElement(67,  "System.Char"),
            new KnownElement(68,  "System.Windows.Media.Animation.CharAnimationBase"),
            new KnownElement(69,  "System.Windows.Media.Animation.CharAnimationUsingKeyFrames"),
            new KnownElement(70,  "System.ComponentModel.CharConverter"),
            new KnownElement(71,  "System.Windows.Media.Converters.CharIListConverter"),
            new KnownElement(72,  "System.Windows.Media.Animation.CharKeyFrame"),
            new KnownElement(73,  "System.Windows.Media.Animation.CharKeyFrameCollection"),
            new KnownElement(74,  "System.Windows.Controls.CheckBox"),
            new KnownElement(75,  "System.Windows.Media.Animation.Clock"),
            new KnownElement(76,  "System.Windows.Media.Animation.ClockController"),
            new KnownElement(77,  "System.Windows.Media.Animation.ClockGroup"),
            new KnownElement(78,  "System.Windows.Data.CollectionContainer"),
            new KnownElement(79,  "System.Windows.Data.CollectionView"),
            new KnownElement(80,  "System.Windows.Data.CollectionViewSource"),
            new KnownElement(81,  "System.Windows.Media.Color"),
            new KnownElement(82,  "System.Windows.Media.Animation.ColorAnimation"),
            new KnownElement(83,  "System.Windows.Media.Animation.ColorAnimationBase"),
            new KnownElement(84,  "System.Windows.Media.Animation.ColorAnimationUsingKeyFrames"),
            new KnownElement(85,  "System.Windows.Media.Imaging.ColorConvertedBitmap"),
            new KnownElement(86,  "System.Windows.ColorConvertedBitmapExtension"),
            new KnownElement(87,  "System.Windows.Media.ColorConverter"),
            new KnownElement(88,  "System.Windows.Media.Animation.ColorKeyFrame"),
            new KnownElement(89,  "System.Windows.Media.Animation.ColorKeyFrameCollection"),
            new KnownElement(90,  "System.Windows.Controls.ColumnDefinition"),
            new KnownElement(91,  "System.Windows.Media.CombinedGeometry"),
            new KnownElement(92,  "System.Windows.Controls.ComboBox"),
            new KnownElement(93,  "System.Windows.Controls.ComboBoxItem"),
            new KnownElement(94,  "System.Windows.Input.CommandConverter"),
            new KnownElement(95,  "System.Windows.ComponentResourceKey"),
            new KnownElement(96,  "System.Windows.Markup.ComponentResourceKeyConverter"),
            new KnownElement(97,  "System.Windows.Media.CompositionTarget"),
            new KnownElement(98,  "System.Windows.Condition"),
            new KnownElement(99,  "System.Windows.Media.ContainerVisual"),
            new KnownElement(100,  "System.Windows.Controls.ContentControl"),
            new KnownElement(101,  "System.Windows.ContentElement"),
            new KnownElement(102,  "System.Windows.Controls.ContentPresenter"),
            new KnownElement(103,  "System.Windows.Markup.ContentPropertyAttribute"),
            new KnownElement(104,  "System.Windows.Markup.ContentWrapperAttribute"),
            new KnownElement(105,  "System.Windows.Controls.ContextMenu"),
            new KnownElement(106,  "System.Windows.Controls.ContextMenuService"),
            new KnownElement(107,  "System.Windows.Controls.Control"),
            new KnownElement(108,  "System.Windows.Controls.ControlTemplate"),
            new KnownElement(109,  "System.Windows.Media.Animation.ControllableStoryboardAction"),
            new KnownElement(110,  "System.Windows.CornerRadius"),
            new KnownElement(111,  "System.Windows.CornerRadiusConverter"),
            new KnownElement(112,  "System.Windows.Media.Imaging.CroppedBitmap"),
            new KnownElement(113,  "System.Globalization.CultureInfo"),
            new KnownElement(114,  "System.ComponentModel.CultureInfoConverter"),
            new KnownElement(115,  "System.Windows.CultureInfoIetfLanguageTagConverter"),
            new KnownElement(116,  "System.Windows.Input.Cursor"),
            new KnownElement(117,  "System.Windows.Input.CursorConverter"),
            new KnownElement(118,  "System.Windows.Media.DashStyle"),
            new KnownElement(119,  "System.Windows.Data.DataChangedEventManager"),
            new KnownElement(120,  "System.Windows.DataTemplate"),
            new KnownElement(121,  "System.Windows.DataTemplateKey"),
            new KnownElement(122,  "System.Windows.DataTrigger"),
            new KnownElement(123,  "System.DateTime"),
            new KnownElement(124,  "System.ComponentModel.DateTimeConverter"),
            new KnownElement(125,  "System.Windows.Markup.DateTimeConverter2"),
            new KnownElement(126,  "System.Decimal"),
            new KnownElement(127,  "System.Windows.Media.Animation.DecimalAnimation"),
            new KnownElement(128,  "System.Windows.Media.Animation.DecimalAnimationBase"),
            new KnownElement(129,  "System.Windows.Media.Animation.DecimalAnimationUsingKeyFrames"),
            new KnownElement(130,  "System.ComponentModel.DecimalConverter"),
            new KnownElement(131,  "System.Windows.Media.Animation.DecimalKeyFrame"),
            new KnownElement(132,  "System.Windows.Media.Animation.DecimalKeyFrameCollection"),
            new KnownElement(133,  "System.Windows.Controls.Decorator"),
            new KnownElement(134,  "System.Windows.Controls.DefinitionBase"),
            new KnownElement(135,  "System.Windows.DependencyObject"),
            new KnownElement(136,  "System.Windows.DependencyProperty"),
            new KnownElement(137,  "System.Windows.Markup.DependencyPropertyConverter"),
            new KnownElement(138,  "System.Windows.DialogResultConverter"),
            new KnownElement(139,  "System.Windows.Media.Media3D.DiffuseMaterial"),
            new KnownElement(140,  "System.Windows.Media.Media3D.DirectionalLight"),
            new KnownElement(141,  "System.Windows.Media.Animation.DiscreteBooleanKeyFrame"),
            new KnownElement(142,  "System.Windows.Media.Animation.DiscreteByteKeyFrame"),
            new KnownElement(143,  "System.Windows.Media.Animation.DiscreteCharKeyFrame"),
            new KnownElement(144,  "System.Windows.Media.Animation.DiscreteColorKeyFrame"),
            new KnownElement(145,  "System.Windows.Media.Animation.DiscreteDecimalKeyFrame"),
            new KnownElement(146,  "System.Windows.Media.Animation.DiscreteDoubleKeyFrame"),
            new KnownElement(147,  "System.Windows.Media.Animation.DiscreteInt16KeyFrame"),
            new KnownElement(148,  "System.Windows.Media.Animation.DiscreteInt32KeyFrame"),
            new KnownElement(149,  "System.Windows.Media.Animation.DiscreteInt64KeyFrame"),
            new KnownElement(150,  "System.Windows.Media.Animation.DiscreteMatrixKeyFrame"),
            new KnownElement(151,  "System.Windows.Media.Animation.DiscreteObjectKeyFrame"),
            new KnownElement(152,  "System.Windows.Media.Animation.DiscretePoint3DKeyFrame"),
            new KnownElement(153,  "System.Windows.Media.Animation.DiscretePointKeyFrame"),
            new KnownElement(154,  "System.Windows.Media.Animation.DiscreteQuaternionKeyFrame"),
            new KnownElement(155,  "System.Windows.Media.Animation.DiscreteRectKeyFrame"),
            new KnownElement(156,  "System.Windows.Media.Animation.DiscreteRotation3DKeyFrame"),
            new KnownElement(157,  "System.Windows.Media.Animation.DiscreteSingleKeyFrame"),
            new KnownElement(158,  "System.Windows.Media.Animation.DiscreteSizeKeyFrame"),
            new KnownElement(159,  "System.Windows.Media.Animation.DiscreteStringKeyFrame"),
            new KnownElement(160,  "System.Windows.Media.Animation.DiscreteThicknessKeyFrame"),
            new KnownElement(161,  "System.Windows.Media.Animation.DiscreteVector3DKeyFrame"),
            new KnownElement(162,  "System.Windows.Media.Animation.DiscreteVectorKeyFrame"),
            new KnownElement(163,  "System.Windows.Controls.DockPanel"),
            new KnownElement(164,  "System.Windows.Controls.Primitives.DocumentPageView"),
            new KnownElement(165,  "System.Windows.Documents.DocumentReference"),
            new KnownElement(166,  "System.Windows.Controls.DocumentViewer"),
            new KnownElement(167,  "System.Windows.Controls.Primitives.DocumentViewerBase"),
            new KnownElement(168,  "System.Double"),
            new KnownElement(169,  "System.Windows.Media.Animation.DoubleAnimation"),
            new KnownElement(170,  "System.Windows.Media.Animation.DoubleAnimationBase"),
            new KnownElement(171,  "System.Windows.Media.Animation.DoubleAnimationUsingKeyFrames"),
            new KnownElement(172,  "System.Windows.Media.Animation.DoubleAnimationUsingPath"),
            new KnownElement(173,  "System.Windows.Media.DoubleCollection"),
            new KnownElement(174,  "System.Windows.Media.DoubleCollectionConverter"),
            new KnownElement(175,  "System.ComponentModel.DoubleConverter"),
            new KnownElement(176,  "System.Windows.Media.Converters.DoubleIListConverter"),
            new KnownElement(177,  "System.Windows.Media.Animation.DoubleKeyFrame"),
            new KnownElement(178,  "System.Windows.Media.Animation.DoubleKeyFrameCollection"),
            new KnownElement(179,  "System.Windows.Media.Drawing"),
            new KnownElement(180,  "System.Windows.Media.DrawingBrush"),
            new KnownElement(181,  "System.Windows.Media.DrawingCollection"),
            new KnownElement(182,  "System.Windows.Media.DrawingContext"),
            new KnownElement(183,  "System.Windows.Media.DrawingGroup"),
            new KnownElement(184,  "System.Windows.Media.DrawingImage"),
            new KnownElement(185,  "System.Windows.Media.DrawingVisual"),
            new KnownElement(186,  "System.Windows.Media.Effects.DropShadowBitmapEffect"),
            new KnownElement(187,  "System.Windows.Duration"),
            new KnownElement(188,  "System.Windows.DurationConverter"),
            new KnownElement(189,  "System.Windows.DynamicResourceExtension"),
            new KnownElement(190,  "System.Windows.DynamicResourceExtensionConverter"),
            new KnownElement(191,  "System.Windows.Shapes.Ellipse"),
            new KnownElement(192,  "System.Windows.Media.EllipseGeometry"),
            new KnownElement(193,  "System.Windows.Media.Effects.EmbossBitmapEffect"),
            new KnownElement(194,  "System.Windows.Media.Media3D.EmissiveMaterial"),
            new KnownElement(195,  "System.ComponentModel.EnumConverter"),
            new KnownElement(196,  "System.Windows.EventManager"),
            new KnownElement(197,  "System.Windows.EventSetter"),
            new KnownElement(198,  "System.Windows.EventTrigger"),
            new KnownElement(199,  "System.Windows.Controls.Expander"),
            new KnownElement(200,  "System.Windows.Expression"),
            new KnownElement(201,  "System.Windows.ExpressionConverter"),
            new KnownElement(202,  "System.Windows.Documents.Figure"),
            new KnownElement(203,  "System.Windows.FigureLength"),
            new KnownElement(204,  "System.Windows.FigureLengthConverter"),
            new KnownElement(205,  "System.Windows.Documents.FixedDocument"),
            new KnownElement(206,  "System.Windows.Documents.FixedDocumentSequence"),
            new KnownElement(207,  "System.Windows.Documents.FixedPage"),
            new KnownElement(208,  "System.Windows.Documents.Floater"),
            new KnownElement(209,  "System.Windows.Documents.FlowDocument"),
            new KnownElement(210,  "System.Windows.Controls.FlowDocumentPageViewer"),
            new KnownElement(211,  "System.Windows.Controls.FlowDocumentReader"),
            new KnownElement(212,  "System.Windows.Controls.FlowDocumentScrollViewer"),
            new KnownElement(213,  "System.Windows.Input.FocusManager"),
            new KnownElement(214,  "System.Windows.Media.FontFamily"),
            new KnownElement(215,  "System.Windows.Media.FontFamilyConverter"),
            new KnownElement(216,  "System.Windows.FontSizeConverter"),
            new KnownElement(217,  "System.Windows.FontStretch"),
            new KnownElement(218,  "System.Windows.FontStretchConverter"),
            new KnownElement(219,  "System.Windows.FontStyle"),
            new KnownElement(220,  "System.Windows.FontStyleConverter"),
            new KnownElement(221,  "System.Windows.FontWeight"),
            new KnownElement(222,  "System.Windows.FontWeightConverter"),
            new KnownElement(223,  "System.Windows.Media.Imaging.FormatConvertedBitmap"),
            new KnownElement(224,  "System.Windows.Controls.Frame"),
            new KnownElement(225,  "System.Windows.FrameworkContentElement"),
            new KnownElement(226,  "System.Windows.FrameworkElement"),
            new KnownElement(227,  "System.Windows.FrameworkElementFactory"),
            new KnownElement(228,  "System.Windows.FrameworkPropertyMetadata"),
            new KnownElement(229,  "System.Windows.FrameworkPropertyMetadataOptions"),
            new KnownElement(230,  "System.Windows.Documents.FrameworkRichTextComposition"),
            new KnownElement(231,  "System.Windows.FrameworkTemplate"),
            new KnownElement(232,  "System.Windows.Documents.FrameworkTextComposition"),
            new KnownElement(233,  "System.Windows.Freezable"),
            new KnownElement(234,  "System.Windows.Media.GeneralTransform"),
            new KnownElement(235,  "System.Windows.Media.GeneralTransformCollection"),
            new KnownElement(236,  "System.Windows.Media.GeneralTransformGroup"),
            new KnownElement(237,  "System.Windows.Media.Geometry"),
            new KnownElement(238,  "System.Windows.Media.Media3D.Geometry3D"),
            new KnownElement(239,  "System.Windows.Media.GeometryCollection"),
            new KnownElement(240,  "System.Windows.Media.GeometryConverter"),
            new KnownElement(241,  "System.Windows.Media.GeometryDrawing"),
            new KnownElement(242,  "System.Windows.Media.GeometryGroup"),
            new KnownElement(243,  "System.Windows.Media.Media3D.GeometryModel3D"),
            new KnownElement(244,  "System.Windows.Ink.GestureRecognizer"),
            new KnownElement(245,  "System.Windows.Media.Imaging.GifBitmapDecoder"),
            new KnownElement(246,  "System.Windows.Media.Imaging.GifBitmapEncoder"),
            new KnownElement(247,  "System.Windows.Media.GlyphRun"),
            new KnownElement(248,  "System.Windows.Media.GlyphRunDrawing"),
            new KnownElement(249,  "System.Windows.Media.GlyphTypeface"),
            new KnownElement(250,  "System.Windows.Documents.Glyphs"),
            new KnownElement(251,  "System.Windows.Media.GradientBrush"),
            new KnownElement(252,  "System.Windows.Media.GradientStop"),
            new KnownElement(253,  "System.Windows.Media.GradientStopCollection"),
            new KnownElement(254,  "System.Windows.Controls.Grid"),
            new KnownElement(255,  "System.Windows.GridLength"),
            new KnownElement(256,  "System.Windows.GridLengthConverter"),
            new KnownElement(257,  "System.Windows.Controls.GridSplitter"),
            new KnownElement(258,  "System.Windows.Controls.GridView"),
            new KnownElement(259,  "System.Windows.Controls.GridViewColumn"),
            new KnownElement(260,  "System.Windows.Controls.GridViewColumnHeader"),
            new KnownElement(261,  "System.Windows.Controls.GridViewHeaderRowPresenter"),
            new KnownElement(262,  "System.Windows.Controls.GridViewRowPresenter"),
            new KnownElement(263,  "System.Windows.Controls.Primitives.GridViewRowPresenterBase"),
            new KnownElement(264,  "System.Windows.Controls.GroupBox"),
            new KnownElement(265,  "System.Windows.Controls.GroupItem"),
            new KnownElement(266,  "System.Guid"),
            new KnownElement(267,  "System.ComponentModel.GuidConverter"),
            new KnownElement(268,  "System.Windows.Media.GuidelineSet"),
            new KnownElement(269,  "System.Windows.Controls.HeaderedContentControl"),
            new KnownElement(270,  "System.Windows.Controls.HeaderedItemsControl"),
            new KnownElement(271,  "System.Windows.HierarchicalDataTemplate"),
            new KnownElement(272,  "System.Windows.Media.HostVisual"),
            new KnownElement(273,  "System.Windows.Documents.Hyperlink"),
            new KnownElement(274,  "System.Windows.Markup.IAddChild"),
            new KnownElement(275,  "System.Windows.Markup.IAddChildInternal"),
            new KnownElement(276,  "System.Windows.Input.ICommand"),
            new KnownElement(277,  "System.Windows.Markup.IComponentConnector"),
            new KnownElement(278,  "System.Windows.Markup.INameScope"),
            new KnownElement(279,  "System.Windows.Markup.IStyleConnector"),
            new KnownElement(280,  "System.Windows.Media.Imaging.IconBitmapDecoder"),
            new KnownElement(281,  "System.Windows.Controls.Image"),
            new KnownElement(282,  "System.Windows.Media.ImageBrush"),
            new KnownElement(283,  "System.Windows.Media.ImageDrawing"),
            new KnownElement(284,  "System.Windows.Media.ImageMetadata"),
            new KnownElement(285,  "System.Windows.Media.ImageSource"),
            new KnownElement(286,  "System.Windows.Media.ImageSourceConverter"),
            new KnownElement(287,  "System.Windows.Media.Imaging.InPlaceBitmapMetadataWriter"),
            new KnownElement(288,  "System.Windows.Controls.InkCanvas"),
            new KnownElement(289,  "System.Windows.Controls.InkPresenter"),
            new KnownElement(290,  "System.Windows.Documents.Inline"),
            new KnownElement(291,  "System.Windows.Documents.InlineCollection"),
            new KnownElement(292,  "System.Windows.Documents.InlineUIContainer"),
            new KnownElement(293,  "System.Windows.Input.InputBinding"),
            new KnownElement(294,  "System.Windows.Input.InputDevice"),
            new KnownElement(295,  "System.Windows.Input.InputLanguageManager"),
            new KnownElement(296,  "System.Windows.Input.InputManager"),
            new KnownElement(297,  "System.Windows.Input.InputMethod"),
            new KnownElement(298,  "System.Windows.Input.InputScope"),
            new KnownElement(299,  "System.Windows.Input.InputScopeConverter"),
            new KnownElement(300,  "System.Windows.Input.InputScopeName"),
            new KnownElement(301,  "System.Windows.Input.InputScopeNameConverter"),
            new KnownElement(302,  "System.Int16"),
            new KnownElement(303,  "System.Windows.Media.Animation.Int16Animation"),
            new KnownElement(304,  "System.Windows.Media.Animation.Int16AnimationBase"),
            new KnownElement(305,  "System.Windows.Media.Animation.Int16AnimationUsingKeyFrames"),
            new KnownElement(306,  "System.ComponentModel.Int16Converter"),
            new KnownElement(307,  "System.Windows.Media.Animation.Int16KeyFrame"),
            new KnownElement(308,  "System.Windows.Media.Animation.Int16KeyFrameCollection"),
            new KnownElement(309,  "System.Int32"),
            new KnownElement(310,  "System.Windows.Media.Animation.Int32Animation"),
            new KnownElement(311,  "System.Windows.Media.Animation.Int32AnimationBase"),
            new KnownElement(312,  "System.Windows.Media.Animation.Int32AnimationUsingKeyFrames"),
            new KnownElement(313,  "System.Windows.Media.Int32Collection"),
            new KnownElement(314,  "System.Windows.Media.Int32CollectionConverter"),
            new KnownElement(315,  "System.ComponentModel.Int32Converter"),
            new KnownElement(316,  "System.Windows.Media.Animation.Int32KeyFrame"),
            new KnownElement(317,  "System.Windows.Media.Animation.Int32KeyFrameCollection"),
            new KnownElement(318,  "System.Windows.Int32Rect"),
            new KnownElement(319,  "System.Windows.Int32RectConverter"),
            new KnownElement(320,  "System.Int64"),
            new KnownElement(321,  "System.Windows.Media.Animation.Int64Animation"),
            new KnownElement(322,  "System.Windows.Media.Animation.Int64AnimationBase"),
            new KnownElement(323,  "System.Windows.Media.Animation.Int64AnimationUsingKeyFrames"),
            new KnownElement(324,  "System.ComponentModel.Int64Converter"),
            new KnownElement(325,  "System.Windows.Media.Animation.Int64KeyFrame"),
            new KnownElement(326,  "System.Windows.Media.Animation.Int64KeyFrameCollection"),
            new KnownElement(327,  "System.Windows.Documents.Italic"),
            new KnownElement(328,  "System.Windows.Controls.ItemCollection"),
            new KnownElement(329,  "System.Windows.Controls.ItemsControl"),
            new KnownElement(330,  "System.Windows.Controls.ItemsPanelTemplate"),
            new KnownElement(331,  "System.Windows.Controls.ItemsPresenter"),
            new KnownElement(332,  "System.Windows.Navigation.JournalEntry"),
            new KnownElement(333,  "System.Windows.Navigation.JournalEntryListConverter"),
            new KnownElement(334,  "System.Windows.Navigation.JournalEntryUnifiedViewConverter"),
            new KnownElement(335,  "System.Windows.Media.Imaging.JpegBitmapDecoder"),
            new KnownElement(336,  "System.Windows.Media.Imaging.JpegBitmapEncoder"),
            new KnownElement(337,  "System.Windows.Input.KeyBinding"),
            new KnownElement(338,  "System.Windows.Input.KeyConverter"),
            new KnownElement(339,  "System.Windows.Input.KeyGesture"),
            new KnownElement(340,  "System.Windows.Input.KeyGestureConverter"),
            new KnownElement(341,  "System.Windows.Media.Animation.KeySpline"),
            new KnownElement(342,  "System.Windows.KeySplineConverter"),
            new KnownElement(343,  "System.Windows.Media.Animation.KeyTime"),
            new KnownElement(344,  "System.Windows.KeyTimeConverter"),
            new KnownElement(345,  "System.Windows.Input.KeyboardDevice"),
            new KnownElement(346,  "System.Windows.Controls.Label"),
            new KnownElement(347,  "System.Windows.Media.Imaging.LateBoundBitmapDecoder"),
            new KnownElement(348,  "System.Windows.LengthConverter"),
            new KnownElement(349,  "System.Windows.Media.Media3D.Light"),
            new KnownElement(350,  "System.Windows.Shapes.Line"),
            new KnownElement(351,  "System.Windows.Documents.LineBreak"),
            new KnownElement(352,  "System.Windows.Media.LineGeometry"),
            new KnownElement(353,  "System.Windows.Media.LineSegment"),
            new KnownElement(354,  "System.Windows.Media.Animation.LinearByteKeyFrame"),
            new KnownElement(355,  "System.Windows.Media.Animation.LinearColorKeyFrame"),
            new KnownElement(356,  "System.Windows.Media.Animation.LinearDecimalKeyFrame"),
            new KnownElement(357,  "System.Windows.Media.Animation.LinearDoubleKeyFrame"),
            new KnownElement(358,  "System.Windows.Media.LinearGradientBrush"),
            new KnownElement(359,  "System.Windows.Media.Animation.LinearInt16KeyFrame"),
            new KnownElement(360,  "System.Windows.Media.Animation.LinearInt32KeyFrame"),
            new KnownElement(361,  "System.Windows.Media.Animation.LinearInt64KeyFrame"),
            new KnownElement(362,  "System.Windows.Media.Animation.LinearPoint3DKeyFrame"),
            new KnownElement(363,  "System.Windows.Media.Animation.LinearPointKeyFrame"),
            new KnownElement(364,  "System.Windows.Media.Animation.LinearQuaternionKeyFrame"),
            new KnownElement(365,  "System.Windows.Media.Animation.LinearRectKeyFrame"),
            new KnownElement(366,  "System.Windows.Media.Animation.LinearRotation3DKeyFrame"),
            new KnownElement(367,  "System.Windows.Media.Animation.LinearSingleKeyFrame"),
            new KnownElement(368,  "System.Windows.Media.Animation.LinearSizeKeyFrame"),
            new KnownElement(369,  "System.Windows.Media.Animation.LinearThicknessKeyFrame"),
            new KnownElement(370,  "System.Windows.Media.Animation.LinearVector3DKeyFrame"),
            new KnownElement(371,  "System.Windows.Media.Animation.LinearVectorKeyFrame"),
            new KnownElement(372,  "System.Windows.Documents.List"),
            new KnownElement(373,  "System.Windows.Controls.ListBox"),
            new KnownElement(374,  "System.Windows.Controls.ListBoxItem"),
            new KnownElement(375,  "System.Windows.Data.ListCollectionView"),
            new KnownElement(376,  "System.Windows.Documents.ListItem"),
            new KnownElement(377,  "System.Windows.Controls.ListView"),
            new KnownElement(378,  "System.Windows.Controls.ListViewItem"),
            new KnownElement(379,  "System.Windows.Localization"),
            new KnownElement(380,  "System.Windows.LostFocusEventManager"),
            new KnownElement(381,  "System.Windows.Markup.MarkupExtension"),
            new KnownElement(382,  "System.Windows.Media.Media3D.Material"),
            new KnownElement(383,  "System.Windows.Media.Media3D.MaterialCollection"),
            new KnownElement(384,  "System.Windows.Media.Media3D.MaterialGroup"),
            new KnownElement(385,  "System.Windows.Media.Matrix"),
            new KnownElement(386,  "System.Windows.Media.Media3D.Matrix3D"),
            new KnownElement(387,  "System.Windows.Media.Media3D.Matrix3DConverter"),
            new KnownElement(388,  "System.Windows.Media.Animation.MatrixAnimationBase"),
            new KnownElement(389,  "System.Windows.Media.Animation.MatrixAnimationUsingKeyFrames"),
            new KnownElement(390,  "System.Windows.Media.Animation.MatrixAnimationUsingPath"),
            new KnownElement(391,  "System.Windows.Media.Media3D.MatrixCamera"),
            new KnownElement(392,  "System.Windows.Media.MatrixConverter"),
            new KnownElement(393,  "System.Windows.Media.Animation.MatrixKeyFrame"),
            new KnownElement(394,  "System.Windows.Media.Animation.MatrixKeyFrameCollection"),
            new KnownElement(395,  "System.Windows.Media.MatrixTransform"),
            new KnownElement(396,  "System.Windows.Media.Media3D.MatrixTransform3D"),
            new KnownElement(397,  "System.Windows.Media.MediaClock"),
            new KnownElement(398,  "System.Windows.Controls.MediaElement"),
            new KnownElement(399,  "System.Windows.Media.MediaPlayer"),
            new KnownElement(400,  "System.Windows.Media.MediaTimeline"),
            new KnownElement(401,  "System.Windows.Controls.Menu"),
            new KnownElement(402,  "System.Windows.Controls.Primitives.MenuBase"),
            new KnownElement(403,  "System.Windows.Controls.MenuItem"),
            new KnownElement(404,  "System.Windows.Controls.MenuScrollingVisibilityConverter"),
            new KnownElement(405,  "System.Windows.Media.Media3D.MeshGeometry3D"),
            new KnownElement(406,  "System.Windows.Media.Media3D.Model3D"),
            new KnownElement(407,  "System.Windows.Media.Media3D.Model3DCollection"),
            new KnownElement(408,  "System.Windows.Media.Media3D.Model3DGroup"),
            new KnownElement(409,  "System.Windows.Media.Media3D.ModelVisual3D"),
            new KnownElement(410,  "System.Windows.Input.ModifierKeysConverter"),
            new KnownElement(411,  "System.Windows.Input.MouseActionConverter"),
            new KnownElement(412,  "System.Windows.Input.MouseBinding"),
            new KnownElement(413,  "System.Windows.Input.MouseDevice"),
            new KnownElement(414,  "System.Windows.Input.MouseGesture"),
            new KnownElement(415,  "System.Windows.Input.MouseGestureConverter"),
            new KnownElement(416,  "System.Windows.Data.MultiBinding"),
            new KnownElement(417,  "System.Windows.Data.MultiBindingExpression"),
            new KnownElement(418,  "System.Windows.MultiDataTrigger"),
            new KnownElement(419,  "System.Windows.MultiTrigger"),
            new KnownElement(420,  "System.Windows.NameScope"),
            new KnownElement(421,  "System.Windows.Navigation.NavigationWindow"),
            new KnownElement(422,  "System.Windows.Markup.NullExtension"),
            new KnownElement(423,  "System.Windows.NullableBoolConverter"),
            new KnownElement(424,  "System.ComponentModel.NullableConverter"),
            new KnownElement(425,  "System.Windows.Media.NumberSubstitution"),
            new KnownElement(426,  "System.Object"),
            new KnownElement(427,  "System.Windows.Media.Animation.ObjectAnimationBase"),
            new KnownElement(428,  "System.Windows.Media.Animation.ObjectAnimationUsingKeyFrames"),
            new KnownElement(429,  "System.Windows.Data.ObjectDataProvider"),
            new KnownElement(430,  "System.Windows.Media.Animation.ObjectKeyFrame"),
            new KnownElement(431,  "System.Windows.Media.Animation.ObjectKeyFrameCollection"),
            new KnownElement(432,  "System.Windows.Media.Media3D.OrthographicCamera"),
            new KnownElement(433,  "System.Windows.Media.Effects.OuterGlowBitmapEffect"),
            new KnownElement(434,  "System.Windows.Controls.Page"),
            new KnownElement(435,  "System.Windows.Documents.PageContent"),
            new KnownElement(436,  "System.Windows.Navigation.PageFunctionBase"),
            new KnownElement(437,  "System.Windows.Controls.Panel"),
            new KnownElement(438,  "System.Windows.Documents.Paragraph"),
            new KnownElement(439,  "System.Windows.Media.Animation.ParallelTimeline"),
            new KnownElement(440,  "System.Windows.Markup.ParserContext"),
            new KnownElement(441,  "System.Windows.Controls.PasswordBox"),
            new KnownElement(442,  "System.Windows.Shapes.Path"),
            new KnownElement(443,  "System.Windows.Media.PathFigure"),
            new KnownElement(444,  "System.Windows.Media.PathFigureCollection"),
            new KnownElement(445,  "System.Windows.Media.PathFigureCollectionConverter"),
            new KnownElement(446,  "System.Windows.Media.PathGeometry"),
            new KnownElement(447,  "System.Windows.Media.PathSegment"),
            new KnownElement(448,  "System.Windows.Media.PathSegmentCollection"),
            new KnownElement(449,  "System.Windows.Media.Animation.PauseStoryboard"),
            new KnownElement(450,  "System.Windows.Media.Pen"),
            new KnownElement(451,  "System.Windows.Media.Media3D.PerspectiveCamera"),
            new KnownElement(452,  "System.Windows.Media.PixelFormat"),
            new KnownElement(453,  "System.Windows.Media.PixelFormatConverter"),
            new KnownElement(454,  "System.Windows.Media.Imaging.PngBitmapDecoder"),
            new KnownElement(455,  "System.Windows.Media.Imaging.PngBitmapEncoder"),
            new KnownElement(456,  "System.Windows.Point"),
            new KnownElement(457,  "System.Windows.Media.Media3D.Point3D"),
            new KnownElement(458,  "System.Windows.Media.Animation.Point3DAnimation"),
            new KnownElement(459,  "System.Windows.Media.Animation.Point3DAnimationBase"),
            new KnownElement(460,  "System.Windows.Media.Animation.Point3DAnimationUsingKeyFrames"),
            new KnownElement(461,  "System.Windows.Media.Media3D.Point3DCollection"),
            new KnownElement(462,  "System.Windows.Media.Media3D.Point3DCollectionConverter"),
            new KnownElement(463,  "System.Windows.Media.Media3D.Point3DConverter"),
            new KnownElement(464,  "System.Windows.Media.Animation.Point3DKeyFrame"),
            new KnownElement(465,  "System.Windows.Media.Animation.Point3DKeyFrameCollection"),
            new KnownElement(466,  "System.Windows.Media.Media3D.Point4D"),
            new KnownElement(467,  "System.Windows.Media.Media3D.Point4DConverter"),
            new KnownElement(468,  "System.Windows.Media.Animation.PointAnimation"),
            new KnownElement(469,  "System.Windows.Media.Animation.PointAnimationBase"),
            new KnownElement(470,  "System.Windows.Media.Animation.PointAnimationUsingKeyFrames"),
            new KnownElement(471,  "System.Windows.Media.Animation.PointAnimationUsingPath"),
            new KnownElement(472,  "System.Windows.Media.PointCollection"),
            new KnownElement(473,  "System.Windows.Media.PointCollectionConverter"),
            new KnownElement(474,  "System.Windows.PointConverter"),
            new KnownElement(475,  "System.Windows.Media.Converters.PointIListConverter"),
            new KnownElement(476,  "System.Windows.Media.Animation.PointKeyFrame"),
            new KnownElement(477,  "System.Windows.Media.Animation.PointKeyFrameCollection"),
            new KnownElement(478,  "System.Windows.Media.Media3D.PointLight"),
            new KnownElement(479,  "System.Windows.Media.Media3D.PointLightBase"),
            new KnownElement(480,  "System.Windows.Media.PolyBezierSegment"),
            new KnownElement(481,  "System.Windows.Media.PolyLineSegment"),
            new KnownElement(482,  "System.Windows.Media.PolyQuadraticBezierSegment"),
            new KnownElement(483,  "System.Windows.Shapes.Polygon"),
            new KnownElement(484,  "System.Windows.Shapes.Polyline"),
            new KnownElement(485,  "System.Windows.Controls.Primitives.Popup"),
            new KnownElement(486,  "System.Windows.PresentationSource"),
            new KnownElement(487,  "System.Windows.Data.PriorityBinding"),
            new KnownElement(488,  "System.Windows.Data.PriorityBindingExpression"),
            new KnownElement(489,  "System.Windows.Controls.ProgressBar"),
            new KnownElement(490,  "System.Windows.Media.Media3D.ProjectionCamera"),
            new KnownElement(491,  "System.Windows.PropertyPath"),
            new KnownElement(492,  "System.Windows.PropertyPathConverter"),
            new KnownElement(493,  "System.Windows.Media.QuadraticBezierSegment"),
            new KnownElement(494,  "System.Windows.Media.Media3D.Quaternion"),
            new KnownElement(495,  "System.Windows.Media.Animation.QuaternionAnimation"),
            new KnownElement(496,  "System.Windows.Media.Animation.QuaternionAnimationBase"),
            new KnownElement(497,  "System.Windows.Media.Animation.QuaternionAnimationUsingKeyFrames"),
            new KnownElement(498,  "System.Windows.Media.Media3D.QuaternionConverter"),
            new KnownElement(499,  "System.Windows.Media.Animation.QuaternionKeyFrame"),
            new KnownElement(500,  "System.Windows.Media.Animation.QuaternionKeyFrameCollection"),
            new KnownElement(501,  "System.Windows.Media.Media3D.QuaternionRotation3D"),
            new KnownElement(502,  "System.Windows.Media.RadialGradientBrush"),
            new KnownElement(503,  "System.Windows.Controls.RadioButton"),
            new KnownElement(504,  "System.Windows.Controls.Primitives.RangeBase"),
            new KnownElement(505,  "System.Windows.Rect"),
            new KnownElement(506,  "System.Windows.Media.Media3D.Rect3D"),
            new KnownElement(507,  "System.Windows.Media.Media3D.Rect3DConverter"),
            new KnownElement(508,  "System.Windows.Media.Animation.RectAnimation"),
            new KnownElement(509,  "System.Windows.Media.Animation.RectAnimationBase"),
            new KnownElement(510,  "System.Windows.Media.Animation.RectAnimationUsingKeyFrames"),
            new KnownElement(511,  "System.Windows.RectConverter"),
            new KnownElement(512,  "System.Windows.Media.Animation.RectKeyFrame"),
            new KnownElement(513,  "System.Windows.Media.Animation.RectKeyFrameCollection"),
            new KnownElement(514,  "System.Windows.Shapes.Rectangle"),
            new KnownElement(515,  "System.Windows.Media.RectangleGeometry"),
            new KnownElement(516,  "System.Windows.Data.RelativeSource"),
            new KnownElement(517,  "System.Windows.Media.Animation.RemoveStoryboard"),
            new KnownElement(518,  "System.Windows.Media.RenderOptions"),
            new KnownElement(519,  "System.Windows.Media.Imaging.RenderTargetBitmap"),
            new KnownElement(520,  "System.Windows.Media.Animation.RepeatBehavior"),
            new KnownElement(521,  "System.Windows.Media.Animation.RepeatBehaviorConverter"),
            new KnownElement(522,  "System.Windows.Controls.Primitives.RepeatButton"),
            new KnownElement(523,  "System.Windows.Controls.Primitives.ResizeGrip"),
            new KnownElement(524,  "System.Windows.ResourceDictionary"),
            new KnownElement(525,  "System.Windows.ResourceKey"),
            new KnownElement(526,  "System.Windows.Media.Animation.ResumeStoryboard"),
            new KnownElement(527,  "System.Windows.Controls.RichTextBox"),
            new KnownElement(528,  "System.Windows.Media.RotateTransform"),
            new KnownElement(529,  "System.Windows.Media.Media3D.RotateTransform3D"),
            new KnownElement(530,  "System.Windows.Media.Media3D.Rotation3D"),
            new KnownElement(531,  "System.Windows.Media.Animation.Rotation3DAnimation"),
            new KnownElement(532,  "System.Windows.Media.Animation.Rotation3DAnimationBase"),
            new KnownElement(533,  "System.Windows.Media.Animation.Rotation3DAnimationUsingKeyFrames"),
            new KnownElement(534,  "System.Windows.Media.Animation.Rotation3DKeyFrame"),
            new KnownElement(535,  "System.Windows.Media.Animation.Rotation3DKeyFrameCollection"),
            new KnownElement(536,  "System.Windows.Input.RoutedCommand"),
            new KnownElement(537,  "System.Windows.RoutedEvent"),
            new KnownElement(538,  "System.Windows.Markup.RoutedEventConverter"),
            new KnownElement(539,  "System.Windows.Input.RoutedUICommand"),
            new KnownElement(540,  "System.Windows.RoutingStrategy"),
            new KnownElement(541,  "System.Windows.Controls.RowDefinition"),
            new KnownElement(542,  "System.Windows.Documents.Run"),
            new KnownElement(543,  "System.Windows.Markup.RuntimeNamePropertyAttribute"),
            new KnownElement(544,  "System.SByte"),
            new KnownElement(545,  "System.ComponentModel.SByteConverter"),
            new KnownElement(546,  "System.Windows.Media.ScaleTransform"),
            new KnownElement(547,  "System.Windows.Media.Media3D.ScaleTransform3D"),
            new KnownElement(548,  "System.Windows.Controls.Primitives.ScrollBar"),
            new KnownElement(549,  "System.Windows.Controls.ScrollContentPresenter"),
            new KnownElement(550,  "System.Windows.Controls.ScrollViewer"),
            new KnownElement(551,  "System.Windows.Documents.Section"),
            new KnownElement(552,  "System.Windows.Media.Animation.SeekStoryboard"),
            new KnownElement(553,  "System.Windows.Controls.Primitives.Selector"),
            new KnownElement(554,  "System.Windows.Controls.Separator"),
            new KnownElement(555,  "System.Windows.Media.Animation.SetStoryboardSpeedRatio"),
            new KnownElement(556,  "System.Windows.Setter"),
            new KnownElement(557,  "System.Windows.SetterBase"),
            new KnownElement(558,  "System.Windows.Shapes.Shape"),
            new KnownElement(559,  "System.Single"),
            new KnownElement(560,  "System.Windows.Media.Animation.SingleAnimation"),
            new KnownElement(561,  "System.Windows.Media.Animation.SingleAnimationBase"),
            new KnownElement(562,  "System.Windows.Media.Animation.SingleAnimationUsingKeyFrames"),
            new KnownElement(563,  "System.ComponentModel.SingleConverter"),
            new KnownElement(564,  "System.Windows.Media.Animation.SingleKeyFrame"),
            new KnownElement(565,  "System.Windows.Media.Animation.SingleKeyFrameCollection"),
            new KnownElement(566,  "System.Windows.Size"),
            new KnownElement(567,  "System.Windows.Media.Media3D.Size3D"),
            new KnownElement(568,  "System.Windows.Media.Media3D.Size3DConverter"),
            new KnownElement(569,  "System.Windows.Media.Animation.SizeAnimation"),
            new KnownElement(570,  "System.Windows.Media.Animation.SizeAnimationBase"),
            new KnownElement(571,  "System.Windows.Media.Animation.SizeAnimationUsingKeyFrames"),
            new KnownElement(572,  "System.Windows.SizeConverter"),
            new KnownElement(573,  "System.Windows.Media.Animation.SizeKeyFrame"),
            new KnownElement(574,  "System.Windows.Media.Animation.SizeKeyFrameCollection"),
            new KnownElement(575,  "System.Windows.Media.SkewTransform"),
            new KnownElement(576,  "System.Windows.Media.Animation.SkipStoryboardToFill"),
            new KnownElement(577,  "System.Windows.Controls.Slider"),
            new KnownElement(578,  "System.Windows.Media.SolidColorBrush"),
            new KnownElement(579,  "System.Windows.Controls.SoundPlayerAction"),
            new KnownElement(580,  "System.Windows.Documents.Span"),
            new KnownElement(581,  "System.Windows.Media.Media3D.SpecularMaterial"),
            new KnownElement(582,  "System.Windows.Controls.SpellCheck"),
            new KnownElement(583,  "System.Windows.Media.Animation.SplineByteKeyFrame"),
            new KnownElement(584,  "System.Windows.Media.Animation.SplineColorKeyFrame"),
            new KnownElement(585,  "System.Windows.Media.Animation.SplineDecimalKeyFrame"),
            new KnownElement(586,  "System.Windows.Media.Animation.SplineDoubleKeyFrame"),
            new KnownElement(587,  "System.Windows.Media.Animation.SplineInt16KeyFrame"),
            new KnownElement(588,  "System.Windows.Media.Animation.SplineInt32KeyFrame"),
            new KnownElement(589,  "System.Windows.Media.Animation.SplineInt64KeyFrame"),
            new KnownElement(590,  "System.Windows.Media.Animation.SplinePoint3DKeyFrame"),
            new KnownElement(591,  "System.Windows.Media.Animation.SplinePointKeyFrame"),
            new KnownElement(592,  "System.Windows.Media.Animation.SplineQuaternionKeyFrame"),
            new KnownElement(593,  "System.Windows.Media.Animation.SplineRectKeyFrame"),
            new KnownElement(594,  "System.Windows.Media.Animation.SplineRotation3DKeyFrame"),
            new KnownElement(595,  "System.Windows.Media.Animation.SplineSingleKeyFrame"),
            new KnownElement(596,  "System.Windows.Media.Animation.SplineSizeKeyFrame"),
            new KnownElement(597,  "System.Windows.Media.Animation.SplineThicknessKeyFrame"),
            new KnownElement(598,  "System.Windows.Media.Animation.SplineVector3DKeyFrame"),
            new KnownElement(599,  "System.Windows.Media.Animation.SplineVectorKeyFrame"),
            new KnownElement(600,  "System.Windows.Media.Media3D.SpotLight"),
            new KnownElement(601,  "System.Windows.Controls.StackPanel"),
            new KnownElement(602,  "System.Windows.Markup.StaticExtension"),
            new KnownElement(603,  "System.Windows.StaticResourceExtension"),
            new KnownElement(604,  "System.Windows.Controls.Primitives.StatusBar"),
            new KnownElement(605,  "System.Windows.Controls.Primitives.StatusBarItem"),
            new KnownElement(606,  "System.Windows.Controls.StickyNoteControl"),
            new KnownElement(607,  "System.Windows.Media.Animation.StopStoryboard"),
            new KnownElement(608,  "System.Windows.Media.Animation.Storyboard"),
            new KnownElement(609,  "System.Windows.Media.StreamGeometry"),
            new KnownElement(610,  "System.Windows.Media.StreamGeometryContext"),
            new KnownElement(611,  "System.Windows.Resources.StreamResourceInfo"),
            new KnownElement(612,  "System.String"),
            new KnownElement(613,  "System.Windows.Media.Animation.StringAnimationBase"),
            new KnownElement(614,  "System.Windows.Media.Animation.StringAnimationUsingKeyFrames"),
            new KnownElement(615,  "System.ComponentModel.StringConverter"),
            new KnownElement(616,  "System.Windows.Media.Animation.StringKeyFrame"),
            new KnownElement(617,  "System.Windows.Media.Animation.StringKeyFrameCollection"),
            new KnownElement(618,  "System.Windows.Ink.StrokeCollection"),
            new KnownElement(619,  "System.Windows.StrokeCollectionConverter"),
            new KnownElement(620,  "System.Windows.Style"),
            new KnownElement(621,  "System.Windows.Input.Stylus"),
            new KnownElement(622,  "System.Windows.Input.StylusDevice"),
            new KnownElement(623,  "System.Windows.Controls.TabControl"),
            new KnownElement(624,  "System.Windows.Controls.TabItem"),
            new KnownElement(625,  "System.Windows.Controls.Primitives.TabPanel"),
            new KnownElement(626,  "System.Windows.Documents.Table"),
            new KnownElement(627,  "System.Windows.Documents.TableCell"),
            new KnownElement(628,  "System.Windows.Documents.TableColumn"),
            new KnownElement(629,  "System.Windows.Documents.TableRow"),
            new KnownElement(630,  "System.Windows.Documents.TableRowGroup"),
            new KnownElement(631,  "System.Windows.Input.TabletDevice"),
            new KnownElement(632,  "System.Windows.TemplateBindingExpression"),
            new KnownElement(633,  "System.Windows.TemplateBindingExpressionConverter"),
            new KnownElement(634,  "System.Windows.TemplateBindingExtension"),
            new KnownElement(635,  "System.Windows.TemplateBindingExtensionConverter"),
            new KnownElement(636,  "System.Windows.TemplateKey"),
            new KnownElement(637,  "System.Windows.Markup.TemplateKeyConverter"),
            new KnownElement(638,  "System.Windows.Controls.TextBlock"),
            new KnownElement(639,  "System.Windows.Controls.TextBox"),
            new KnownElement(640,  "System.Windows.Controls.Primitives.TextBoxBase"),
            new KnownElement(641,  "System.Windows.Input.TextComposition"),
            new KnownElement(642,  "System.Windows.Input.TextCompositionManager"),
            new KnownElement(643,  "System.Windows.TextDecoration"),
            new KnownElement(644,  "System.Windows.TextDecorationCollection"),
            new KnownElement(645,  "System.Windows.TextDecorationCollectionConverter"),
            new KnownElement(646,  "System.Windows.Media.TextEffect"),
            new KnownElement(647,  "System.Windows.Media.TextEffectCollection"),
            new KnownElement(648,  "System.Windows.Documents.TextElement"),
            new KnownElement(649,  "System.Windows.Controls.TextSearch"),
            new KnownElement(650,  "System.Windows.ThemeDictionaryExtension"),
            new KnownElement(651,  "System.Windows.Thickness"),
            new KnownElement(652,  "System.Windows.Media.Animation.ThicknessAnimation"),
            new KnownElement(653,  "System.Windows.Media.Animation.ThicknessAnimationBase"),
            new KnownElement(654,  "System.Windows.Media.Animation.ThicknessAnimationUsingKeyFrames"),
            new KnownElement(655,  "System.Windows.ThicknessConverter"),
            new KnownElement(656,  "System.Windows.Media.Animation.ThicknessKeyFrame"),
            new KnownElement(657,  "System.Windows.Media.Animation.ThicknessKeyFrameCollection"),
            new KnownElement(658,  "System.Windows.Controls.Primitives.Thumb"),
            new KnownElement(659,  "System.Windows.Controls.Primitives.TickBar"),
            new KnownElement(660,  "System.Windows.Media.Imaging.TiffBitmapDecoder"),
            new KnownElement(661,  "System.Windows.Media.Imaging.TiffBitmapEncoder"),
            new KnownElement(662,  "System.Windows.Media.TileBrush"),
            new KnownElement(663,  "System.TimeSpan"),
            new KnownElement(664,  "System.ComponentModel.TimeSpanConverter"),
            new KnownElement(665,  "System.Windows.Media.Animation.Timeline"),
            new KnownElement(666,  "System.Windows.Media.Animation.TimelineCollection"),
            new KnownElement(667,  "System.Windows.Media.Animation.TimelineGroup"),
            new KnownElement(668,  "System.Windows.Controls.Primitives.ToggleButton"),
            new KnownElement(669,  "System.Windows.Controls.ToolBar"),
            new KnownElement(670,  "System.Windows.Controls.Primitives.ToolBarOverflowPanel"),
            new KnownElement(671,  "System.Windows.Controls.Primitives.ToolBarPanel"),
            new KnownElement(672,  "System.Windows.Controls.ToolBarTray"),
            new KnownElement(673,  "System.Windows.Controls.ToolTip"),
            new KnownElement(674,  "System.Windows.Controls.ToolTipService"),
            new KnownElement(675,  "System.Windows.Controls.Primitives.Track"),
            new KnownElement(676,  "System.Windows.Media.Transform"),
            new KnownElement(677,  "System.Windows.Media.Media3D.Transform3D"),
            new KnownElement(678,  "System.Windows.Media.Media3D.Transform3DCollection"),
            new KnownElement(679,  "System.Windows.Media.Media3D.Transform3DGroup"),
            new KnownElement(680,  "System.Windows.Media.TransformCollection"),
            new KnownElement(681,  "System.Windows.Media.TransformConverter"),
            new KnownElement(682,  "System.Windows.Media.TransformGroup"),
            new KnownElement(683,  "System.Windows.Media.Imaging.TransformedBitmap"),
            new KnownElement(684,  "System.Windows.Media.TranslateTransform"),
            new KnownElement(685,  "System.Windows.Media.Media3D.TranslateTransform3D"),
            new KnownElement(686,  "System.Windows.Controls.TreeView"),
            new KnownElement(687,  "System.Windows.Controls.TreeViewItem"),
            new KnownElement(688,  "System.Windows.Trigger"),
            new KnownElement(689,  "System.Windows.TriggerAction"),
            new KnownElement(690,  "System.Windows.TriggerBase"),
            new KnownElement(691,  "System.Windows.Markup.TypeExtension"),
            new KnownElement(692,  "System.Windows.Markup.TypeTypeConverter"),
            new KnownElement(693,  "System.Windows.Documents.Typography"),
            new KnownElement(694,  "System.Windows.UIElement"),
            new KnownElement(695,  "System.UInt16"),
            new KnownElement(696,  "System.ComponentModel.UInt16Converter"),
            new KnownElement(697,  "System.UInt32"),
            new KnownElement(698,  "System.ComponentModel.UInt32Converter"),
            new KnownElement(699,  "System.UInt64"),
            new KnownElement(700,  "System.ComponentModel.UInt64Converter"),
            new KnownElement(701,  "System.Windows.Media.Converters.UShortIListConverter"),
            new KnownElement(702,  "System.Windows.Documents.Underline"),
            new KnownElement(703,  "System.Windows.Controls.Primitives.UniformGrid"),
            new KnownElement(704,  "System.Uri"),
            new KnownElement(705,  "System.UriTypeConverter"),
            new KnownElement(706,  "System.Windows.Controls.UserControl"),
            new KnownElement(707,  "System.Windows.Controls.Validation"),
            new KnownElement(708,  "System.Windows.Vector"),
            new KnownElement(709,  "System.Windows.Media.Media3D.Vector3D"),
            new KnownElement(710,  "System.Windows.Media.Animation.Vector3DAnimation"),
            new KnownElement(711,  "System.Windows.Media.Animation.Vector3DAnimationBase"),
            new KnownElement(712,  "System.Windows.Media.Animation.Vector3DAnimationUsingKeyFrames"),
            new KnownElement(713,  "System.Windows.Media.Media3D.Vector3DCollection"),
            new KnownElement(714,  "System.Windows.Media.Media3D.Vector3DCollectionConverter"),
            new KnownElement(715,  "System.Windows.Media.Media3D.Vector3DConverter"),
            new KnownElement(716,  "System.Windows.Media.Animation.Vector3DKeyFrame"),
            new KnownElement(717,  "System.Windows.Media.Animation.Vector3DKeyFrameCollection"),
            new KnownElement(718,  "System.Windows.Media.Animation.VectorAnimation"),
            new KnownElement(719,  "System.Windows.Media.Animation.VectorAnimationBase"),
            new KnownElement(720,  "System.Windows.Media.Animation.VectorAnimationUsingKeyFrames"),
            new KnownElement(721,  "System.Windows.Media.VectorCollection"),
            new KnownElement(722,  "System.Windows.Media.VectorCollectionConverter"),
            new KnownElement(723,  "System.Windows.VectorConverter"),
            new KnownElement(724,  "System.Windows.Media.Animation.VectorKeyFrame"),
            new KnownElement(725,  "System.Windows.Media.Animation.VectorKeyFrameCollection"),
            new KnownElement(726,  "System.Windows.Media.VideoDrawing"),
            new KnownElement(727,  "System.Windows.Controls.ViewBase"),
            new KnownElement(728,  "System.Windows.Controls.Viewbox"),
            new KnownElement(729,  "System.Windows.Controls.Viewport3D"),
            new KnownElement(730,  "System.Windows.Media.Media3D.Viewport3DVisual"),
            new KnownElement(731,  "System.Windows.Controls.VirtualizingPanel"),
            new KnownElement(732,  "System.Windows.Controls.VirtualizingStackPanel"),
            new KnownElement(733,  "System.Windows.Media.Visual"),
            new KnownElement(734,  "System.Windows.Media.Media3D.Visual3D"),
            new KnownElement(735,  "System.Windows.Media.VisualBrush"),
            new KnownElement(736,  "System.Windows.Media.VisualTarget"),
            new KnownElement(737,  "System.Windows.WeakEventManager"),
            new KnownElement(738,  "System.Windows.Markup.WhitespaceSignificantCollectionAttribute"),
            new KnownElement(739,  "System.Windows.Window"),
            new KnownElement(740,  "System.Windows.Media.Imaging.WmpBitmapDecoder"),
            new KnownElement(741,  "System.Windows.Media.Imaging.WmpBitmapEncoder"),
            new KnownElement(742,  "System.Windows.Controls.WrapPanel"),
            new KnownElement(743,  "System.Windows.Media.Imaging.WriteableBitmap"),
            new KnownElement(744,  "System.Windows.Markup.XamlBrushSerializer"),
            new KnownElement(745,  "System.Windows.Markup.XamlInt32CollectionSerializer"),
            new KnownElement(746,  "System.Windows.Markup.XamlPathDataSerializer"),
            new KnownElement(747,  "System.Windows.Markup.XamlPoint3DCollectionSerializer"),
            new KnownElement(748,  "System.Windows.Markup.XamlPointCollectionSerializer"),
            new KnownElement(749,  "System.Windows.Markup.XamlReader"),
            new KnownElement(750,  "System.Windows.Markup.XamlStyleSerializer"),
            new KnownElement(751,  "System.Windows.Markup.XamlTemplateSerializer"),
            new KnownElement(752,  "System.Windows.Markup.XamlVector3DCollectionSerializer"),
            new KnownElement(753,  "System.Windows.Markup.XamlWriter"),
            new KnownElement(754,  "System.Windows.Data.XmlDataProvider"),
            new KnownElement(755,  "System.Windows.Markup.XmlLangPropertyAttribute"),
            new KnownElement(756,  "System.Windows.Markup.XmlLanguage"),
            new KnownElement(757,  "System.Windows.Markup.XmlLanguageConverter"),
            new KnownElement(758,  "System.Windows.Data.XmlNamespaceMapping"),
            new KnownElement(759,  "System.Windows.Documents.ZoomPercentageConverter"),
        };
        }
    }
}


<|start_filename|>Sample Applications/PhotoViewerDemo/ExposureModeConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace PhotoViewerDemo
{
    /// <summary>
    ///     Converts an exposure mode from an enum into a human-readable string (e.g. AperturePriority
    ///     becomes "Aperture Priority")
    /// </summary>
    public class ExposureModeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var exposureMode = (ExposureMode) value;

            switch (exposureMode)
            {
                case ExposureMode.AperturePriority:
                    return "Aperture Priority";

                case ExposureMode.HighSpeedMode:
                    return "High Speed Mode";

                case ExposureMode.LandscapeMode:
                    return "Landscape Mode";

                case ExposureMode.LowSpeedMode:
                    return "Low Speed Mode";

                case ExposureMode.Manual:
                    return "Manual";

                case ExposureMode.NormalProgram:
                    return "Normal";

                case ExposureMode.PortraitMode:
                    return "Portrait";

                case ExposureMode.ShutterPriority:
                    return "Shutter Priority";

                default:
                    return "Unknown";
            }
        }

        public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/CosineExpression.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    /// <summary>
    ///     Evaluate the cosine of an expression.
    /// </summary>
    public sealed class CosineExpression : UnaryExpression
    {
        public CosineExpression(IExpression child) : base(child)
        {
        }

        protected override double Operate(double d) => Math.Cos(d);

        public override IExpression Differentiate(string byVar) => new MultExpression(new NegateExpression(new SineExpression(child)),
                child.Differentiate(byVar));

        public override IExpression Simplify()
        {
            var newChild = child.Simplify();
            var childConst = newChild as ConstantExpression;

            if (childConst != null)
            {
                // child is constant;  just evaluate it;
                return new ConstantExpression(Math.Cos(childConst.Value));
            }
            return new CosineExpression(newChild);
        }

        public override string ToString() => "cos(" + child.ToString() + ")";
    }
}

<|start_filename|>Migration and Interoperability/WindowsFormsHostingWpfControl/FormsApp/Program.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

#region Using directives

using System;
using System.Windows.Forms;

#endregion

namespace FormsApp
{
    internal static class Program
    {
        [STAThread]
        private static void Main()
        {
            //Run the application
            Application.EnableVisualStyles();
            //System.Windows.Forms.Application.EnableRTLMirroring();
            Application.Run(new Form1());
        }
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/FunctionWireframeModel.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows.Media.Media3D;

namespace GraphingCalculatorDemo.Parser
{
    public class FunctionWireframeModel
    {
        private double _du;
        private double _dv;
        // - - - - - - - - - - - - - - - - - - - - - - - - - -

        private IExpression _fx;
        private IExpression _fxDu;
        private IExpression _fxDv;
        private IExpression _fy;
        private IExpression _fyDu;
        private IExpression _fyDv;
        private IExpression _fz;
        private IExpression _fzDu;
        private IExpression _fzDv;
        private int _lengthX;
        private int _lengthY;
        private Point3D[,] _positions;
        protected double UMax;
        // - - - - - - - - - - - - - - - - - - - - - - - - - -

        protected double UMin;
        protected double VMax;
        protected double VMin;

        protected FunctionWireframeModel()
        {
            // We open this class up for extension only by those who promise to call Init
            //  at some time during their constructors.  If they do not, CreateMesh will fail.
        }

        public FunctionWireframeModel(
            string fx,
            string fy,
            string fz,
            double uMin,
            double uMax,
            double vMin,
            double vMax
            )
        {
            Init(
                FunctionParser.Parse(fx),
                FunctionParser.Parse(fy),
                FunctionParser.Parse(fz),
                uMin,
                uMax,
                vMin,
                vMax
                );
        }

        protected Point3D this[int x, int y] => _positions[x, y];

        protected void Init(
            IExpression fx,
            IExpression fy,
            IExpression fz,
            double uMin,
            double uMax,
            double vMin,
            double vMax
            )
        {
            _fx = fx.Simplify();
            _fy = fy.Simplify();
            _fz = fz.Simplify();

            _fxDu = _fx.Differentiate("u").Simplify();
            _fxDv = _fx.Differentiate("v").Simplify();
            _fyDu = _fy.Differentiate("u").Simplify();
            _fyDv = _fy.Differentiate("v").Simplify();
            _fzDu = _fz.Differentiate("u").Simplify();
            _fzDv = _fz.Differentiate("v").Simplify();

            UMin = uMin;
            UMax = uMax;
            VMin = vMin;
            VMax = vMax;
        }

        /// <summary>
        ///     Creates a mesh with a horizontal and vertical resolution indicated
        ///     by the input parameters.  It will generate
        ///     (precisionU-1)*(precisionV-1) quads.
        /// </summary>
        public Model3DGroup CreateWireframeModel(int precisionU, int precisionV)
        {
            _lengthX = precisionU;
            _lengthY = precisionV;
            _du = (UMax - UMin)/(precisionU - 1);
            _dv = (VMax - VMin)/(precisionV - 1);

            _positions = new Point3D[_lengthX, _lengthY];

            var v = VMin;
            for (var y = 0; y < _lengthY; y++)
            {
                var u = UMin;
                if (y == _lengthY - 1)
                {
                    v = VMax;
                }
                for (var x = 0; x < _lengthX; x++)
                {
                    if (x == _lengthX - 1)
                    {
                        u = UMax;
                    }
                    VariableExpression.Define("u", u);
                    VariableExpression.Define("v", v);
                    _positions[x, y] = Evaluate();
                    u += _du;
                }
                v += _dv;
            }
            VariableExpression.Undefine("u");
            VariableExpression.Undefine("v");

            var group = new Model3DGroup();

            // TODO: Remove
            //ScreenSpaceLines3D lines;
            /*
            // Create Horizontal lines
            for ( int y = 0; y < lengthY; y++ )
            {
                lines = new ScreenSpaceLines3D();
                lines.Color = Colors.Black;
                lines.Thickness = 1;
                for ( int x = 0; x < lengthX; x++ )
                {
                    lines.Points.Add( positions[ x,y ] );
                }
                group.Children.Add( lines );
            }

            // Create Vertical lines
            for ( int x = 0; x < lengthX; x++ )
            {
                lines = new ScreenSpaceLines3D();
                lines.Color = Colors.Black;
                lines.Thickness = 1;
                for ( int y = 0; y < lengthY; y++ )
                {
                    lines.Points.Add( positions[ x,y ] );
                }
                group.Children.Add( lines );
            }
            */

            return group;
        }

        /// <summary>
        ///     Evaluates the mesh position at the indicated parameters.
        /// </summary>
        private Point3D Evaluate()
        {
            var p = new Point3D
            {
                X = _fx.Evaluate(),
                Y = _fy.Evaluate(),
                Z = _fz.Evaluate()
            };


            return p;
        }
    }
}

<|start_filename|>Data Binding/DataBindingToStringFomat/PurchaseItem.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace DataBindingToStringFomat
{
    public class PurchaseItem
    {
        public PurchaseItem()
        {
        }

        public PurchaseItem(string desc, double price, DateTime endDate)
        {
            Description = desc;
            Price = price;
            OfferExpires = endDate;
        }

        public string Description { get; set; }
        public double Price { get; set; }
        public DateTime OfferExpires { get; set; }

        public override string ToString() => $"{Description}, {Price:c}, {OfferExpires:D}";
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/Sphere.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    //--------------------------------------------------------------

    public sealed class Sphere : FunctionMesh
    {
        public Sphere(double radius)
        {
            Init(new MultExpression(new ConstantExpression(radius), FunctionParser.Parse("cos(u)sin(v)")),
                new MultExpression(new ConstantExpression(radius), FunctionParser.Parse("-cos(v)")),
                new MultExpression(new ConstantExpression(radius), FunctionParser.Parse("sin(-u)sin(v)")),
                -Math.PI, Math.PI, 0.0, Math.PI);
        }
    }

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    //--------------------------------------------------------------

    /*
    public class                Apple : Function
    {
        // This will throw.  I don't support log(x) function yet
        public                  Apple( double radius )
        {
            Init( new MultExpression( radius * 0.125, FunctionParser.Parse( "cos(u)(4+3.8cos(v))" ) ),
                  new MultExpression( radius * 0.125, FunctionParser.Parse( "(cos(v)+sin(-v)-1)(1+sin(-v))log(1-pi*v/10)+7.5sin(-v)" ) ),
                  new MultExpression( radius * 0.125, FunctionParser.Parse( "sin(-u)(4+3.8cos(v))" ) ),
                  -Math.PI, Math.PI, 0.0, Math.PI )
        }
    }
    */
}

<|start_filename|>Input and Commands/ICommandSourceImplementation/FontStringValueConverter.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Globalization;
using System.Windows.Data;

namespace ICommandSourceImplementation
{
    [ValueConversion(typeof (double), typeof (int))]
    public class FontStringValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var fontSize = (string) value;
            int intFont;

            try
            {
                intFont = int.Parse(fontSize);
                return intFont;
            }
            catch (FormatException e)
            {
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}

<|start_filename|>Input and Commands/EditingCommands/MainWindow.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls;

namespace EditingCommands
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ExecuteCommand(object sender, RoutedEventArgs args)
        {
            var command = ((Button) sender).Name;

            var target = routeToRTB.IsChecked.Value
                ? sampleRTB
                : (routeToTB.IsChecked.Value ? sampleTB : samplePWB as IInputElement);

            switch (command)
            {
                // Paragraph Alignment
                case "AlignCenter":
                    System.Windows.Documents.EditingCommands.AlignCenter.Execute(null, target);
                    break;
                case "AlignJustify":
                    System.Windows.Documents.EditingCommands.AlignJustify.Execute(null, target);
                    break;
                case "AlignRight":
                    System.Windows.Documents.EditingCommands.AlignRight.Execute(null, target);
                    break;
                case "AlignLeft":
                    System.Windows.Documents.EditingCommands.AlignLeft.Execute(null, target);
                    break;

                //Caret Movement by Line
                case "MoveUpByLine":
                    System.Windows.Documents.EditingCommands.MoveUpByLine.Execute(null, target);
                    break;
                case "MoveDownByLine":
                    System.Windows.Documents.EditingCommands.MoveDownByLine.Execute(null, target);
                    break;
                case "MoveToLineEnd":
                    System.Windows.Documents.EditingCommands.MoveToLineEnd.Execute(null, target);
                    break;
                case "MoveToLineStart":
                    System.Windows.Documents.EditingCommands.MoveToLineStart.Execute(null, target);
                    break;

                //Caret Movement by Character
                case "MoveLeftByCharacter":
                    System.Windows.Documents.EditingCommands.MoveLeftByCharacter.Execute(null, target);
                    break;
                case "MoveRightByCharacter":
                    System.Windows.Documents.EditingCommands.MoveRightByCharacter.Execute(null, target);
                    break;

                //Caret Movement by Word
                case "MoveLeftByWord":
                    System.Windows.Documents.EditingCommands.MoveLeftByWord.Execute(null, target);
                    break;
                case "MoveRightByWord":
                    System.Windows.Documents.EditingCommands.MoveRightByWord.Execute(null, target);
                    break;

                //Caret Movement by Paragraph
                case "MoveUpByParagraph":
                    System.Windows.Documents.EditingCommands.MoveUpByParagraph.Execute(null, target);
                    break;
                case "MoveDownByParagraph":
                    System.Windows.Documents.EditingCommands.MoveDownByParagraph.Execute(null, target);
                    break;

                //Caret Movement by Page
                case "MoveUpByPage":
                    System.Windows.Documents.EditingCommands.MoveUpByPage.Execute(null, target);
                    break;
                case "MoveDownByPage":
                    System.Windows.Documents.EditingCommands.MoveDownByPage.Execute(null, target);
                    break;

                //Caret Movement by Document
                case "MoveToDocumentEnd":
                    System.Windows.Documents.EditingCommands.MoveToDocumentEnd.Execute(null, target);
                    break;
                case "MoveToDocumentStart":
                    System.Windows.Documents.EditingCommands.MoveToDocumentStart.Execute(null, target);
                    break;

                //Deletion
                case "Delete":
                    System.Windows.Documents.EditingCommands.Delete.Execute(null, target);
                    break;
                case "DeleteNextWord":
                    System.Windows.Documents.EditingCommands.DeleteNextWord.Execute(null, target);
                    break;
                case "DeletePreviousWord":
                    System.Windows.Documents.EditingCommands.DeletePreviousWord.Execute(null, target);
                    break;

                //Spelling Errors
                case "CorrectSpellingError":
                    System.Windows.Documents.EditingCommands.CorrectSpellingError.Execute(null, target);
                    break;
                case "IgnoreSpellingError":
                    System.Windows.Documents.EditingCommands.IgnoreSpellingError.Execute(null, target);
                    break;

                //Toggle Insert
                case "ToggleInsert":
                    System.Windows.Documents.EditingCommands.ToggleInsert.Execute(null, target);
                    break;

                //Symbol Entry
                case "Backspace":
                    System.Windows.Documents.EditingCommands.Backspace.Execute(null, target);
                    break;
                case "EnterLineBreak":
                    System.Windows.Documents.EditingCommands.EnterLineBreak.Execute(null, target);
                    break;
                case "EnterParagraphBreak":
                    System.Windows.Documents.EditingCommands.EnterParagraphBreak.Execute(null, target);
                    break;
                case "TabBackward":
                    System.Windows.Documents.EditingCommands.TabBackward.Execute(null, target);
                    break;
                case "TabForward":
                    System.Windows.Documents.EditingCommands.TabForward.Execute(null, target);
                    break;

                //Paragraph Formatting
                case "IncreaseIndentation":
                    System.Windows.Documents.EditingCommands.IncreaseIndentation.Execute(null, target);
                    break;
                case "DecreaseIndentation":
                    System.Windows.Documents.EditingCommands.DecreaseIndentation.Execute(null, target);
                    break;
                case "ToggleBullets":
                    System.Windows.Documents.EditingCommands.ToggleBullets.Execute(null, target);
                    break;
                case "ToggleNumbering":
                    System.Windows.Documents.EditingCommands.ToggleNumbering.Execute(null, target);
                    break;

                //Formatting
                case "IncreaseFontSize":
                    System.Windows.Documents.EditingCommands.IncreaseFontSize.Execute(null, target);
                    break;
                case "DecreaseFontSize":
                    System.Windows.Documents.EditingCommands.DecreaseFontSize.Execute(null, target);
                    break;
                case "ToggleBold":
                    System.Windows.Documents.EditingCommands.ToggleBold.Execute(null, target);
                    break;
                case "ToggleItalic":
                    System.Windows.Documents.EditingCommands.ToggleItalic.Execute(null, target);
                    break;
                case "ToggleSubscript":
                    System.Windows.Documents.EditingCommands.ToggleSubscript.Execute(null, target);
                    break;
                case "ToggleSuperscript":
                    System.Windows.Documents.EditingCommands.ToggleSuperscript.Execute(null, target);
                    break;
                case "ToggleUnderline":
                    System.Windows.Documents.EditingCommands.ToggleUnderline.Execute(null, target);
                    break;


                //Selection by Line
                case "SelectUpByLine":
                    System.Windows.Documents.EditingCommands.SelectUpByLine.Execute(null, target);
                    break;
                case "SelectDownByLine":
                    System.Windows.Documents.EditingCommands.SelectDownByLine.Execute(null, target);
                    break;
                case "SelectToLineEnd":
                    System.Windows.Documents.EditingCommands.SelectToLineEnd.Execute(null, target);
                    break;
                case "SelectToLineStart":
                    System.Windows.Documents.EditingCommands.SelectToLineStart.Execute(null, target);
                    break;

                //Selection by Character
                case "SelectLeftByCharacter":
                    System.Windows.Documents.EditingCommands.SelectLeftByCharacter.Execute(null, target);
                    break;
                case "SelectRightByCharacter":
                    System.Windows.Documents.EditingCommands.SelectRightByCharacter.Execute(null, target);
                    break;

                //Caret Selection by Word
                case "SelectLeftByWord":
                    System.Windows.Documents.EditingCommands.SelectLeftByWord.Execute(null, target);
                    break;
                case "SelectRightByWord":
                    System.Windows.Documents.EditingCommands.SelectRightByWord.Execute(null, target);
                    break;

                //Selection by Paragraph
                case "SelectUpByParagraph":
                    System.Windows.Documents.EditingCommands.SelectUpByParagraph.Execute(null, target);
                    break;
                case "SelectDownByParagraph":
                    System.Windows.Documents.EditingCommands.SelectDownByParagraph.Execute(null, target);
                    break;

                //Selection by Page
                case "SelectUpByPage":
                    System.Windows.Documents.EditingCommands.SelectUpByPage.Execute(null, target);
                    break;
                case "SelectDownByPage":
                    System.Windows.Documents.EditingCommands.SelectDownByPage.Execute(null, target);
                    break;

                //Selection by Document
                case "SelectToDocumentEnd":
                    System.Windows.Documents.EditingCommands.SelectToDocumentEnd.Execute(null, target);
                    break;
                case "SelectToDocumentStart":
                    System.Windows.Documents.EditingCommands.SelectToDocumentStart.Execute(null, target);
                    break;
            }

            target.Focus();
        }
    }
}

<|start_filename|>Sample Applications/PhotoStoreDemo/PrintBase.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;
using System.Windows.Media.Imaging;

namespace PhotoStoreDemo
{
    public class PrintBase : INotifyPropertyChanged
    {
        private BitmapSource _photo;
        private PrintType _printType;
        private int _quantity;

        public PrintBase(BitmapSource photo, PrintType printtype, int quantity)
        {
            Photo = photo;
            PrintType = printtype;
            Quantity = quantity;
        }

        public PrintBase(BitmapSource photo, string description, double cost)
        {
            Photo = photo;
            PrintType = new PrintType(description, cost);
            Quantity = 0;
        }

        public BitmapSource Photo
        {
            set
            {
                _photo = value;
                OnPropertyChanged("Photo");
            }
            get { return _photo; }
        }

        public PrintType PrintType
        {
            set
            {
                _printType = value;
                OnPropertyChanged("PrintType");
            }
            get { return _printType; }
        }

        public int Quantity
        {
            set
            {
                _quantity = value;
                OnPropertyChanged("Quantity");
            }
            get { return _quantity; }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string info)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
        }

        public override string ToString() => PrintType.ToString();
    }
}

<|start_filename|>Sample Applications/GraphingCalculatorDemo/Parser/Cone.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;

namespace GraphingCalculatorDemo.Parser
{
    public sealed class Cone : FunctionMesh
    {
        public Cone(double radius, double height)
        {
            IExpression fx = new MultExpression(
                new MultExpression(
                    new SubExpression(
                        new ConstantExpression(height),
                        new VariableExpression("v")),
                    new ConstantExpression(radius/height)),
                new CosineExpression(
                    new VariableExpression("u")));
            IExpression fy = new VariableExpression("v");
            IExpression fz = new MultExpression(
                new MultExpression(
                    new SubExpression(
                        new ConstantExpression(height),
                        new VariableExpression("v")),
                    new ConstantExpression(radius/height)),
                new SineExpression(
                    new NegateExpression(
                        new VariableExpression("u"))));

            Init(fx, fy, fz, -Math.PI, Math.PI, 0.0, height);
        }
    }
}

<|start_filename|>Sample Applications/HtmlToXamlDemo/HtmlEncodedTextWriter.cs<|end_filename|>
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;

namespace HtmlToXamlDemo
{
    public class HtmlEncodedTextWriter : XmlTextWriter
    {
        public HtmlEncodedTextWriter(TextWriter w) : base(w) { }

        #region Overrides of XmlTextWriter

        /// <inheritdoc />
        public override void WriteString(string text)
        {
            text = WebUtility.HtmlEncode(text);
            WriteRaw(text);
        }

        #endregion
    }
}


<|start_filename|>Properties/CustomClassesWithDP/ButtonColors.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace CustomClassesWithDP
{
    public enum ButtonColors
    {
        None,
        Black,
        White,
        Brown,
        Gray
    }
}

<|start_filename|>Sample Applications/SlidePuzzleDemo/Puzzle.cs<|end_filename|>
﻿// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;

namespace SlidePuzzleDemo
{
    /// <summary>
    ///     Interaction logic for Puzzle.xaml
    /// </summary>
    public partial class Puzzle : Window
    {
        private void PuzzleSourceChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = (ComboBox) sender;
            var item = (ComboBoxItem) cb.SelectedValue;
            var tag = (string) item.Tag;

            _stylingPuzzle = true;

            if (_masterVideoElement != null)
            {
                _masterVideoElement.Stop();
                _masterVideoElement = null;
            }

            switch (tag)
            {
                case "Untemplated":
                    _stylingPuzzle = false;
                    break;

                case "StaticBitmap":
                {
                    var masterImage = (Image) Resources["MasterImage"];
                    _elementToChopUp = masterImage;
                    var bitmap = (BitmapSource) masterImage.Source;
                    _puzzleSize = new Size(bitmap.PixelWidth/1.5, bitmap.PixelHeight/1.5);
                }
                    break;

                case "StaticVectorContent":
                {
                    _elementToChopUp = new VectorContent();
                    _puzzleSize = new Size(500, 500);
                }
                    break;

                case "VideoContent":
                {
                    _elementToChopUp = PrepareVideoElement(out _puzzleSize);
                }
                    break;

                case "AnimateVectorContent":
                {
                    var vc = new VectorContent();

                    // Must explicitly start storyboards that only appear in VisualBrushes
                    vc.BeginStoryboard(vc.MyStoryboard);

                    _elementToChopUp = vc;
                    _puzzleSize = new Size(500, 500);
                }

                    break;

                case "Document":
                {
                    FrameworkElement elt = new Document();
                    _elementToChopUp = elt;
                    _puzzleSize = new Size(elt.Width, elt.Height);
                }
                    break;

                case "FormsContent":
                {
                    FrameworkElement elt = new FormContent();
                    _elementToChopUp = elt;
                    _puzzleSize = new Size(700, 500);
                }
                    break;

                case "SpinningCube":
                {
                    var vc = new VectorContent();
                    vc.BeginStoryboard(vc.MyStoryboard);
                    // Must explicitly start storyboards that only appear in VisualBrushes
                    var masterImage = (Image) Resources["TableImage"];

                    var sc = new SpinningCube
                    {
                        CubeMaterial = {Brush = new ImageBrush(masterImage.Source)},
                        CubeMaterial2 = {Brush = new VisualBrush(vc)}
                    };


                    var myStoryboard = (Storyboard) sc.Resources["MyStoryboard"];
                    sc.BeginStoryboard(myStoryboard);
                    // Must explicitly start storyboards that only appear in VisualBrushes
                    _elementToChopUp = sc;
                    _puzzleSize = new Size(500, 500);
                }

                    break;

                default:
                    Debug.Assert(false, "Unexpected Puzzle Source");
                    break;
            }

            NewPuzzleGrid();
        }

        private UIElement PrepareVideoElement(out Size resultingSize)
        {
            _masterVideoElement = (MediaElement) Resources["MasterVideo"];
            _masterVideoElement.UnloadedBehavior = MediaState.Manual;


            resultingSize = new Size(_masterVideoElement.Width, _masterVideoElement.Height);

            _masterVideoElement.Play();

            return _masterVideoElement;
        }

        private void OnMoveMade(object sender, HandledEventArgs e)
        {
            // Blur or unblur based on whether the move was a valid one.
            var blur = (DropShadowEffect)StatusLabel.Effect;
            if (blur != null)
            {
                if (e.Handled)
                {
                    blur.BlurRadius = 0.0;
                    StatusLabel.Content = "";
                }
                else
                {
                    if (blur.BlurRadius >= 4.0) blur.BlurRadius = 2.0; else blur.BlurRadius = 4.0;
                    StatusLabel.Content = "Bad Move!";
                }
            }
        }

        private void NewPuzzleGrid()
        {
            if (_puzzleGrid != null)
            {
                PuzzleHostingPanel.Children.Remove(_puzzleGrid);
            }
            _puzzleGrid = new PuzzleGrid();
            _puzzleGrid.PuzzleWon += delegate { StatusLabel.Content = "Got it!!!"; };

            _puzzleGrid.MoveMade += OnMoveMade;

            _puzzleGrid.IsApplyingStyle = _stylingPuzzle;
            _puzzleGrid.NumRows = _numRows;

            _puzzleGrid.ElementToChopUp = _elementToChopUp;
            _puzzleGrid.PuzzleSize = _puzzleSize;

            _puzzleGrid.ShowNumbers(ChkShowNumbers.IsChecked.Value);

            _puzzleGrid.ShouldAnimateInteractions = ChkShowAnimations.IsChecked.Value;

            PuzzleHostingPanel.Children.Add(_puzzleGrid);
            StatusLabel.Content = "New " + _numRows + "x" + _numRows + " game";
        }

        #region Less Consequential Event Handlers

        private void OnMixUp(object sender, RoutedEventArgs e)
        {
            _puzzleGrid.MixUpPuzzle();
        }

        private void OnResetPuzzle(object sender, RoutedEventArgs e)
        {
            NewPuzzleGrid();
        }

        private void OnShowHideNumbers(object sender, RoutedEventArgs e)
        {
            var cb = (CheckBox) sender;
            _puzzleGrid.ShowNumbers(cb.IsChecked.Value);
        }

        private void OnChkAnimation(object sender, RoutedEventArgs e)
        {
            var cb = (CheckBox) sender;
            _puzzleGrid.ShouldAnimateInteractions = cb.IsChecked.Value;
        }

        private void PuzzleDimensionsChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = (ComboBox) sender;
            var item = (ComboBoxItem) cb.SelectedValue;
            var tag = (string) item.Tag;
            _numRows = int.Parse(tag);
            NewPuzzleGrid();
        }

        #endregion

        #region Private Data and Boilerplate

        public Puzzle()
        {
            InitializeComponent();
            var dropShadow = new DropShadowEffect();
            dropShadow.ShadowDepth = 0;
            dropShadow.BlurRadius = 0;
            dropShadow.Color = Colors.Red;
            StatusLabel.Effect = dropShadow;
        }

        private PuzzleGrid _puzzleGrid;
        private UIElement _elementToChopUp;
        private Size _puzzleSize;
        private bool _stylingPuzzle;
        private int _numRows;

        private MediaElement _masterVideoElement;

        #endregion
    }
}

<|start_filename|>Sample Applications/PhotoViewerDemo/CroppingAdorner.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace PhotoViewerDemo
{
    // Adorner based on the ResizingAdorner in the SDK sample
    public class CroppingAdorner : Adorner
    {
        private readonly Thumb _bottomLeft;
        private readonly Thumb _bottomRight;
        // Cropping adorner uses Thumbs for visual elements.  
        // The Thumbs have built-in mouse input handling.
        private readonly Thumb _topLeft;
        private readonly Thumb _topRight;
        // To store and manage the adorner's visual children.
        private readonly VisualCollection _visualChildren;
        // Initialize the CroppingAdorner.
        public CroppingAdorner(UIElement adornedElement)
            : base(adornedElement)
        {
            _visualChildren = new VisualCollection(this);

            // Call a helper method to initialize the Thumbs
            // with a customized cursors.
            BuildAdornerCorner(ref _topLeft, Cursors.SizeNWSE);
            BuildAdornerCorner(ref _topRight, Cursors.SizeNESW);
            BuildAdornerCorner(ref _bottomLeft, Cursors.SizeNESW);
            BuildAdornerCorner(ref _bottomRight, Cursors.SizeNWSE);

            // Add handlers for resizing.
            _bottomLeft.DragDelta += HandleBottomLeft;
            _bottomRight.DragDelta += HandleBottomRight;
            _topLeft.DragDelta += HandleTopLeft;
            _topRight.DragDelta += HandleTopRight;
        }

        // Override the VisualChildrenCount and GetVisualChild properties to interface with 
        // the adorner's visual collection.
        protected override int VisualChildrenCount => _visualChildren.Count;
        // Handler for resizing from the bottom-right.
        private void HandleBottomRight(object sender, DragDeltaEventArgs args)
        {
            var adornedElement = AdornedElement as FrameworkElement;
            var hitThumb = sender as Thumb;

            if (adornedElement == null || hitThumb == null) return;
            var parentElement = adornedElement.Parent as FrameworkElement;

            // Ensure that the Width and Height are properly initialized after the resize.
            EnforceSize(adornedElement);

            // Change the size by the amount the user drags the mouse, as long as it's larger 
            // than the width or height of an adorner, respectively.
            //adornedElement.Width = Math.Max(adornedElement.Width + args.HorizontalChange, hitThumb.DesiredSize.Width);
            //adornedElement.Height = Math.Max(args.VerticalChange + adornedElement.Height, hitThumb.DesiredSize.Height);
        }

        // Handler for resizing from the bottom-left.
        private void HandleBottomLeft(object sender, DragDeltaEventArgs args)
        {
            var adornedElement = AdornedElement as FrameworkElement;
            var hitThumb = sender as Thumb;

            if (adornedElement == null || hitThumb == null) return;

            // Ensure that the Width and Height are properly initialized after the resize.
            EnforceSize(adornedElement);

            // Change the size by the amount the user drags the mouse, as long as it's larger 
            // than the width or height of an adorner, respectively.
            //adornedElement.Width = Math.Max(adornedElement.Width - args.HorizontalChange, hitThumb.DesiredSize.Width);
            //adornedElement.Height = Math.Max(args.VerticalChange + adornedElement.Height, hitThumb.DesiredSize.Height);
        }

        // Handler for resizing from the top-right.
        private void HandleTopRight(object sender, DragDeltaEventArgs args)
        {
            var adornedElement = AdornedElement as FrameworkElement;
            var hitThumb = sender as Thumb;

            if (adornedElement == null || hitThumb == null) return;
            var parentElement = adornedElement.Parent as FrameworkElement;

            // Ensure that the Width and Height are properly initialized after the resize.
            EnforceSize(adornedElement);

            // Change the size by the amount the user drags the mouse, as long as it's larger 
            // than the width or height of an adorner, respectively.
            //adornedElement.Width = Math.Max(adornedElement.Width + args.HorizontalChange, hitThumb.DesiredSize.Width);
            //adornedElement.Height = Math.Max(adornedElement.Height - args.VerticalChange, hitThumb.DesiredSize.Height);
        }

        // Handler for resizing from the top-left.
        private void HandleTopLeft(object sender, DragDeltaEventArgs args)
        {
            var adornedElement = AdornedElement as FrameworkElement;
            var hitThumb = sender as Thumb;

            if (adornedElement == null || hitThumb == null) return;

            // Ensure that the Width and Height are properly initialized after the resize.
            EnforceSize(adornedElement);

            // Change the size by the amount the user drags the mouse, as long as it's larger 
            // than the width or height of an adorner, respectively.
            //adornedElement.Width = Math.Max(adornedElement.Width - args.HorizontalChange, hitThumb.DesiredSize.Width);
            //adornedElement.Height = Math.Max(adornedElement.Height - args.VerticalChange, hitThumb.DesiredSize.Height);
        }

        // Arrange the Adorners.
        protected override Size ArrangeOverride(Size finalSize)
        {
            // desiredWidth and desiredHeight are the width and height of the element that's being adorned.  
            // These will be used to place the ResizingAdorner at the corners of the adorned element.  
            var desiredWidth = AdornedElement.DesiredSize.Width;
            var desiredHeight = AdornedElement.DesiredSize.Height;
            // adornerWidth & adornerHeight are used for placement as well.
            var adornerWidth = DesiredSize.Width;
            var adornerHeight = DesiredSize.Height;

            _topLeft.Arrange(new Rect(-adornerWidth/2, -adornerHeight/2, adornerWidth, adornerHeight));
            _topRight.Arrange(new Rect(desiredWidth - adornerWidth/2, -adornerHeight/2, adornerWidth, adornerHeight));
            _bottomLeft.Arrange(new Rect(-adornerWidth/2, desiredHeight - adornerHeight/2, adornerWidth, adornerHeight));
            _bottomRight.Arrange(new Rect(desiredWidth - adornerWidth/2, desiredHeight - adornerHeight/2, adornerWidth,
                adornerHeight));

            // Return the final size.
            return finalSize;
        }

        // Helper method to instantiate the corner Thumbs, set the Cursor property, 
        // set some appearance properties, and add the elements to the visual tree.
        private void BuildAdornerCorner(ref Thumb cornerThumb, Cursor customizedCursor)
        {
            if (cornerThumb != null) return;

            cornerThumb = new Thumb {Cursor = customizedCursor};

            // Set some arbitrary visual characteristics.
            cornerThumb.Height = cornerThumb.Width = 10;
            cornerThumb.Opacity = 0.40;
            cornerThumb.Background = new SolidColorBrush(Colors.MediumBlue);

            _visualChildren.Add(cornerThumb);
        }

        // This method ensures that the Widths and Heights are initialized.  Sizing to content produces
        // Width and Height values of Double.NaN.  Because this Adorner explicitly resizes, the Width and Height
        // need to be set first.  It also sets the maximum size of the adorned element.
        private void EnforceSize(FrameworkElement adornedElement)
        {
            if (adornedElement.Width.Equals(double.NaN))
                adornedElement.Width = adornedElement.DesiredSize.Width;
            if (adornedElement.Height.Equals(double.NaN))
                adornedElement.Height = adornedElement.DesiredSize.Height;

            var parent = adornedElement.Parent as FrameworkElement;
            if (parent != null)
            {
                adornedElement.MaxHeight = parent.ActualHeight;
                adornedElement.MaxWidth = parent.ActualWidth;
            }
        }

        protected override Visual GetVisualChild(int index) => _visualChildren[index];
    }
}

<|start_filename|>Accessibility/FetchTimer/uiautomationfetcher.cs<|end_filename|>
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;

namespace FetchTimer
{
    internal class UiAutomationFetcher
    {
        // Number of properties fetched for each test.
        private const int NumberOfFetches = 5;
        // Member variables

        // Application form, for output.
        private readonly FetchTimerForm _appForm;
        private readonly AutomationElementMode _mode;
        private readonly Point _targetPoint;
        private readonly TreeScope _treeScope;
        private int _cachedPropCount;
        private int _currentPropCount;
        private int _elementCount;

        /// <summary>
        ///     Constructor.
        /// </summary>
        /// <param name="form">The application form.</param>
        /// <param name="targetPoint">The screen coordinates of the cursor.</param>
        /// <param name="scope">The TreeScope for caching.</param>
        /// <param name="mode">The mode for caching.</param>
        public UiAutomationFetcher(FetchTimerForm form,
            Point targetPt,
            TreeScope scope, AutomationElementMode cacheMode)
        {
            _appForm = form;
            _treeScope = scope;
            _targetPoint = targetPt;
            _mode = cacheMode;
        }

        public void DoWork()
        {
            long timeToGetUncached = 0;
            long timeToGetCached = 0;

            // Create a System.Diagnostics.Stopwatch.
            var stopWatchTimer = new Stopwatch();


            // TEST 1: Get the target element without caching, and retrieve
            //  current properties.

            stopWatchTimer.Start();
            AutomationElement targetNoCache = null;
            try
            {
                targetNoCache = AutomationElement.FromPoint(_targetPoint);
            }
            catch (ElementNotAvailableException)
            {
                OutputLine("Could not retrieve element.");
                return;
            }

            // Get current properties.
            _currentPropCount = 0;
            GetCurrentProperties(targetNoCache, 0);
            stopWatchTimer.Stop();
            timeToGetUncached = stopWatchTimer.Elapsed.Ticks;


            // TEST 2: Get the target element with caching, and retrieve
            //   cached properties.

            // Create CacheRequest.
            var fetchRequest = new CacheRequest();

            // Add properties to fetch.
            fetchRequest.Add(AutomationElement.NameProperty);
            fetchRequest.Add(AutomationElement.AutomationIdProperty);
            fetchRequest.Add(AutomationElement.ControlTypeProperty);
            fetchRequest.Add(AutomationElement.FrameworkIdProperty);
            fetchRequest.Add(AutomationElement.IsContentElementProperty);

            // Set options.
            fetchRequest.AutomationElementMode = _mode;
            fetchRequest.TreeScope = _treeScope;
            fetchRequest.TreeFilter = Automation.RawViewCondition;

            // Activate the CacheRequest and fetch the target.
            AutomationElement targetCached = null;
            using (fetchRequest.Activate())
            {
                stopWatchTimer.Reset();
                stopWatchTimer.Start();
                try
                {
                    targetCached = AutomationElement.FromPoint(_targetPoint);
                }
                catch (InvalidOperationException)
                {
                    OutputLine("InvalidOperationException. Could not retrieve element.");
                    return;
                }
                catch (ElementNotAvailableException)
                {
                    OutputLine("ElementNotAvailableException. Could not retrieve element.");
                    return;
                }
            } // CacheRequest is now inactive.

            // Get cached properties.
            GetCachedProperties(targetCached, true);
            stopWatchTimer.Stop();
            timeToGetCached = stopWatchTimer.Elapsed.Ticks;

            // TEST 3: Get updated cache.

            stopWatchTimer.Reset();
            stopWatchTimer.Start();
            var cacheUpdated = false;
            if (_mode == AutomationElementMode.Full)
            {
                var updatedTargetCached = targetCached.GetUpdatedCache(fetchRequest);
                GetCachedProperties(updatedTargetCached, false);
                // Fetches were counted again, so divide count by 2.
                _cachedPropCount /= 2;
                cacheUpdated = true;
                stopWatchTimer.Stop();
            }
            var updateTicks = stopWatchTimer.Elapsed.Ticks;

            // END OF TESTS. 

            // Display results

            var nameProperty = targetNoCache.Current.Name;
            var framework = targetNoCache.Current.FrameworkId;
            OutputLine("Name: " + nameProperty);
            OutputLine("Framework: " + framework);
            OutputLine(_elementCount + " cached element(s).");

            OutputLine(timeToGetUncached.ToString("N0") + " Ticks to retrieve element(s) and get "
                       + _currentPropCount + " current properties.");
            OutputLine(timeToGetCached.ToString("N0") + " Ticks to retrieve element(s) and get "
                       + _cachedPropCount + " cached properties.");

            // Show ratio between current and cached performance.
            var ratio = timeToGetUncached/(float) timeToGetCached;
            if (ratio > 2)
            {
                OutputLine("Current:Cached = " + ratio.ToString("N0") + ":1");
            }
            else
            {
                // Print with decimal.
                OutputLine("Current:Cached = " + ratio.ToString("N1") + ":1");
            }
            if (cacheUpdated)
            {
                OutputLine(updateTicks.ToString("N0") + " Ticks to update cache and get properties.");
            }
            else
            {
                OutputLine("Cannot update cache in None mode.");
            }
            OutputLine("");
        }

        /// <summary>
        ///     Walks the tree and gets properties from all elements found. Recursive.
        /// </summary>
        /// <param name="element">Node to walk.</param>
        /// <param name="depth">
        ///     Depth of this iteration (distance from initial node).
        /// </param>
        /// <remarks>
        ///     Nothing is done with the objects retrieved.
        /// </remarks>
        private void GetCurrentProperties(AutomationElement element, int depth)
        {
            if ((_treeScope == TreeScope.Element) && (depth > 0))
            {
                return;
            }
            if (((_treeScope & TreeScope.Descendants) == 0) && (depth > 1))
            {
                return;
            }
            var name = element.Current.Name;
            var id = element.Current.AutomationId;
            var controlType = element.Current.ControlType;
            var framework = element.Current.FrameworkId;
            _currentPropCount += NumberOfFetches;

            var walker = TreeWalker.ContentViewWalker;
            var elementChild = walker.GetFirstChild(element);
            while (elementChild != null)
            {
                GetCurrentProperties(elementChild, depth + 1);
                elementChild = walker.GetNextSibling(elementChild);
            }
        }

        /// <summary>
        ///     Gets a set of cached properties. Recursive.
        /// </summary>
        /// <param name="element">The target element.</param>
        /// <remarks>
        ///     Nothing is done with the objects retrieved.
        /// </remarks>
        private void GetCachedProperties(AutomationElement element, bool updateCount)
        {
            if (updateCount)
            {
                _elementCount++;
            }
            var name = element.Cached.Name;
            var s = element.Cached.AutomationId;
            var controlType = element.Cached.ControlType;
            var frame = element.Cached.FrameworkId;
            _cachedPropCount += NumberOfFetches;

            try
            {
                foreach (AutomationElement child in element.CachedChildren)
                {
                    GetCachedProperties(child, updateCount);
                }
            }
            catch (InvalidOperationException)
            {
                // Expected; there might be no CachedChildren, in which case an 
                //exception is raised when the property is accessed.
            }
        }

        /// <summary>
        ///     Prints a line of text to the textbox.
        /// </summary>
        /// <param name="outputStr">The string to print.</param>
        /// <remarks>
        ///     Must use Invoke so that UI is not being called directly from this thread.
        /// </remarks>
        private void OutputLine(string outputStr)
        {
            _appForm.Invoke(_appForm.OutputMethodInstance, outputStr + Environment.NewLine);
        }
    } // UIAutoWorker class.
}