### WPF Clock Controller Example Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-interactively-control-a-clock This is the constructor for the ClockControllerExample class, which inherits from Page. It initializes the main panel and sets it as the content of the page. ```vb ' This example shows how to interactively control ' a root clock. ' Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Shapes Imports System.Windows.Media.Animation Namespace Microsoft.Samples.Animation.TimingBehaviors Public Class ClockControllerExample Inherits Page Private ReadOnly myControllableClock As AnimationClock Private ReadOnly seekButton As Button Private ReadOnly seekAmountTextBox As TextBox Private ReadOnly timeSeekOriginListBox As ListBox Public Sub New() Dim mainPanel As New StackPanel() ``` -------------------------------- ### VB.NET WPF Storyboard Example Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-animate-a-property-by-using-a-storyboard This VB.NET code sets up a WPF page, including creating a name scope, defining UI elements like buttons and a stack panel, and initializing Storyboards for animations. It prepares the environment for animating button properties. ```vb Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Media.Animation Namespace SDKSample ' Uses a storyboard to animate the properties ' of two buttons. Public Class StoryboardExample Inherits Page Private Dim WithEvents myWidthAnimatedButton As Button Private Dim WithEvents myColorAnimatedButton As Button Private Dim myWidthAnimatedButtonStoryboard As Storyboard Private Dim myColorAnimatedButtonStoryboard As Storyboard Public Sub New() ' Create a name scope for the page. NameScope.SetNameScope(Me, New NameScope()) Me.WindowTitle = "Animate Properties using Storyboards" Dim myStackPanel As New StackPanel() myStackPanel.MinWidth = 500 myStackPanel.Margin = New Thickness(30) myStackPanel.HorizontalAlignment = HorizontalAlignment.Left Dim myTextBlock As New TextBlock() myTextBlock.Text = "Storyboard Animation Example" myStackPanel.Children.Add(myTextBlock) ' ' Create and animate the first button. ' ' Create a button. myWidthAnimatedButton = New Button() myWidthAnimatedButton.Height = 30 myWidthAnimatedButton.Width = 200 myWidthAnimatedButton.HorizontalAlignment = HorizontalAlignment.Left myWidthAnimatedButton.Content = "A Button" ' 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. myWidthAnimatedButton.Name = "myWidthAnimatedButton" ``` -------------------------------- ### Configure Visual Studio to Start External Program Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/configure-vs-to-debug-a-xaml-browser-to-call-a-web-service Specify PresentationHost.exe as the external program to start for debugging an XBAP. ```text C:\WINDOWS\System32\PresentationHost.exe ``` -------------------------------- ### Initialize and Start Generic Host in WPF (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/how-to-use-host-builder Create the host using CreateApplicationBuilder, register services, start the host, and display the main window in the Application_Startup event handler. ```C# private async void Application_Startup(object sender, StartupEventArgs e) { var builder = Host.CreateApplicationBuilder(); builder.Services.AddHostedService(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); _host = builder.Build(); await _host.StartAsync(); MainWindow mainWindow = _host.Services.GetRequiredService(); mainWindow.Show(); } ``` -------------------------------- ### Initialize and Start Generic Host in WPF (VB) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/how-to-use-host-builder Create the host using CreateApplicationBuilder, register services, start the host, and display the main window in the Application_Startup event handler. ```VB Private Async Sub Application_Startup(sender As Object, e As StartupEventArgs) Dim builder = Host.CreateApplicationBuilder() builder.Services.AddHostedService(Of SampleLifecycleService)() builder.Services.AddSingleton(Of IGreetingService, GreetingService)() builder.Services.AddSingleton(Of MainWindow)() _host = builder.Build() Await _host.StartAsync() Dim mainWindow As MainWindow = _host.Services.GetRequiredService(Of MainWindow)() mainWindow.Show() End Sub ``` -------------------------------- ### WPF Clock Control Example Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-seek-a-clock-synchronously This code sets up a basic WPF page with a rectangle, a DoubleAnimation, and an AnimationClock to control the rectangle's width. It also creates a set of buttons for controlling the animation's playback. ```vb.net Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Media.Animation Imports System.Windows.Navigation Imports System.Windows.Shapes Imports System.Data Imports System.Xml Imports System.Configuration Namespace SDKSample ''' ''' Shows how to interactively control a clock. ''' Public Class SeekAlignedToLastTickExample Inherits Page Private myClock As AnimationClock Private currentTimeIndicator As TextBlock Private seekDestination As TextBox Private rectangleWidthIndicator As TextBlock Private myRectangle As Rectangle Public Sub New() Me.WindowTitle = "Controlling a Storyboard" Me.Background = Brushes.White Dim myStackPanel As New StackPanel() myStackPanel.Margin = New Thickness(20) ' Create a rectangle. myRectangle = New Rectangle() With myRectangle .Width = 100 .Height = 20 .Margin = New Thickness(12, 0, 0, 5) .Fill = New SolidColorBrush(Color.FromArgb(170, 51, 51, 255)) .HorizontalAlignment = HorizontalAlignment.Left End With myStackPanel.Children.Add(myRectangle) ' ' Create an animation and a storyboard to animate the ' rectangle. ' Dim myDoubleAnimation As New DoubleAnimation(100, 500, New Duration(TimeSpan.FromSeconds(60))) myClock = myDoubleAnimation.CreateClock() myRectangle.ApplyAnimationClock(Rectangle.WidthProperty, myClock) myClock.Controller.Stop() ' ' Create some buttons to control the storyboard ' and a panel to contain them. ' Dim buttonPanel As New StackPanel() buttonPanel.Orientation = Orientation.Horizontal Dim beginButton As New Button() beginButton.Content = "Begin" AddHandler beginButton.Click, AddressOf beginButton_Clicked buttonPanel.Children.Add(beginButton) Dim pauseButton As New Button() pauseButton.Content = "Pause" AddHandler pauseButton.Click, AddressOf pauseButton_Clicked buttonPanel.Children.Add(pauseButton) Dim resumeButton As New Button() resumeButton.Content = "Resume" AddHandler resumeButton.Click, AddressOf resumeButton_Clicked buttonPanel.Children.Add(resumeButton) Dim skipToFillButton As New Button() skipToFillButton.Content = "Skip to Fill" AddHandler skipToFillButton.Click, AddressOf skipToFillButton_Clicked buttonPanel.Children.Add(skipToFillButton) Dim setSpeedRatioButton As New Button() setSpeedRatioButton.Content = "Triple Speed" AddHandler setSpeedRatioButton.Click, AddressOf setSpeedRatioButton_Clicked buttonPanel.Children.Add(setSpeedRatioButton) Dim stopButton As New Button() stopButton.Content = "Stop" AddHandler stopButton.Click, AddressOf stopButton_Clicked buttonPanel.Children.Add(stopButton) Dim removeButton As New Button() removeButton.Content = "Remove" AddHandler removeButton.Click, AddressOf removeButton_Clicked buttonPanel.Children.Add(removeButton) myStackPanel.Children.Add(buttonPanel) ``` -------------------------------- ### C# Example: Interactively Control a Root Clock Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-interactively-control-a-clock This example demonstrates how to create and control a root animation clock using buttons. It requires WPF and System.Windows.Media.Animation namespaces. ```C# /* This example shows how to interactively control a root clock. */ using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Media.Animation; namespace Microsoft.Samples.Animation.TimingBehaviors { public class ClockControllerExample : Page { private AnimationClock myControllableClock; private Button seekButton; private TextBox seekAmountTextBox; private ListBox timeSeekOriginListBox; public ClockControllerExample() { StackPanel mainPanel = new StackPanel(); // Create a rectangle to animate. Rectangle animatedRectangle = new Rectangle(); animatedRectangle.Width = 100; animatedRectangle.Height = 100; animatedRectangle.Fill = Brushes.Orange; mainPanel.Children.Add(animatedRectangle); // Create a DoubleAnimation to // animate its width. DoubleAnimation widthAnimation = new DoubleAnimation( 100, 500, new Duration(TimeSpan.FromSeconds(5))); // Create a clock from the animation. myControllableClock = widthAnimation.CreateClock(); // Apply the clock to the rectangle's Width property. animatedRectangle.ApplyAnimationClock( Rectangle.WidthProperty, myControllableClock); myControllableClock.Controller.Stop(); // // Create some buttons to control the clock. // // Create a button to begin the clock. Button beginButton = new Button(); beginButton.Content = "Begin"; beginButton.Click += new RoutedEventHandler(beginButton_Clicked); mainPanel.Children.Add(beginButton); // Create a button to pause the clock. Button pauseButton = new Button(); pauseButton.Content = "Pause"; pauseButton.Click += new RoutedEventHandler(pauseButton_Clicked); mainPanel.Children.Add(pauseButton); // Create a button to resume the clock. Button resumeButton = new Button(); resumeButton.Content = "Resume"; resumeButton.Click += new RoutedEventHandler(resumeButton_Clicked); mainPanel.Children.Add(resumeButton); // Create a button to advance the clock to // its fill period. Button skipToFillButton = new Button(); skipToFillButton.Content = "Skip to Fill"; skipToFillButton.Click += new RoutedEventHandler(skipToFillButton_Clicked); mainPanel.Children.Add(skipToFillButton); // Create a button to stop the clock. Button stopButton = new Button(); stopButton.Content = "Stop"; stopButton.Click += new RoutedEventHandler(stopButton_Clicked); mainPanel.Children.Add(stopButton); // // Create some controls the enable the user to // seek the clock. // ``` -------------------------------- ### Line Command Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/path-markup-syntax Example of a line command. 'l 20 30' uses relative coordinates, while 'L 20,30' uses absolute coordinates. ```WPF Path Markup l 20 30 ``` ```WPF Path Markup L 20,30 ``` -------------------------------- ### Staggering Animations with BeginTime Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/timing-behaviors-overview This XAML example demonstrates how to use the BeginTime property to stagger the start of two animations within a Storyboard. The second animation starts after the first one completes. ```xaml ``` -------------------------------- ### Instantiate the Default Memory Cache Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/walkthrough-caching-application-data-in-a-wpf-application Get an instance of the default in-memory cache object to start caching data. ```C# ObjectCache cache = MemoryCache.Default; ``` -------------------------------- ### VB.NET Console App Initialization Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/initialization-for-object-elements-not-in-an-object-tree Demonstrates loading a loose XAML file and initializing a UI element using BeginInit and EndInit in VB.NET. Assumes utility functions Rasterize and Save are defined elsewhere. ```vbnet Shared Sub Main(ByVal args() As String) Dim e As UIElement Dim _file As String = Directory.GetCurrentDirectory() & "\\starting.xaml" Using stream As Stream = File.Open(_file, FileMode.Open) ' loading files from current directory, project settings take care of copying the file Dim pc As New ParserContext() pc.BaseUri = New Uri(_file, UriKind.Absolute) e = CType(XamlReader.Load(stream, pc), UIElement) End Using Dim paperSize As New Size(8.5 * 96, 11 * 96) e.Measure(paperSize) e.Arrange(New Rect(paperSize)) e.UpdateLayout() ' ' * Render effect at normal dpi, indicator is the original RED rectangle ' Dim image1 As RenderTargetBitmap = Rasterize(e, paperSize.Width, paperSize.Height, 96, 96) Save(image1, "render1.png") Dim b As New Button() b.BeginInit() b.Background = Brushes.Blue b.Height = 200 b.Width = b.Height b.EndInit() b.Measure(paperSize) b.Arrange(New Rect(paperSize)) b.UpdateLayout() ' now render the altered version, with the element built up and initialized Dim image2 As RenderTargetBitmap = Rasterize(b, paperSize.Width, paperSize.Height, 96, 96) Save(image2, "render2.png") End Sub ``` -------------------------------- ### XAML Setup for TextWrapping Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/how-to-change-the-textwrapping-property-programmatically Defines three buttons and a TextBlock in XAML. The buttons trigger changes to the TextWrapping property of the TextBlock. ```xaml Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Lorem ipsum dolor sit aet, consectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. ``` -------------------------------- ### C# Console App Initialization Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/initialization-for-object-elements-not-in-an-object-tree Illustrates loading a loose XAML file and initializing a UI element using BeginInit and EndInit before rendering. Assumes utility functions Rasterize and Save are defined elsewhere. ```csharp [STAThread] static void Main(string[] args) { UIElement e; string file = Directory.GetCurrentDirectory() + "\\starting.xaml"; using (Stream stream = File.Open(file, FileMode.Open)) { // loading files from current directory, project settings take care of copying the file ParserContext pc = new ParserContext(); pc.BaseUri = new Uri(file, UriKind.Absolute); e = (UIElement)XamlReader.Load(stream, pc); } Size paperSize = new Size(8.5 * 96, 11 * 96); e.Measure(paperSize); e.Arrange(new Rect(paperSize)); e.UpdateLayout(); /* * Render effect at normal dpi, indicator is the original RED rectangle */ RenderTargetBitmap image1 = Rasterize(e, paperSize.Width, paperSize.Height, 96, 96); Save(image1, "render1.png"); Button b = new Button(); b.BeginInit(); b.Background = Brushes.Blue; b.Width = b.Height = 200; b.EndInit(); b.Measure(paperSize); b.Arrange(new Rect(paperSize)); b.UpdateLayout(); // now render the altered version, with the element built up and initialized RenderTargetBitmap image2 = Rasterize(b, paperSize.Width, paperSize.Height, 96, 96); Save(image2, "render2.png"); } ``` -------------------------------- ### Instantiate the Default Memory Cache (Visual Basic) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/walkthrough-caching-application-data-in-a-wpf-application Get an instance of the default in-memory cache object to start caching data. ```Visual Basic Dim cache As ObjectCache = MemoryCache.Default ``` -------------------------------- ### Create a Basic 3D Scene Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-create-a-3-d-scene This snippet shows the fundamental setup for a 3D scene in WPF, including defining the viewport, camera, lighting, and geometry. It requires the System.Windows.Media.Media3D namespace. ```C# using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Media3D; namespace SDKSample { public partial class Basic3DShapeExample : Page { public Basic3DShapeExample() { // Declare scene objects. Viewport3D myViewport3D = new Viewport3D(); Model3DGroup myModel3DGroup = new Model3DGroup(); GeometryModel3D myGeometryModel = new GeometryModel3D(); ModelVisual3D myModelVisual3D = new ModelVisual3D(); // Defines the camera used to view the 3D object. In order to view the 3D object, // the camera must be positioned and pointed such that the object is within view // of the camera. PerspectiveCamera myPCamera = new PerspectiveCamera(); // Specify where in the 3D scene the camera is. myPCamera.Position = new Point3D(0, 0, 2); // Specify the direction that the camera is pointing. myPCamera.LookDirection = new Vector3D(0, 0, -1); // Define camera's horizontal field of view in degrees. myPCamera.FieldOfView = 60; // Asign the camera to the viewport myViewport3D.Camera = myPCamera; // Define the lights cast in the scene. Without light, the 3D object cannot // be seen. Note: to illuminate an object from additional directions, create // additional lights. DirectionalLight myDirectionalLight = new DirectionalLight(); myDirectionalLight.Color = Colors.White; myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61); myModel3DGroup.Children.Add(myDirectionalLight); // The geometry specifes the shape of the 3D plane. In this sample, a flat sheet // is created. MeshGeometry3D myMeshGeometry3D = new MeshGeometry3D(); // Create a collection of normal vectors for the MeshGeometry3D. Vector3DCollection myNormalCollection = new Vector3DCollection(); myNormalCollection.Add(new Vector3D(0,0,1)); myNormalCollection.Add(new Vector3D(0,0,1)); myNormalCollection.Add(new Vector3D(0,0,1)); myNormalCollection.Add(new Vector3D(0,0,1)); myNormalCollection.Add(new Vector3D(0,0,1)); myNormalCollection.Add(new Vector3D(0,0,1)); myMeshGeometry3D.Normals = myNormalCollection; // Create a collection of vertex positions for the MeshGeometry3D. Point3DCollection myPositionCollection = new Point3DCollection(); myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5)); myPositionCollection.Add(new Point3D(0.5, -0.5, 0.5)); myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5)); myPositionCollection.Add(new Point3D(0.5, 0.5, 0.5)); myPositionCollection.Add(new Point3D(-0.5, 0.5, 0.5)); myPositionCollection.Add(new Point3D(-0.5, -0.5, 0.5)); myMeshGeometry3D.Positions = myPositionCollection; // Create a collection of texture coordinates for the MeshGeometry3D. PointCollection myTextureCoordinatesCollection = new PointCollection(); myTextureCoordinatesCollection.Add(new Point(0, 0)); myTextureCoordinatesCollection.Add(new Point(1, 0)); myTextureCoordinatesCollection.Add(new Point(1, 1)); myTextureCoordinatesCollection.Add(new Point(1, 1)); myTextureCoordinatesCollection.Add(new Point(0, 1)); myTextureCoordinatesCollection.Add(new Point(0, 0)); myMeshGeometry3D.TextureCoordinates = myTextureCoordinatesCollection; // Create a collection of triangle indices for the MeshGeometry3D. Int32Collection myTriangleIndicesCollection = new Int32Collection(); myTriangleIndicesCollection.Add(0); myTriangleIndicesCollection.Add(1); myTriangleIndicesCollection.Add(2); myTriangleIndicesCollection.Add(3); myTriangleIndicesCollection.Add(4); myTriangleIndicesCollection.Add(5); myMeshGeometry3D.TriangleIndices = myTriangleIndicesCollection; // Apply the mesh to the geometry model. myGeometryModel.Geometry = myMeshGeometry3D; // The material specifies the material applied to the 3D object. In this sample a // linear gradient covers the surface of the 3D object. ``` -------------------------------- ### VB.NET Code to Get Offset Relative to Descendant Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-get-the-offset-of-a-visual This VB.NET code achieves the same offset calculation as the C# example, using the TransformToDescendant method and the Transform method of the GeneralTransform object. ```vbnet ' Return the general transform for the specified visual object. Dim generalTransform1 As GeneralTransform = myStackPanel.TransformToDescendant(myTextBlock) ' Retrieve the point value relative to the child. Dim currentPoint As Point = generalTransform1.Transform(New Point(0, 0)) ``` -------------------------------- ### Animate Rectangle Geometry with Key Frames Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-animate-a-rectangle-geometry-by-using-key-frames Animates the Rect property of a RectangleGeometry using Linear, Discrete, and Spline key frames. This example requires a WPF application setup. ```C# using System; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; namespace KeyFrameAnimationExample { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // Create a RectangleGeometry RectangleGeometry rectGeometry = new RectangleGeometry(); rectGeometry.Rect = new Rect(50, 50, 100, 100); // Create a RectangleGeometry. (This is a placeholder, in a real app you'd add this to a visual tree) // For demonstration, we'll just create the animation objects. // Create animation using key frames RectAnimationUsingKeyFrames rectAnimation = new RectAnimationUsingKeyFrames(); // 1. Linear key frame: Animate for 2 seconds LinearRectKeyFrame linearKeyFrame = new LinearRectKeyFrame(); linearKeyFrame.Value = new Rect(75, 75, 150, 150); // New position and size linearKeyFrame.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2)); rectAnimation.KeyFrames.Add(linearKeyFrame); // 2. Discrete key frame: Decrease height suddenly over 0.5 seconds DiscreteRectKeyFrame discreteKeyFrame = new DiscreteRectKeyFrame(); discreteKeyFrame.Value = new Rect(75, 75, 150, 100); // Height decreased discreteKeyFrame.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.5)); // 2 + 0.5 rectAnimation.KeyFrames.Add(discreteKeyFrame); // 3. Spline key frame: Return to original size and position over 2 seconds SplineRectKeyFrame splineKeyFrame = new SplineRectKeyFrame(); splineKeyFrame.Value = new Rect(50, 50, 100, 100); // Original size and position splineKeyFrame.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(4.5)); // 2.5 + 2 // Optional: Configure KeySpline for exponential acceleration splineKeyFrame.KeySpline = new KeySpline(0.7, 0.0, 0.9, 1.0); rectAnimation.KeyFrames.Add(splineKeyFrame); // Set the animation's duration rectAnimation.Duration = TimeSpan.FromSeconds(4.5); // In a real WPF application, you would apply this animation to a RectangleGeometry // For example, if you had a Path element named 'myPath' with a RectangleGeometry: // myPath.Data.BeginAnimation(RectangleGeometry.RectProperty, rectAnimation); // Since this is a standalone example, we just construct the animation. } } } ``` -------------------------------- ### Show Main Window on Startup in VB.NET Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/application-management-overview This VB.NET code demonstrates opening and showing the main window upon application startup. ```VB.NET Imports System.Windows Namespace SDKSample Partial Public Class App Inherits Application Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs) ' Open a window Dim window As New MainWindow() window.Show() End Sub End Class End Namespace ``` -------------------------------- ### C# Storyboard Animation Setup Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-animate-a-property-by-using-a-storyboard This C# code sets up a WPF Page, registers a name scope, and creates a button. It initializes a DoubleAnimation to animate the button's width, setting the start and end values and duration. ```C# using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; namespace Microsoft.Samples.Animation.AnimatingWithStoryboards { // 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()); this.WindowTitle = "Animate Properties using Storyboards"; StackPanel myStackPanel = new StackPanel(); myStackPanel.MinWidth = 500; myStackPanel.Margin = new Thickness(30); myStackPanel.HorizontalAlignment = HorizontalAlignment.Left; TextBlock myTextBlock = new TextBlock(); myTextBlock.Text = "Storyboard Animation Example"; myStackPanel.Children.Add(myTextBlock); // // Create and animate the first button. // // Create a button. Button myWidthAnimatedButton = new Button(); myWidthAnimatedButton.Height = 30; myWidthAnimatedButton.Width = 200; myWidthAnimatedButton.HorizontalAlignment = HorizontalAlignment.Left; myWidthAnimatedButton.Content = "A Button"; // 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. myWidthAnimatedButton.Name = "myWidthAnimatedButton"; // Register the name with the page to which the button belongs. this.RegisterName(myWidthAnimatedButton.Name, myWidthAnimatedButton); // Create a DoubleAnimation to animate the width of the button. DoubleAnimation myDoubleAnimation = new DoubleAnimation(); myDoubleAnimation.From = 200; myDoubleAnimation.To = 300; myDoubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(3000)); ``` -------------------------------- ### Handle the Startup Event in VB.NET Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/application-management-overview This snippet demonstrates handling the Startup event in VB.NET for application initialization. ```VB.NET Namespace SDKSample Partial Public Class App Inherits Application Private Sub App_Startup(ByVal sender As Object, ByVal e As StartupEventArgs) ' Application is running ' End Class End Namespace ' ``` -------------------------------- ### WPF XAML for Clock State Notification Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-receive-notification-when-clock-state-changes This XAML defines a page with two rectangles, text blocks to display state changes, and a button to start animations. It includes a Storyboard with two DoubleAnimations, both configured to trigger the CurrentStateInvalidated event. ```XAML ``` -------------------------------- ### Add Grid to Border and Show Window (C#) Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/alignment-margins-and-padding-overview This snippet shows the initialization of a WPF Window, Border, and Grid, including setting properties like background, border thickness, corner radius, and padding. It demonstrates how to structure the main window content. ```csharp mainWindow = new Window(); myBorder = new Border(); myBorder.Background = Brushes.LightBlue; myBorder.BorderBrush = Brushes.Black; myBorder.BorderThickness = new Thickness(2); myBorder.CornerRadius = new CornerRadius(45); myBorder.Padding = new Thickness(25); // Define the Grid. myGrid = new Grid(); myGrid.Background = Brushes.White; myGrid.ShowGridLines = true; ``` -------------------------------- ### Define and Implement a Dependency Property in C# Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/control-authoring-overview This C# example demonstrates how to define a dependency property named 'Value' for a custom control. It includes registering the property, setting up its metadata with callbacks, and creating a CLR wrapper for getting and setting the value. ```csharp /// /// Identifies the Value dependency property. /// public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof(decimal), typeof(NumericUpDown), new FrameworkPropertyMetadata(MinValue, new PropertyChangedCallback(OnValueChanged), new CoerceValueCallback(CoerceValue))); /// /// Gets or sets the value assigned to the control. /// public decimal Value { get { return (decimal)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } private static object CoerceValue(DependencyObject element, object value) { decimal newValue = (decimal)value; NumericUpDown control = (NumericUpDown)element; newValue = Math.Max(MinValue, Math.Min(MaxValue, newValue)); return newValue; } private static void OnValueChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { NumericUpDown control = (NumericUpDown)obj; RoutedPropertyChangedEventArgs e = new RoutedPropertyChangedEventArgs( (decimal)args.OldValue, (decimal)args.NewValue, ValueChangedEvent); control.OnValueChanged(e); } ``` -------------------------------- ### Get Native Data Formats using GetFormats(false) in VB.NET Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/how-to-list-the-data-formats-in-a-data-object This VB.NET example demonstrates retrieving only native data formats from a `DataObject` by using the `GetFormats(False)` overload. This is helpful for filtering out auto-convertible formats and focusing on direct data types. ```vbnet Dim dataObject As New DataObject("Some string data to store...") ' Get an array of strings, each string denoting a data format ' that is available in the data object. This overload of GetDataFormats ' accepts a Boolean parameter inidcating whether to include auto-convertible ' data formats, or only return native data formats. Dim dataFormats() As String = dataObject.GetFormats(False) ' Include auto-convertible? ' Get the number of native data formats present in the data object. Dim numberOfDataFormats As Integer = dataFormats.Length ' To enumerate the resulting array of data formats, and take some action when ' a particular data format is found, use a code structure similar to the following. For Each dataFormat As String In dataFormats If dataFormat = System.Windows.DataFormats.Text Then ' Take some action if/when data in the Text data format is found. Exit For End If Next dataFormat ``` -------------------------------- ### Example XBAP Filename for Debugging Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/configure-vs-to-debug-a-xaml-browser-to-call-a-web-service Provide the specific .xbap file path as an argument to the '-debug' command. ```text -debug c:\example.xbap ``` -------------------------------- ### WPF Point Animation Along Path Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-animate-an-object-along-a-path-point-animation This VB.NET code demonstrates how to create and apply a PointAnimationUsingPath to animate an EllipseGeometry along a PathGeometry in WPF. It sets up the geometry, registers names, creates the animation and storyboard, and starts the animation when the path element is loaded. ```vbnet Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Media.Animation Imports System.Windows.Navigation Imports System.Windows.Shapes Namespace SDKSample Public Class PointAnimationUsingPathExample Inherits Page Public Sub New() ' Create a NameScope for the page so that ' we can use Storyboards. NameScope.SetNameScope(Me, New NameScope()) ' Create the EllipseGeometry to animate. Dim animatedEllipseGeometry As New EllipseGeometry(New Point(10, 100), 15, 15) ' Register the EllipseGeometry's name with ' the page so that it can be targeted by a ' storyboard. Me.RegisterName("AnimatedEllipseGeometry", animatedEllipseGeometry) ' Create a Path element to display the geometry. Dim ellipsePath As New Path() ellipsePath.Data = animatedEllipseGeometry ellipsePath.Fill = Brushes.Blue ellipsePath.Margin = New Thickness(15) ' Create a Canvas to contain ellipsePath ' and add it to the page. Dim mainPanel As New Canvas() mainPanel.Width = 400 mainPanel.Height = 400 mainPanel.Children.Add(ellipsePath) Me.Content = mainPanel ' Create the animation path. Dim animationPath As New PathGeometry() Dim pFigure As New PathFigure() pFigure.StartPoint = New Point(10, 100) Dim pBezierSegment As New PolyBezierSegment() pBezierSegment.Points.Add(New Point(35, 0)) pBezierSegment.Points.Add(New Point(135, 0)) pBezierSegment.Points.Add(New Point(160, 100)) pBezierSegment.Points.Add(New Point(180, 190)) pBezierSegment.Points.Add(New Point(285, 200)) pBezierSegment.Points.Add(New Point(310, 100)) pFigure.Segments.Add(pBezierSegment) animationPath.Figures.Add(pFigure) ' Freeze the PathGeometry for performance benefits. animationPath.Freeze() ' Create a PointAnimationgUsingPath to move ' the EllipseGeometry along the animation path. Dim centerPointAnimation As New PointAnimationUsingPath() centerPointAnimation.PathGeometry = animationPath centerPointAnimation.Duration = TimeSpan.FromSeconds(5) centerPointAnimation.RepeatBehavior = RepeatBehavior.Forever ' Set the animation to target the Center property ' of the EllipseGeometry named "AnimatedEllipseGeometry". Storyboard.SetTargetName(centerPointAnimation, "AnimatedEllipseGeometry") Storyboard.SetTargetProperty(centerPointAnimation, New PropertyPath(EllipseGeometry.CenterProperty)) ' Create a Storyboard to contain and apply the animation. Dim pathAnimationStoryboard As New Storyboard() pathAnimationStoryboard.RepeatBehavior = RepeatBehavior.Forever pathAnimationStoryboard.AutoReverse = True pathAnimationStoryboard.Children.Add(centerPointAnimation) ' Start the Storyboard when ellipsePath is loaded. AddHandler ellipsePath.Loaded, Sub(sender As Object, e As RoutedEventArgs) pathAnimationStoryboard.Begin(Me) End Sub End Class End Namespace ``` -------------------------------- ### MainWindow Initialization and Data Generation Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/how-to-group-sort-and-filter-data-in-the-datagrid-control Initializes the MainWindow, retrieves the tasks collection, and populates it with sample data. This setup is necessary for data binding to the DataGrid. ```vbnet Imports System.ComponentModel Imports System.Collections.ObjectModel Class MainWindow Public Sub New() InitializeComponent() ' Get a reference to the tasks collection. Dim _tasks As Tasks = Me.Resources("tasks") ' Generate some task data and add it to the task list. For index = 1 To 14 _tasks.Add(New Task() With _ {.ProjectName = "Project " & ((index Mod 3) + 1).ToString(), _ .TaskName = "Task " & index.ToString(), _ .DueDate = Date.Now.AddDays(index), .Complete = (index Mod 2 = 0) _ }) Next End Sub ``` -------------------------------- ### Display Command Line Syntax Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/how-to-validate-and-merge-printtickets Displays the correct command line syntax for running the sample program. This is useful for user guidance when incorrect arguments are provided. ```vb ''' ''' Displays the correct command line syntax to run this sample program. ''' Private Shared Sub DisplayUsage() Console.WriteLine() Console.WriteLine("Usage #1: printticket.exe -l \"\"" ) Console.WriteLine(" Run program on the specified local printer") Console.WriteLine() Console.WriteLine(" Quotation marks may be omitted if there are no spaces in printer_name.") Console.WriteLine() Console.WriteLine("Usage #2: printticket.exe -r \"\\\\\"" ) Console.WriteLine(" Run program on the specified network printer") Console.WriteLine() Console.WriteLine(" Quotation marks may be omitted if there are no spaces in server_name or printer_name.") Console.WriteLine() Console.WriteLine("Usage #3: printticket.exe -a") Console.WriteLine(" Run program on all installed printers") Console.WriteLine() End Sub ``` -------------------------------- ### WPF DoubleAnimationUsingPath Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-animate-an-object-along-a-path-double-animation This VB.NET code creates a rectangle, defines a path using PathGeometry, and animates the rectangle's TranslateTransform along this path using two DoubleAnimationUsingPath objects for X and Y coordinates. The animation is set to repeat indefinitely and starts when the rectangle is loaded. ```vb Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Media Imports System.Windows.Media.Animation Imports System.Windows.Navigation Imports System.Windows.Shapes Namespace SDKSample Public Class DoubleAnimationUsingPathExample Inherits Page Public Sub New() ' Create a NameScope for the page so that ' we can use Storyboards. NameScope.SetNameScope(Me, New NameScope()) ' Create a rectangle. Dim aRectangle As New Rectangle() aRectangle.Width = 30 aRectangle.Height = 30 aRectangle.Fill = Brushes.Blue ' Create a transform. This transform ' will be used to move the rectangle. Dim animatedTranslateTransform As New TranslateTransform() ' Register the transform's name with the page ' so that they it be targeted by a Storyboard. Me.RegisterName("AnimatedTranslateTransform", animatedTranslateTransform) aRectangle.RenderTransform = animatedTranslateTransform ' Create a Canvas to contain the rectangle ' and add it to the page. Dim mainPanel As New Canvas() mainPanel.Width = 400 mainPanel.Height = 400 mainPanel.Children.Add(aRectangle) Me.Content = mainPanel ' Create the animation path. Dim animationPath As New PathGeometry() Dim pFigure As New PathFigure() pFigure.StartPoint = New Point(10, 100) Dim pBezierSegment As New PolyBezierSegment() pBezierSegment.Points.Add(New Point(35, 0)) pBezierSegment.Points.Add(New Point(135, 0)) pBezierSegment.Points.Add(New Point(160, 100)) pBezierSegment.Points.Add(New Point(180, 190)) pBezierSegment.Points.Add(New Point(285, 200)) pBezierSegment.Points.Add(New Point(310, 100)) pFigure.Segments.Add(pBezierSegment) animationPath.Figures.Add(pFigure) ' Freeze the PathGeometry for performance benefits. animationPath.Freeze() ' Create a DoubleAnimationUsingPath to move the ' rectangle horizontally along the path by animating ' its TranslateTransform. Dim translateXAnimation As New DoubleAnimationUsingPath() translateXAnimation.PathGeometry = animationPath translateXAnimation.Duration = TimeSpan.FromSeconds(5) ' Set the Source property to X. This makes ' the animation generate horizontal offset values from ' the path information. translateXAnimation.Source = PathAnimationSource.X ' Set the animation to target the X property ' of the TranslateTransform named "AnimatedTranslateTransform". Storyboard.SetTargetName(translateXAnimation, "AnimatedTranslateTransform") Storyboard.SetTargetProperty(translateXAnimation, New PropertyPath(TranslateTransform.XProperty)) ' Create a DoubleAnimationUsingPath to move the ' rectangle vertically along the path by animating ' its TranslateTransform. Dim translateYAnimation As New DoubleAnimationUsingPath() translateYAnimation.PathGeometry = animationPath translateYAnimation.Duration = TimeSpan.FromSeconds(5) ' Set the Source property to Y. This makes ' the animation generate vertical offset values from ' the path information. translateYAnimation.Source = PathAnimationSource.Y ' Set the animation to target the Y property ' of the TranslateTransform named "AnimatedTranslateTransform". Storyboard.SetTargetName(translateYAnimation, "AnimatedTranslateTransform") Storyboard.SetTargetProperty(translateYAnimation, New PropertyPath(TranslateTransform.YProperty)) ' Create a Storyboard to contain and apply the animations. Dim pathAnimationStoryboard As New Storyboard() pathAnimationStoryboard.RepeatBehavior = RepeatBehavior.Forever pathAnimationStoryboard.Children.Add(translateXAnimation) pathAnimationStoryboard.Children.Add(translateYAnimation) ' Start the animations when the rectangle is loaded. AddHandler aRectangle.Loaded, Sub(sender As Object, e As RoutedEventArgs) pathAnimationStoryboard.Begin(Me) End Sub End Class End Namespace ``` -------------------------------- ### Instantiate and Populate Aquariums in C# Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/properties/collection-type-dependency-properties Demonstrates creating two Aquarium instances and adding a Fish to each. This code verifies that each Aquarium has its own independent collection. ```csharp private void InitializeAquariums(object sender, RoutedEventArgs e) { Aquarium aquarium1 = new(); Aquarium aquarium2 = new(); aquarium1.AquariumContents.Add(new Fish()); aquarium2.AquariumContents.Add(new Fish()); MessageBox.Show( $"aquarium1 contains {aquarium1.AquariumContents.Count} fish\r\n" + $"aquarium2 contains {aquarium2.AquariumContents.Count} fish"); } ``` -------------------------------- ### Play Video Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/drawing-objects-overview A complete example demonstrating how to play a video file once using VideoDrawing and MediaPlayer. ```csharp // // Create a VideoDrawing. // MediaPlayer player = new MediaPlayer(); player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); VideoDrawing aVideoDrawing = new VideoDrawing(); aVideoDrawing.Rect = new Rect(0, 0, 100, 100); aVideoDrawing.Player = player; // Play the video once. player.Play(); ``` -------------------------------- ### VB.NET Page Setup and Drawing Creation Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-create-different-tile-patterns-with-a-tilebrush Sets up a WPF Page with a white background and margins, and defines a drawing for a triangle using PathGeometry, PathFigure, and PolyLineSegment. ```VB.NET Imports System.Windows Imports System.Windows.Controls Imports System.Windows.Input Imports System.Windows.Media Imports System.Windows.Media.Animation Imports System.Windows.Shapes Namespace BrushesIntroduction Public Class TileModeExample Inherits Page Public Sub New() Background = Brushes.White Margin = New Thickness(20) Dim mainPanel As New StackPanel() mainPanel.HorizontalAlignment = HorizontalAlignment.Left ' ' Create a Drawing. This will be the DrawingBrushes' content. ' Dim triangleLinesSegment As New PolyLineSegment() triangleLinesSegment.Points.Add(New Point(50, 0)) triangleLinesSegment.Points.Add(New Point(0, 50)) Dim triangleFigure As New PathFigure() triangleFigure.IsClosed = True triangleFigure.StartPoint = New Point(0, 0) triangleFigure.Segments.Add(triangleLinesSegment) Dim triangleGeometry As New PathGeometry() triangleGeometry.Figures.Add(triangleFigure) ``` -------------------------------- ### Basic Usage of PresentationHost.exe Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/wpf-host-presentationhost-exe This is the fundamental command to launch a WPF application or file using PresentationHost.exe. Replace 'uri|filename' with the actual path or URI. ```command-line PresentationHost.exe [parameters] uri|filename ``` -------------------------------- ### Start Clock Control Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-interactively-control-a-clock This method is called when the 'Begin' button is clicked to start the clock's animation. ```csharp // Starts the clock. private void beginButton_Clicked(object sender, RoutedEventArgs e) { myControllableClock.Controller.Begin(); } ``` -------------------------------- ### Show Main Window on Startup in C# Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/application-management-overview This C# code shows how to open and display the main window of a WPF application when the Startup event is raised. ```C# using System.Windows; namespace SDKSample { public partial class App : Application { void App_Startup(object sender, StartupEventArgs e) { // Open a window MainWindow window = new MainWindow(); window.Show(); } } } ``` -------------------------------- ### Vertical Line Command Example Source: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/path-markup-syntax Example of a vertical line command. 'v 90' uses relative coordinates. ```WPF Path Markup v 90 ```