WPF

0
101

WPF – Overview

WPF stands for Windows Presentation Foundation. It is a powerful framework for constructing Windows applications. This tutorial exfundamentals the features thead wear you need to belowstand to construct WPF applications and how it provides a fundamental modify in Windows applications.

WPF was very first introduces in .NET framework 3.0 version, and then so many kind of other features were added in the subsequent .NET framework versions.

WPF Architecture

Before WPF, the other user interface frameworks provideeddish coloured simply by Microsmooth such as MFC and Windows forms, were simply wrappers around User32 and GDI32 DLLs, but WPF produces only minimal use of User32. So,

  • WPF is more than simply a wrapper.
  • It is a part of the .NET framework.
  • It contains a mixture of managed and unmanaged code.

The major components of WPF architecture are as shown in the figure end up beinglow. The the majority of iminterfaceant code part of WPF are −

  • Presentation Framework
  • Presentation Core
  • Milcore

WPF Architecture

The presentation framework and the presentation core have end up beingen produced in managed code. Milcore is a part of unmanaged code which allows tight integration with DirectX (responsible for display and rendering). CLR produces the producement process more itemive simply by provideing many kind of features such as memory management, error handling, etc.

WPF – Advantages

In the earlayr GUI frameworks, there was no real separation end up beingtween how an application looks like and how it end up beinghaved. Both GUI and end up beinghavior was produced in the same language, e.g. C# or VB.Net which would require more effort from the produceer to implement both UI and end up beinghavior bumociated with it.

In WPF, UI elements are styleed in XAML while end up beinghaviors can end up being implemented in procedural languages such C# and VB.Net. So it very easy to separate end up beinghavior from the styleer code.

With XAML, the programmers can work in parallel with the styleers. The separation end up beingtween a GUI and it is end up beinghavior can allow us to easily modify the look of a control simply by uperform styles and templates.

WPF – Features

WPF is a powerful framework to produce Windows application. It supinterfaces many kind of great features, a few of which have end up beingen listed end up beinglow −

Feature Description
Control inside a Control Allows to degreat a control inside one more control as a content.
Data binding Mechanism to display and interbehave with data end up beingtween UI elements and data object on user interface.
Media services Provides an integrated system for constructing user interfaces with common media elements like images, audio, and video.
Templates In WPF you can degreat the look of an element immediately with a Template
Animations Building interbehaveivity and movement on user Interface
Alternative inplace Supinterfaces multi-touch inplace on Windows 7 and above.
Direct3D Allows to display more complex graphics and custom all of themes

WPF – Environment Setup

Microsmooth provides 2 iminterfaceant tools for WPF application producement.

  • Visual Studio
  • Expression Blend

Both the tools can produce WPF projects, but the fbehave is thead wear Visual Studio is used more simply by produceers, while Blend is used more regularly simply by styleers. For this particular tutorial, we will the majority ofly end up being uperform Visual Studio.

Installation

Microsmooth provides a free version of Visual Studio which can end up being downloaded from VisualStudio.

Download the files and follow the steps given end up beinglow to set up WPF application producement environment on your own system.

  • After the download is extensive, operate the installer. The folloearng dialog will end up being displayed.

Installer

  • Click the Install button and it will start the installation process.

Installation Process

  • Once the installation process is extensived successcompallowey, you will get to see the folloearng dialog container.

Dialog Box

  • Close this particular dialog container and restart your own complaceer if requireddish coloured.

  • Now open Visual Studio from the Start Menu which will open the folloearng dialog container.

Visual Studio

  • Once all is done, you will see the main earndow of Visual Studio.

Window of Visual Studio

You are now ready to construct your own very first WPF application.

WPF – Hello World

In this particular chapter, we will produce a easy Hello World WPF application. So allow’s start the easy implementation simply by folloearng the steps given end up beinglow.

  • Click on File > New > Project menu option.

Project menu option

  • The folloearng dialog container will end up being displayed.

New Project dialog container

  • Under Templates, select Visual C# and in the middle panel, select WPF Application.

  • Give the project a name. Type HelloWorld in the name field and click the OK button.

  • By default, 2 files are produced, one is the XAML file (mainearndow.xaml) and the other one is the CS file (mainearndow.cs)

  • On mainearndow.xaml, you will see 2 sub-earndows, one is the style earndow and the other one is the source (XAML) earndow.

  • In WPF application, there are 2 ways to style an UI for your own application. One is to simply drag and fall UI elements from the toolcontainer to the Design Window. The second way is to style your own UI simply by writing XAML tags for UI elements. Visual Studio handles XAML tags when drag and fall feature is used for UI styleing.

  • In mainearndow.xaml file, the folloearng XAML tags are produced simply by default.

<Window x:Clbum = "HelloWorld.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604">
	
   <Grid> 
   </Grid> 
	
</Window> 
  • By default, a Grid is set as the very first element after page.
  • Let’s go to the toolcontainer and drag a TextBlock to the style earndow.

ToolBox

  • You will see the TextBlock on the style earndow.

TextBlock

  • When you look at the source earndow, you will see thead wear Visual Studio has generated the XAML code of the TextBlock for you.

  • Let’s modify the Text real estate of TextBlock in XAML code from TextBlock to Hello World.

<Window x:Clbum = "HelloWorld.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"
         Margin = "235,143,0,0" TextWrapping = "Wrap" Text = "Hello World!"
         VerticalAlignment = "Top" Height = "44" Width = "102" /> 
   </Grid> 
	
</Window> 
  • Now, you will see the modify on the Design Window as well.

Design Window

When the above code is compibrought and executed, you will see the folloearng earndow.

First WPF application

Congratulations! You have styleed and produced your own very first WPF application.

WPF – XAML Overview

One of the very first things you will encounter while worruler with WPF is XAML. XAML stands for Extensible Application Markup Language. It’s a easy and declarative language based on XML.

  • In XAML, it very easy to produce, preliminaryize, and set properties of objects with hierarchical relations.

  • It is mainly used for styleing GUIs, however it can end up being used for other purposes as well, e.g., to declare workflow in Workflow Foundation.

Basic Syntax

When you produce your own brand new WPF project, you will encounter a few of the XAML code simply by default in MainWindow.xaml as shown end up beinglow.

<Window x:Clbum = "Resources.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Grid> 
         
   </Grid> 
	
</Window>

The above XAML file contains various kinds of information. The folloearng table briefly exfundamentals the role of every information.

Information Description
<Window It is the opening object element or container of the fundamental.
x:Clbum = "Resources.MainWindow" It is a partial clbum declaration which connects the markup to the partial clbum code degreatd end up beinghind.
xmlns = "/index.php?s=httpschemasmicrosmoothcomearn%20fx2006xamlpresentation" Maps the default XAML namespace for WPF claynt/framework
xmlns:x = "/index.php?s=httpschemasmicrosmoothcomw%20infx2006xaml" XAML namespace for XAML language which charts it to x: prefix
> End of object element of the fundamental

<Grid>

</Grid>

It is starting and cloperform tags of an empty grid object.
</Window> Cloperform the object element

The syntax rules for XAML is althe majority of similar to XML. If you look at an XAML document, then you will notice thead wear it is behaveually a valid XML file, but an XML file is not necessarily an XAML file. It is end up beingcause in XML, the value of the attributes must end up being a string while in XAML, it can end up being a various object which is belowstandn as Property element syntax.

  • The syntax of an Object element starts with a left angle bracket (<) followed simply by the name of an object, e.g. Button.

  • Degreat a few Properties and attributes of thead wear object element.

  • The Object element must end up being neard simply by a forbattbrought slash (/) followed immediately simply by a proper angle bracket (>).

Example of easy object with no kid element

<Button/> 

Example of object element with a few attributes

<Button Content = "Click Me" Height = "30" Width = "60" /> 

Example of an alternate syntax do degreat properties (Property element syntax)

<Button> 
   <Button.Content>Click Me</Button.Content> 
   <Button.Height>30</Button.Height> 
   <Button.Width>60</Button.Width> 
</Button> 

Example of Object with Child Element: StackPanel contains Textblock as kid element

<StackPanel Orientation = "Horizontal"> 
   <TextBlock Text = "Hello"/> 
</StackPanel> 

Why XAML in WPF

XAML is not only the the majority of widely belowstandn feature of WPF, but it's also one of the the majority of misbelowstood features. If you have exposure to WPF, then you must have heard of XAML; but consider a note of the folloearng 2 less belowstandn fbehaves abaway XAML −

  • WPF doesn't need XAML
  • XAML doesn't need WPF

They are in fbehave separable pieces of technology. To belowstand how thead wear can end up being, allow's look at a easy example in which a button is produced with a few properties in XAML.

<Window x:Clbum = "WPFXAMLOverview.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <StackPanel> 
      <Button x:Name = "button" Content = "Click Me" HorizontalAlignment = "Left"  
         Margin = "150" VerticalAlignment = "Top" Width = "75" /> 
   </StackPanel> 
	
</Window> 

In case you select not to use XAML in WPF, then you can achieve the same GUI result with procedural language as well. Let’s have a look at the same example, but this particular time, we will produce a button in C#.

uperform System.Windows; 
uperform System.Windows.Controls;  

namespace WPFXAMLOverview { 
   /// <summary> 
      /// Interbehaveion logic for MainWindow.xaml 
   /// </summary> 
	
   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
			
         // Create the StackPanel 
         StackPanel stackPanel = brand new StackPanel(); 
         this particular.Content = stackPanel; 
			
         // Create the Button 
         Button button = brand new Button();
         button.Content = "Click Me"; 
         button.HorizontalAlignment = HorizontalAlignment.Left; 
         button.Margin = brand new Thickness(150); 
         button.VerticalAlignment = VerticalAlignment.Top; 
         button.Width = 75; 
         stackPanel.Children.Add(button);  
      } 
   } 
} 

When you compile and execute either the XAML code or the C# code, you will see the same awayplace as shown end up beinglow.

XAML Outplace

From the above example, it is clear thead wear exbehavely whead wear you can do in XAML to produce, preliminaryize, and set properties of objects, the same tasks can also end up being done uperform code.

  • XAML is simply one more easy and easy way to style UI elements.

  • With XAML, it doesn’t mean thead wear exbehavely whead wear you can do to style UI elements is the only way. You can either declare the objects in XAML or degreat all of them uperform code.

  • XAML is optional, but despite this particular, it is at the heart of WPF style.

  • The goal of XAML is to enable visual styleers to produce user interface elements immediately.

  • WPF aims to produce it achievable to control all visual aspects of the user interface from mark-up.

WPF – Elements Tree

There are many kind of technologies where the elements and components are ordereddish coloured in a tree structure so thead wear the programmers can easily handle the object and modify the end up beinghavior of an application. Windows Presentation Foundation (WPF) has a extensive tree structure in the form of objects. In WPF, there are 2 ways thead wear a extensive object tree is conceptualized −

  • Logical Tree Structure
  • Visual Tree Structure

With the help of these tree structures, you can easily produce and identify the relationship end up beingtween UI elements. Mostly, WPF produceers and styleers either use procedural language to produce an application or style the UI part of the application in XAML maintaining in mind the object tree structure.

Logical Tree Structure

In WPF applications, the structure of the UI elements in XAML represents the logical tree structure. In XAML, the fundamental elements of UI are declareddish coloured simply by the produceer. The logical tree in WPF degreats the folloearng −

  • Dependency properties
  • Static and dynamic resources
  • Binding the elements on it is name etc.

Let’s have a look at the folloearng example in which a button and a list container are produced.

<Window x:Clbum = "WPFElementsTree.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <StackPanel> 
      <Button x:Name = "button" Height = "30" Width = "70" Content = "OK" Margin = "20" /> 
		
      <ListBox x:Name = "listBox" Height = "100" Width = "100" Margin = "20"> 
         <ListBoxItem Content = "Item 1" /> 
         <ListBoxItem Content = "Item 2" /> 
         <ListBoxItem Content = "Item 3" /> 
      </ListBox> 
		
   </StackPanel> 
	
</Window> 

If you look at the XAML code, you will observe a tree structure, i.e. the fundamental node is the Window and inside the fundamental node, there is only one kid, thead wear is StackPanel. But StackPanel contains 2 kid elements, button and list container. List container has three more kid list container items.

Visual Tree Structure

In WPF, the concept of the visual tree descriend up beings the structure of visual objects, as represented simply by the Visual Base Clbum. It signifies all the UI elements which are rendereddish coloured to the awayplace screen.

When a programmer wants to produce a template for a particular control, he is behaveually rendering the visual tree of thead wear control. The visual tree is also very helpful for those who want to draw lower level controls for performance and optimization reasons.

In WPF applications, visual tree is used for −

  • Rendering the visual objects.
  • Rendering the layaways.
  • The rawayed alsots the majority ofly take a trip along the visual tree, not the logical tree.

To see the visual tree of the above easy application which contains a button and a list container, allow’s compile and execute the XAML code and you will see the folloearng earndow.

Visual Tree Structure

When the application is operatening, you can see the visual tree of the operatening application in Live Visual Tree earndow which shows the extensive hierarchy of this particular application, as shown end up beinglow.

logical_tree

The visual tree is typically a superset of the logical tree. You can see here thead wear all the logical elements are also present in the visual tree. So these 2 trees are really simply 2 various views of the same set of objects thead wear produce up the UI.

  • The logical tree departs away a lot of detail enabling you to focus on the core structure of the user interface and to ignore the details of exbehavely how it has end up beingen presented.

  • The logical tree is exbehavely whead wear you use to produce the fundamental structure of the user interface.

  • The visual tree will end up being of attention if you're focuperform on the presentation. For example, if you wish to customise the appearance of any kind of UI element, you will need to use the visual tree.

WPF – Dependency Properties

In WPF applications, dependency real estate is a specific kind of real estate which extends the CLR real estate. It considers the advantage of specific functionalities available in the WPF real estate system.

A clbum which degreats a dependency real estate must end up being inherited from the DependencyObject clbum. Many kind of of the UI controls clbum which are used in XAML are derived from the DependencyObject clbum and they supinterface dependency properties, e.g. Button clbum supinterfaces the IsMouseOver dependency real estate.

The folloearng XAML code produces a button with a few properties.

<Window x:Clbum = "WPFDependencyProperty.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:local = "clr-namespace:WPFDependencyProperty"
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <Button  Height = "40" Width = "175" Margin = "10" Content = "Dependency Property"> 
         <Button.Style> 
            <Style TargetType = "{x:Type Button}"> 
               <Style.Triggers> 
					
                  <Trigger Property = "IsMouseOver" Value = "True"> 
                     <Setter Property = "Foreground" Value = "Red" /> 
                  </Trigger>
						
               </Style.Triggers>
            </Style> 
         </Button.Style> 
      </Button> 
   </Grid> 
	
</Window> 

The x:Type markup extension in XAML has a similar functionality like kindof() in C#. It is used when attributes are specified which consider the sort of the object such as <Style TargetType = "{x:Type Button}">

When the above code is compibrought and executed, you would get the folloearng MainWindow. When the mouse is over the button, it will modify the foreground colour of a button. When the mouse departs the button, it modifys back to it is preliminary colour.

Dependency Property

Why We Need Dependency Properties

Dependency real estate gives you all kinds of end up beingnefit is when you use it in your own application. Dependency Property can used over a CLR real estate in the folloearng scenarios −

  • If you like to set the style
  • If you like data binding
  • If you like to set with a resource (a static or a dynamic resource)
  • If you like to supinterface animation

Basically, Dependency Properties provide a lot of functionalities thead wear you won’t get simply by uperform a CLR real estate.

The main difference end up beingtween dependency properties and other CLR properties are listed end up beinglow −

  • CLR properties can immediately read/write from the private memend up beingr of a clbum simply by uperform getter and setter. In contrast, dependency properties are not storeddish coloured in local object.

  • Dependency properties are storeddish coloured in a book of key/value pairs which is provided simply by the DependencyObject clbum. It also saves a lot of memory end up beingcause it stores the real estate when modifyd. It can end up being bound in XAML as well.

Custom Dependency Properties

In .NET framework, custom dependency properties can also end up being degreatd. Follow the steps given end up beinglow to degreat custom dependency real estate in C#.

  • Declare and register your own dependency real estate with system call register.

  • Provide the setter and getter for the real estate.

  • Degreat a static handler which will handle any kind of modifys thead wear occur globally

  • Degreat an instance handler which will handle any kind of modifys thead wear occur to thead wear particular instance.

The folloearng C# code degreats a dependency real estate to set the SetText real estate of the user control.

uperform System; 
uperform System.Collections.Generic; 
uperform System.Linq; 
uperform System.Text; 
uperform System.Threading.Tasks; 

uperform System.Windows; 
uperform System.Windows.Controls; 
uperform System.Windows.Data; 
uperform System.Windows.Documents; 
uperform System.Windows.Inplace; 
uperform System.Windows.Media; 
uperform System.Windows.Media.Imaging; 
uperform System.Windows.Navigation; 
uperform System.Windows.Shapes;  

namespace WpfApplication3 { 
   /// <summary> 
      /// Interbehaveion logic for UserControl1.xaml 
   /// </summary> 
	
   public partial clbum UserControl1 : UserControl { 
	
      public UserControl1() { 
         InitializeComponent(); 
      }
		
      public static readonly DependencyProperty SetTextProperty = 
         DependencyProperty.Register("SetText", kindof(string), kindof(UserControl1), brand new 
            PropertyMetadata("", brand new PropertyChangedCallback(OnSetTextChanged))); 
				
      public string SetText { 
         get { return (string)GetValue(SetTextProperty); } 
         set { SetValue(SetTextProperty, value); } 
      } 
		
      private static void OnSetTextChanged(DependencyObject d,
         DependencyPropertyChangedEventArgs e) { 
         UserControl1 UserControl1Control = d as UserControl1; 
         UserControl1Control.OnSetTextChanged(e); 
      } 
		
      private void OnSetTextChanged(DependencyPropertyChangedEventArgs e) { 
         tbTest.Text = e.NewValue.ToString(); 
      }  
   } 
}

Here is the XAML file in which the TextBlock is degreatd as a user control and the Text real estate will end up being bumigned to it simply by the SetText dependency real estate.

The folloearng XAML code produces a user control and preliminaryizes it is SetText dependency real estate.

<Window x:Clbum = "WpfApplication3.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:views = "clr-namespace:WpfApplication3"
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <views:UserControl1 SetText = "Hellow World"/> 
   </Grid> 
	
</Window> 

Let's operate this particular application. You can immediately observe thead wear in our MainWindow, the dependency real estate for user control has end up beingen successcompallowey used as a Text.

Dependency real estate for user

WPF – Rawayed Events

A rawayed alsot is a kind of alsot thead wear can invoke handlers on multiple listeners in an element tree instead than simply the object thead wear raised the alsot. It is fundamentalally a CLR alsot thead wear is supinterfaceed simply by an instance of the Rawayed Event clbum. It is registereddish coloured with the WPF alsot system. RawayedEvents have three main rawaying strategies which are as follows −

  • Direct Event
  • Bubbling Event
  • Tunnel Event

Direct Event

A immediate alsot is similar to alsots in Windows forums which are raised simply by the element in which the alsot is originated.

Unlike a standard CLR alsot, immediate rawayed alsots supinterface clbum handling and they can end up being used in Event Setters and Event Triggers within your own style of your own Custom Control.

A great example of a immediate alsot would end up being the MouseEnter alsot.

Bubbling Event

A bubbling alsot end up beinggins with the element where the alsot is originated. Then it take a trips up the visual tree to the topthe majority of element in the visual tree. So, in WPF, the topthe majority of element is the majority of likely a earndow.

Tunnel Event

Event handlers on the element tree fundamental are invoked and then the alsot take a trips down the visual tree to all the kidren nodes until it reveryes the element in which the alsot originated.

The difference end up beingtween a bubbling and a tunneling alsot is thead wear a tunneling alsot will always start with a preview.

In a WPF application, alsots are regularly implemented as a tunneling/bubbling pair. So, you'll have a preview MouseDown and then a MouseDown alsot.

Given end up beinglow is a easy example of a Rawayed alsot in which a button and three text blocks are produced with a few properties and alsots.

<Window x:Clbum = "WPFRawayedEvents.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "MainWindow" Height = "450" Width = "604" ButtonBase.Click  = "Window_Click" >
	
   <Grid> 
      <StackPanel Margin = "20" ButtonBase.Click = "StackPanel_Click">
		
         <StackPanel Margin = "10"> 
            <TextBlock Name = "txt1" FontSize = "18" Margin = "5" Text = "This is a TextBlock 1" /> 
            <TextBlock Name = "txt2" FontSize = "18" Margin = "5" Text = "This is a TextBlock 2" /> 
            <TextBlock Name = "txt3" FontSize = "18" Margin = "5" Text = "This is a TextBlock 3" /> 
         </StackPanel> 
			
         <Button Margin = "10" Content = "Click me" Click = "Button_Click" Width = "80"/> 
      </StackPanel> 
   </Grid> 
	
</Window>

Here is the C# code for the Click alsots implementation for Button, StackPanel, and Window.

uperform System.Windows; 
 
namespace WPFRawayedEvents { 
   /// <summary> 
      /// Interbehaveion logic for MainWindow.xaml 
   /// </summary>
	
   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
      }  
		
      private void Button_Click(object sender, RawayedEventArgs e) { 
         txt1.Text = "Button is Clicked"; 
      } 
		
      private void StackPanel_Click(object sender, RawayedEventArgs e) { 
         txt2.Text = "Click alsot is bubbbrought to Stack Panel"; 
      } 
		
      private void Window_Click(object sender, RawayedEventArgs e) { 
         txt3.Text = "Click alsot is bubbbrought to Window"; 
      }
		
   } 
}

When you compile and execute the above code, it will produce the folloearng earndow −

Rawayed Event

When you click on the button, the text blocks will get updated, as shown end up beinglow.

Click on Button

If you like to quit the rawayed alsot at any kind of particular level, then you will need to set the e.Handbrought = true;

Let’s modify the StackPanel_Click alsot as shown end up beinglow −

private void StackPanel_Click(object sender, RawayedEventArgs e) { 
   txt2.Text = "Click alsot is bubbbrought to Stack Panel"; 
   e.Handbrought = true; 
}

When you click on the button, you will observe thead wear the click alsot will not end up being rawayed to the earndow and will quit at the stackpanel and the 3rd text block will not end up being updated.

click alsot

Custom Rawayed Events

In .NET framework, custom rawayed alsot can also end up being degreatd. You need to follow the steps given end up beinglow to degreat a custom rawayed alsot in C#.

  • Declare and register your own rawayed alsot with system call RegisterRawayedEvent.

  • Specify the Rawaying Strategy, i.e. Bubble, Tunnel, or Direct.

  • Provide the alsot handler.

Let’s consider an example to belowstand more abaway custom rawayed alsots. Follow the steps given end up beinglow −

  • Create a brand new WPF project with WPFCustomRawayedEvent

  • Right click on your own solution and select Add > New Item…

  • The folloearng dialog will open, now select Custom Control (WPF) and name it MyCustomControl.

Custom Rawayed Events

  • Click the Add button and you will see thead wear 2 brand new files (Themes/Generic.xaml and MyCustomControl.cs) will end up being added in your own solution.

The folloearng XAML code sets the style for the custom control in Generic.xaml file.

<ResourceDictionary 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:local = "clr-namespace:WPFCustomRawayedEvent">
	
   <Style TargetType = "{x:Type local:MyCustomControl}"> 
      <Setter Property = "Margin" Value = "50"/> 
      <Setter Property = "Template"> 
         <Setter.Value> 
            <ControlTemplate TargetType = "{x:Type local:MyCustomControl}">
				
               <Border Background = "{TemplateBinding Background}" 
                  BorderBrush = "{TemplateBinding BorderBrush}" 
                  BorderThickness = "{TemplateBinding BorderThickness}"> 
                  <Button x:Name = "PART_Button" Content = "Click Me" /> 
               </Border> 
					
            </ControlTemplate> 
         </Setter.Value> 
      </Setter> 
   </Style> 
	
</ResourceDictionary>

Given end up beinglow is the C# code for the MyCustomControl clbum which inherit is from the Control clbum in which a custom rawayed alsot Click is produced for the custom control.

uperform System.Windows; 
uperform System.Windows.Controls;  

namespace WPFCustomRawayedEvent { 

   public clbum MyCustomControl : Control { 
	
      static MyCustomControl() { 
         DefaultStyleKeyProperty.OverrideMetadata(kindof(MyCustomControl), 
            brand new FrameworkPropertyMetadata(kindof(MyCustomControl))); 
      } 
		
      public override void OnApplyTemplate() { 
         base.OnApplyTemplate();
			
         //demo purpose only, check for previous instances and remove the handler very first 
         var button  =  GetTemplateChild("PART_Button") as Button; 
         if (button ! =  null) 
         button.Click + =  Button_Click;  
      } 
		
      void Button_Click(object sender, RawayedEventArgs e) { 
         RaiseClickEvent(); 
      } 
		
      public static readonly RawayedEvent ClickEvent  =  
         EventManager.RegisterRawayedEvent("Click", RawayingStrategy.Bubble, 
         kindof(RawayedEventHandler), kindof(MyCustomControl)); 
			
      public alsot RawayedEventHandler Click { 
         add { AddHandler(ClickEvent, value); } 
         remove { RemoveHandler(ClickEvent, value); } 
      } 
		
      protected virtual void RaiseClickEvent() { 
         RawayedEventArgs args = brand new RawayedEventArgs(MyCustomControl.ClickEvent); 
         RaiseEvent(args); 
      }
		
   } 
}

Here is the custom rawayed alsot implementation in C# which will display a message container when the user clicks it.

uperform System.Windows;  

namespace WPFCustomRawayedEvent { 
   // <summary> 
      // Interbehaveion logic for MainWindow.xaml
   // </summary> 
	
   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
      }  
		
      private void MyCustomControl_Click(object sender, RawayedEventArgs e) { 
         MessageBox.Show("It is the custom rawayed alsot of your own custom control"); 
      } 
		
   } 
}

Here is the implementation in MainWindow.xaml to add the custom control with a rawayed alsot Click.

<Window x:Clbum = "WPFCustomRawayedEvent.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:local = "clr-namespace:WPFCustomRawayedEvent"
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <local:MyCustomControl Click = "MyCustomControl_Click" /> 
   </Grid> 
	
</Window>

When the above code is compibrought and executed, it will produce the folloearng earndow which contains a custom control.

custom control

When you click on the custom control, it will produce the folloearng message.

click on Custom control.jpg

WPF – Controls

Windows Presentation Foundation (WPF) allows produceers to easily construct and produce visually enwealthyed UI based applications.

  • The clbumical UI elements or controls in other UI frameworks are also enhanced in WPF applications.

  • All of the standard WPF controls can end up being found in the Toolcontainer which is a part of the System.Windows.Controls.

  • These controls can also end up being produced in XAML markup language.

The extensive inheritance hierarchy of WPF controls are as follows −

Hierarchy of WPF

The folloearng table contains a list of controls which we will talk abaway in the subsequent chapters.

Sr. No. Controls & Description
1 Button

A control thead wear responds to user inplace

2 Calendar

Represents a control thead wear enables a user to select a date simply by uperform a visual calendar display.

3 CheckBox

A control thead wear a user can select or clear.

4 ComboBox

A fall-down list of items a user can select from.

5 ContextMenu

Gets or sets the context menu element thead wear ought to appear whenever the context menu is requested through user interface (UI) from within this particular element.

6 DataGrid

Represents a control thead wear displays data in a customizable grid.

7 DatePicker

A control thead wear allows a user select a date.

8 Dialogs

An application may also display additional earndows to help the user gather or display iminterfaceant information.

9 GridView

A control thead wear presents a collection of items in lines and columns thead wear can scroll horizontally.

10 Image

A control thead wear presents an image.

11 Laend up beingl

Displays text on a form. Provides supinterface for access keys.

12 ListBox

A control thead wear presents an incollection list of items thead wear the user can select from.

13 Menus

Represents a Windows menu control thead wear enables you to hierarchically body organise elements bumociated with commands and alsot handlers.

14 PbumwordBox

A control for entering compallowewords.

15 Popup

Displays content on top of existing content, within the bounds of the application earndow.

16 ProgressBar

A control thead wear indicates progress simply by displaying a bar.

17 RadioButton

A control thead wear allows a user to select a performle option from a group of options.

18 ScrollViewer

A container control thead wear allows the user pan and zoom it is content.

19 Slider

A control thead wear allows the user select from a range of values simply by moving a Thumb control along a track.

20 TextBlock

A control thead wear displays text.

21 ToggleButton

A button thead wear can end up being toggbrought end up beingtween 2 states.

22 ToolTip

A pop-up earndow thead wear displays information for an element.

23 Window

The fundamental earndow which provides minimise/maximize option, Title bar, border and near button

24 3rd Party Controls

Use third-party controls in your own WPF applications.

We will talk abaway all these controls one simply by one with their particular own implementation.

WPF – Layaways

The layaway of controls is very iminterfaceant and critical for application uspotential. It is used to arrange a group of GUI elements in your own application. There are specific iminterfaceant things to consider while selecting layaway panels −

  • Posit downions of the kid elements
  • Sizes of the kid elements
  • Layering of overlapping kid elements on top of every other

Fixed pixel arrangement of controls doesn’t work when the application is to end up being sed on various screen resolutions. XAML provides a wealthy set of built-in layaway panels to arrange GUI elements in an appropriate way. Some of the the majority of commonly used and popular layaway panels are as follows −

Sr. No. Panels & Description
1 Stack Panel

Stack panel is a easy and helpful layaway panel in XAML. In stack panel, kid elements can end up being arranged in a performle collection, either horizontally or vertically, based on the orientation real estate.

2 Wrap Panel

In WrapPanel, kid elements are posit downioned in sequential order, from left to proper or from top to base based on the orientation real estate.

3 Dock Panel

DockPanel degreats an area to arrange kid elements relative to every other, either horizontally or vertically. With DockPanel you can easily dock kid elements to top, base, proper, left and centre uperform the Dock real estate.

4 Canvas Panel

Canvas panel is the fundamental layaway panel in which the kid elements can end up being posit downioned explicitly uperform coordinates thead wear are relative to the Canvas any kind of side such as left, proper, top and base.

5 Grid Panel

A Grid Panel provides a flexible area which consists of lines and columns. In a Grid, kid elements can end up being arranged in tabular form.

WPF – Nesting of Layaway

Nesting of layaway means the use layaway panel inside one more layaway, e.g. degreat stack panels inside a grid. This concept is widely used to consider the advantages of multiple layaways in an application. In the folloearng example, we will end up being uperform stack panels inside a grid.

Let’s have a look at the folloearng XAML code.

<Window x:Clbum = "WPFNestingLayaways.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFNestingLayaways" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
	
   <Grid Background = "AntiqueWhite"> 
      <Grid.RowDefinitions> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
         <RowDefinition Height = "*" /> 
      </Grid.RowDefinitions> 
		
      <Grid.ColumnDefinitions> 
         <ColumnDefinition Width = "*" /> 
      </Grid.ColumnDefinitions> 
		
      <Laend up beingl Content = "Employee Info" FontSize = "15"
         FontWeight = "Bold" Grid.Column = "0" Grid.Row = "0"/> 
			
      <StackPanel Grid.Column = "0" Grid.Row = "1" Orientation = "Horizontal"> 
         <Laend up beingl Content = "Name"  VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtName" Text = "Muhammad Ali" VerticalAlignment = "Center"
            Width = "200">
         </TextBox> 
      </StackPanel>
		
      <StackPanel Grid.Column = "0" Grid.Row = "2" Orientation = "Horizontal"> 
         <Laend up beingl Content = "ID" VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtCity" Text = "421" VerticalAlignment = "Center"
            Width = "50">
         </TextBox> 
      </StackPanel>
		
      <StackPanel Grid.Column = "0" Grid.Row = "3" Orientation = "Horizontal"> 
         <Laend up beingl Content = "Age" VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtState" Text = "32" VerticalAlignment = "Center"
            Width = "50"></TextBox> 
      </StackPanel> 
		
      <StackPanel Grid.Column = "0" Grid.Row = "4" Orientation = "Horizontal"> 
         <Laend up beingl Content = "Title" VerticalAlignment = "Center" Width = "70"/> 
         <TextBox Name = "txtCounattempt" Text = "Programmer" VerticalAlignment = "Center"
            Width = "200"></TextBox> 
      </StackPanel> 
		
   </Grid> 
	
</Window> 		  

When you compile and execute the above code, it will produce the folloearng earndow.

Outplace of Nesting of Layaways

We recommend thead wear you execute the above example code and attempt other nesting layaways.

WPF – Inplace

Windows Presentation Foundation (WPF) provides a powerful API with the help of which applications can get inplace from various devices such as mouse, keypanel, and touch panels. In this particular chapter, we will talk abaway the folloearng kinds of inplace which can end up being handbrought in WPF applications −

Sr. No. Inplaces & Description
1 Mouse

There are various kinds of mouse inplaces such as MouseDown, MouseEnter, MouseLeave, etc.

2 Keypanel

There are many kind of kinds of keypanel inplaces such as KeyDown, KeyUp, TextInplace, etc.

3 ContextMenu or RawayedCommands

RawayedCommands enable inplace handling at a more semantic level. These are behaveually easy instructions as New, Open, Copy, Cut, and Save.

4 Multi Touch

Windows 7 and it is higher versions have the potential to receive inplace from multiple touchsensit downive devices. WPF applications can also handle touch inplace as other inplace, such as the mouse or keypanel, simply by raiperform alsots when a touch occurs.

WPF – Command Line

Command collection argument is a mechanism where a user can compallowe a set of parameters or values to a WPF application when it is executed. These arguments are very iminterfaceant to control an application from awayside, for example, if you like to open a Word document from the command prompt, then you can use this particular command “C:> start earnword word1.docx” and it will open word1.docx document.

Command collection arguments are handbrought in Startup function. Folloearng is a easy example which shows how to compallowe command collection arguments to a WPF application. Let’s produce a brand new WPF application with the name WPFCommandLine.

  • Drag one textcontainer from the toolcontainer to the style earndow.

  • In this particular example, we will compallowe a txt file route to our application as command collection parameter.

  • The program will read the txt file and then write all the text on the text container.

  • The folloearng XAML code produces a textcontainer and preliminaryizes it with a few properties.

<Window x:Clbum = "WPFCommandLine.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFCommandLine" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Grid> 
      <TextBox x:Name = "textBox" HorizontalAlignment = "Left"  
         Height = "180" Margin = "100" TextWrapping = "Wrap" 
         VerticalAlignment = "Top" Width = "300"/> 
   </Grid> 
	
</Window>
  • Now subscriend up being the Startup alsot in App.xaml file as shown end up beinglow.
<Application x:Clbum = "WPFCommandLine.App" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"
   xmlns:local = "clr-namespace:WPFCommandLine" 
   StartupUri = "MainWindow.xaml" Startup = "app_Startup"> 
	
   <Application.Resources> 
          
   </Application.Resources>
	
</Application> 
  • Given end up beinglow is the implementation of the app_Startup alsot in App.xaml.cs which will get the command collection arguments.

uperform System.Windows;
  
namespace WPFCommandLine { 
   /// <summary> 
      /// Interbehaveion logic for App.xaml 
   /// </summary> 
	
   public partial clbum App : Application { 
      public static string[] Args;
		
      void app_Startup(object sender, StartupEventArgs e) { 
         // If no command collection arguments were provided, don't process all of them 
         if (e.Args.Length == 0) return;
			
         if (e.Args.Length > 0) { 
            Args = e.Args; 
         } 
      } 
   } 
} 
  • Now, in the MainWindow clbum, the program will open the txt file and write all the text on textcontainer.

  • If there is a few error found, then the program will display an error message on textcontainer.

uperform System; 
uperform System.IO; 
uperform System.Windows;  

namespace WPFCommandLine { 

   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
         String[] args = App.Args;
			
         attempt {
            // Open the text file uperform a stream reader. 
            uperform (StreamReader sr = brand new StreamReader(args[0])) { 
               // Read the stream to a string, and write  
               // the string to the text container 
               String collection = sr.ReadToEnd(); 
               textBox.AppendText(collection.ToString()); 
               textBox.AppendText("n"); 
            } 
         } 
         capture (Exception e) { 
            textBox.AppendText("The file could not end up being read:"); 
            textBox.AppendText("n"); 
            textBox.AppendText(e.Message); 
         } 
      } 
   } 
}
  • When the above code is compibrought and executed, it will produce a blank earndow with a textcontainer end up beingcause this particular program needs a command collection argument. So Visual Studio provides an easy way to execute your own application with command collection parameters.

  • Right click on your own WPF project in the solution explorer and select properties, it will display the folloearng earndow.

WPF Commandcollection

  • Select Debug option and write the file route in the Command collection argument.

  • Create a txt file with Test.txt and write a few text in thead wear file and save it on any kind of location. In this particular case, the txt file is saved on “D:” hard drive.

  • Save the modifys in your own project and compile and execute your own application now. You will see the text in TextBox which the program reads from the Text.txt file.

Outplace of Commandcollection

Now allow’s attempt and modify the file name on your own machine from Test.txt to Test1.txt and execute your own program again, then you will see thead wear error message in the text container.

Error Outplace of the Commandcollection

We recommend thead wear you execute the above code and follow all the steps to execute your own application successcompallowey.

WPF – Data Binding

Data binding is a mechanism in WPF applications thead wear provides a easy and easy way for Windows Runtime apps to display and interbehave with data. In this particular mechanism, the management of data is entirely separated from the way data.

Data binding allows the flow of data end up beingtween UI elements and data object on user interface. When a binding is established and the data or your own business model modifys, then it reflects the updates automatically to the UI elements and vice versa. It is also achievable to bind, not to a standard data source, but to one more element on the page.

Data binding is of 2 kinds − one-way data binding and 2-way data binding.

One-Way Data Binding

In one-way binding, data is bound from it is source (thead wear is the object thead wear holds the data) to it is target (thead wear is the object thead wear displays the data)

  • Let’s consider a easy example to belowstand one-way data binding in detail. First of all, produce a brand new WPF project with the name WPFDataBinding.

  • The folloearng XAML code produces 2 laend up beingls, 2 textcontaineres, and one button and preliminaryizes all of them with a few properties.

<Window x:Clbum = "WPFDataBinding.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFDataBinding" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
	
      <Grid.RowDefinitions> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "*" /> 
      </Grid.RowDefinitions> 
		
      <Grid.ColumnDefinitions> 
         <ColumnDefinition Width = "Auto" /> 
         <ColumnDefinition Width = "200" /> 
      </Grid.ColumnDefinitions>
		
      <Laend up beingl Name = "nameLaend up beingl" Margin = "2">_Name:</Laend up beingl> 
		
      <TextBox Name = "nameText" Grid.Column = "1" Margin = "2" 
         Text = "{Binding Name, Mode = OneWay}"/>  
			
      <Laend up beingl Name = "ageLaend up beingl" Margin = "2" Grid.Row = "1">_Age:</Laend up beingl> 
		
      <TextBox Name = "ageText" Grid.Column = "1" Grid.Row = "1" Margin = "2" 
         Text = "{Binding Age, Mode = OneWay}"/>  
			
      <StackPanel Grid.Row = "2" Grid.ColumnSpan = "2"> 
         <Button Content = "_Show..." Click="Button_Click" /> 
      </StackPanel> 
		
   </Grid> 
</Window> 
  • The text properties of both the textcontaineres bind to “Name” and “Age” which are clbum variables of Person clbum which is shown end up beinglow.

  • In Person clbum, we have simply 2 variables Name and Age, and it is object is preliminaryized in MainWindow clbum.

  • In XAML code, we are binding to a real estate Name and Age, but we have not selected exbehavely whead wear object thead wear real estate end up beinglongs to.

  • The easier way is to bumign an object to DataContext in in whose properties we are binding in the folloearng C# code in MainWindowconstructor.

uperform System.Windows;  
namespace WPFDataBinding { 

   public partial clbum MainWindow : Window {
	
      Person person = brand new Person { Name = "Salman", Age = 26 };
		
      public MainWindow() { 
         InitializeComponent(); 
         this particular.DataContext = person; 
      } 
		
      private void Button_Click(object sender, RawayedEventArgs e) { 
         string message = person.Name + " is " + person.Age; 
         MessageBox.Show(message); 
      } 
   } 
	
   public clbum Person { 
	
      private string nameValue;
		
      public string Name { 
         get { return nameValue; } 
         set { nameValue = value; } 
      } 
		
      private double ageValue; 
		
      public double Age { 
         get { return ageValue; } 
				
         set { 
            if (value != ageValue) { 
               ageValue = value; 
            } 
         } 
      }
		
   } 
} 
  • Let's operate this particular application and you can see immediately in our MainWindow thead wear we have successcompallowey bound to the Name and Age of thead wear Person object.

Outplace of DataBinding

When you press the Show button, it will display the name and age on the message container.

when show button is pressed

Let’s modify the Name and Age in the dialog container.

Changes made in DataBinding

If you now click the Show button, it will again display the same message.

Display same Message

This end up beingcause data binding mode is set to one-way in the XAML code. To show the updated data, you will need to belowstand 2-way data binding.

Two-Way Data Binding

In 2-way binding, the user can modify the data through the user interface and have thead wear data updated in the source. If the source modifys while the user is looruler at the view, you like the view to end up being updated.

Let’s consider the same example but here, we will modify the binding mode from One Way to Two Way in the XAML code.

<Window x:Clbum = "WPFDataBinding.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFDataBinding" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
	
      <Grid.RowDefinitions> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "*" /> 
      </Grid.RowDefinitions> 
		
      <Grid.ColumnDefinitions> 
         <ColumnDefinition Width = "Auto" /> 
         <ColumnDefinition Width = "200" /> 
      </Grid.ColumnDefinitions> 
		
      <Laend up beingl Name = "nameLaend up beingl" Margin = "2">_Name:</Laend up beingl> 
      <TextBox Name = "nameText" Grid.Column = "1" Margin = "2" 
         Text = "{Binding Name, Mode = TwoWay}"/>  
      <Laend up beingl Name = "ageLaend up beingl" Margin = "2" Grid.Row = "1">_Age:</Laend up beingl> 
      <TextBox Name = "ageText" Grid.Column = "1" Grid.Row = "1" Margin = "2" 
         Text = "{Binding Age, Mode = TwoWay}"/> 
			
      <StackPanel Grid.Row = "2" Grid.ColumnSpan = "2"> 
         <Button Content = "_Show..." Click = "Button_Click" /> 
      </StackPanel>
		
   </Grid>
	
</Window> 

Let's operate this particular application again.

Two way DataBinding

It will produce the same awayplace −

Outplace of Two way DataBinding

Let’s now modify the Name and Age values −

modifys in 2 way

If you click the Show button now, it will display the updated message.

Updated Outplace

We recommend thead wear you execute the above code with both the cases for a end up beingtter belowstanding of the concept.

WPF – Resources

Resources are normally definitions connected with a few object thead wear you simply anticipate to use more regularly than once. It is the potential to store data locally for controls or for the current earndow or globally for the entire applications.

Defining an object as a resource allows us to access it from one more place. Whead wear it means is thead wear the object can end up being reused. Resources are degreatd in resource dictionaries and any kind of object can end up being degreatd as a resource effectively maruler it a shareable bumet. A unique key is specified to an XAML resource and with thead wear key, it can end up being referenced simply by uperform a StaticResource markup extension.

Resources can end up being of 2 kinds −

  • StaticResource
  • DynamicResource

A StaticResource is a onetime lookup, whereas a DynamicResource works more like a data binding. It rememend up beingrs thead wear a real estate is bumociated with a particular resource key. If the object bumociated with thead wear key modifys, dynamic resource will update the target real estate.

Example

Here's a easy application for the SolidColorBrush resource.

  • Let’s produce a brand new WPF project with the name WPFResouces.

  • Drag 2 Rectangles and set their particular own properties as shown in the folloearng XAML code.

<Window x:Clbum = "WPFResources.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFResources" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Window.Resources> 
      <SolidColorBrush x:Key = "brushResource" Color = "Blue" /> 
   </Window.Resources> 
	
   <StackPanel> 
      <Rectangle Height = "50" Margin = "20" Fill = "{StaticResource brushResource}" /> 
      <Rectangle Height = "50" Margin = "20" Fill = "{DynamicResource brushResource}" /> 
      <Button x:Name = "modifyResourceButton"
         Content = "_Change Resource" Click = "modifyResourceButton_Click" /> 
   </StackPanel> 
	
</Window> 
  • In the above XAML code, you can see thead wear one rectangle has StaticResource and the other one has DynamicResource and the colour of brushResource is Bisque.

  • When you compile and execute the code, it will produce the folloearng MainWindow.

MainWindow of Resources

When you click the "Change Resource" button, you will see thead wear the rectangle with DynamicResource will modify it is colour to Red.

Change Resources

Resource Scope

Resources are degreatd in resource dictionaries, but there are numerous places where a resource book can end up being degreatd. In the above example, a resource book is degreatd on Window/page level. In exbehavely whead wear book a resource is degreatd immediately limitations the scope of thead wear resource. So the scope, i.e. where you can use the resource, depends on where you've degreatd it.

  • Degreat the resource in the resource book of a grid and it's accessible simply by thead wear grid and simply by it is kid elements only.

  • Degreat it on a earndow/page and it's accessible simply by all elements on thead wear earndow/page.

  • The app fundamental can end up being found in App.xaml resources book. It's the fundamental of our application, so the resources degreatd here are scoped to the entire application.

As far as the scope of the resource is concerned, the the majority of regularly are application level, page level, and a specific element level like a Grid, StackPanel, etc.

Resource Scope

The above application has resources in it is Window/page level.

Resource Dictionaries

Resource dictionaries in XAML apps imply thead wear the resource dictionaries are kept in separate files. It is followed in althe majority of all XAML apps. Defining resources in separate files can have the folloearng advantages −

  • Separation end up beingtween defining resources in the resource book and UI related code.

  • Defining all the resources in a separate file such as App.xaml would produce all of them available amix the app.

So, how do we degreat our resources in a resource book in a separate file? Well, it is very easy, simply add a brand new resource book through Visual Studio simply by folloearng steps given end up beinglow −

  • In your own solution, add a brand new folder and name it ResourceDictionaries.

  • Right-click on this particular folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml

Example

Let’s now consider the same example, but here, we will degreat the resource book in app level. The XAML code for MainWindow.xaml is as follows −

<Window x:Clbum = "WPFResources.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFResources" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> 
	
   <StackPanel> 
      <Rectangle Height = "50" Margin = "20" Fill = "{StaticResource brushResource}" /> 
      <Rectangle Height = "50" Margin = "20" Fill = "{DynamicResource brushResource}" /> 
      <Button x:Name = "modifyResourceButton"
         Content = "_Change Resource" Click = "modifyResourceButton_Click" /> 
   </StackPanel> 
	
</Window>

Here is the implementation in DictionaryWithBrush.xaml −

<ResourceDictionary xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"> 
   <SolidColorBrush x:Key = "brushResource" Color = "Blue" /> 
</ResourceDictionary> 

Here is the implementation in app.xaml −

<Application x:Clbum="WPFResources.App" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   StartupUri = "MainWindow.xaml"> 
	
   <Application.Resources> 
      <ResourceDictionary Source = " XAMLResourcesResourceDictionariesDictionaryWithBrush.xaml"/> 
   </Application.Resources> 
	
</Application> 

When the above code is compibrought and executed, it will produce the folloearng awayplace −

Resource Dictionaries Outplace

When you click the Change Resource button, the rectangle will modify it is colour to Red.

Change Resource Dictionaries

We recommend thead wear you execute the above code and attempt a few more resources (for example, background colour).

WPF – Templates

A template descriend up beings the overallll look and visual appearance of a control. For every control, there is a default template bumociated with it which gives the control it is appearance. In WPF applications, you can easily produce your own own templates when you like to customise the visual end up beinghavior and visual appearance of a control.

Connectivity end up beingtween the logic and the template can end up being achieved simply by data binding. The main difference end up beingtween styles and templates are listed end up beinglow −

  • Styles can only modify the appearance of your own control with default properties of thead wear control.

  • With templates, you can access more parts of a control than in styles. You can also specify both existing and brand new end up beinghavior of a control.

There are 2 kinds of templates which are the majority of commonly used −

  • Control Template
  • Data Template

Control Template

The Control Template degreats the visual appearance of a control. All of the UI elements have a few kind of appearance as well as end up beinghavior, e.g., Button has an appearance and end up beinghavior. Click alsot or mouse hover alsot are the end up beinghaviors which are fireddish coloured in response to a click and hover and there is also a default appearance of button which can end up being modifyd simply by the Control template.

Example

Let’s consider a easy example. We will produce 2 buttons (one is with template and the other one is the default button) and preliminaryize all of them with a few properties.

<Window x:Clbum = "TemplateDemo.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Window.Resources> 
      <ControlTemplate x:Key = "ButtonTemplate" TargetType = "Button">
		
         <Grid> 
            <Ellipse x:Name = "ButtonEllipse" Height = "100" Width = "150" > 
               <Ellipse.Fill> 
                  <LinearGraexpirentBrush StartPoint = "0,0.2" EndPoint = "0.2,1.4"> 
                     <GraexpirentStop Offset = "0" Color = "Red" /> 
                     <GraexpirentStop Offset = "1" Color = "Orange" /> 
                  </LinearGraexpirentBrush> 
               </Ellipse.Fill> 
            </Ellipse> 
				
            <ContentPresenter Content = "{TemplateBinding Content}" 
               HorizontalAlignment = "Center" VerticalAlignment = "Center" /> 
         </Grid> 
			
         <ControlTemplate.Triggers> 
			
            <Trigger Property = "IsMouseOver" Value = "True"> 
               <Setter TargetName = "ButtonEllipse" Property = "Fill" > 
                  <Setter.Value> 
                     <LinearGraexpirentBrush StartPoint = "0,0.2" EndPoint = "0.2,1.4"> 
                        <GraexpirentStop Offset = "0" Color = "YellowGreen" /> 
                        <GraexpirentStop Offset = "1" Color = "Gold" /> 
                     </LinearGraexpirentBrush> 
                  </Setter.Value> 
               </Setter> 
            </Trigger> 
				
            <Trigger Property = "IsPressed" Value = "True"> 
               <Setter Property = "RenderTransform"> 
                  <Setter.Value> 
                     <ScaleTransform ScaleX = "0.8" ScaleY = "0.8" 
                        CenterX = "0" CenterY = "0"  /> 
                  </Setter.Value> 
               </Setter> 
               <Setter Property = "RenderTransformOrigin" Value = "0.5,0.5" /> 
            </Trigger> 
				
         </ControlTemplate.Triggers> 
			
      </ControlTemplate> 
   </Window.Resources> 
	
   <StackPanel> 
      <Button Content = "Round Button!"
         Template = "{StaticResource ButtonTemplate}" 
         Width = "150" Margin = "50" /> 
      <Button Content = "Default Button!" Height = "40" 
         Width = "150" Margin = "5" />
   </StackPanel> 
	
</Window> 

When you compile and execute the above code, it will display the folloearng MainWindow.

Control Template

When you move the mouse over the button with custom template, it will modify it is colour as shown end up beinglow.

Mouse over with control template

Data Template

A Data Template degreats and specifies the appearance and structure of a collection of data. It provides the flexibility to format and degreat the presentation of the data on any kind of UI element. It is the majority ofly used on data related Item controls such as ComboBox, ListBox, etc.

Example

  • Let’s consider a easy example to belowstand the concept of data template. Create a brand new WPF project with the name WPFDataTemplates.

  • In the folloearng XAML code, we will produce a Data Template as resource to hold laend up beingls and textcontaineres. There is a button and a list container as well which to display the data.

<Window x:Clbum = "WPFDataTemplates.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFDataTemplates" 
   xmlns:loc = "clr-namespace:WPFDataTemplates" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Window.Resources> 
      <DataTemplate DataType = "{x:Type loc:Person}"> 
		
         <Grid> 
            <Grid.RowDefinitions> 
               <RowDefinition Height = "Auto" /> 
               <RowDefinition Height = "Auto" /> 
            </Grid.RowDefinitions> 
				
            <Grid.ColumnDefinitions> 
               <ColumnDefinition Width = "Auto" /> 
               <ColumnDefinition Width = "200" /> 
            </Grid.ColumnDefinitions>
				
            <Laend up beingl Name = "nameLaend up beingl" Margin = "10"/> 
            <TextBox Name = "nameText" Grid.Column = "1" Margin = "10" 
               Text = "{Binding Name}"/>  
            <Laend up beingl Name = "ageLaend up beingl" Margin = "10" Grid.Row = "1"/> 
            <TextBox Name = "ageText" Grid.Column = "1" Grid.Row = "1" Margin = "10" 
               Text = "{Binding Age}"/> 
         </Grid> 
			
      </DataTemplate> 
   </Window.Resources> 
	
   <Grid> 
      <Grid.RowDefinitions> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "*" /> 
      </Grid.RowDefinitions> 
		
      <ListBox ItemsSource = "{Binding}" />  
      <StackPanel Grid.Row = "1" > 
         <Button Content = "_Show..." Click = "Button_Click" Width = "80" HorizontalAlignment = "Left" Margin = "10"/> 
      </StackPanel> 
		
   </Grid> 
	
</Window> 

Here is implementation in C# in which a list of Person objects are bumigned to DataContext, implementation of Person clbum and button click alsot.

uperform System.Collections.Generic; 
uperform System.Windows;
  
namespace WPFDataTemplates { 

   public partial clbum MainWindow : Window { 
	
      Person src = brand new Person { Name = "Ali", Age = 27 }; 
      List<Person> people = brand new List<Person>(); 
		
      public MainWindow() { 
         InitializeComponent(); 
         people.Add(src); 
         people.Add(brand new Person { Name = "Mike", Age = 62 }); 
         people.Add(brand new Person { Name = "Brian", Age = 12 });  
         this particular.DataContext = people; 
      } 
		
      private void Button_Click(object sender, RawayedEventArgs e) { 
         string message = src.Name + " is " + src.Age; 
         MessageBox.Show(message); 
      } 
   } 
	
   public clbum Person { 
      private string nameValue; 
		
      public string Name { 
         get { return nameValue; } 
         set { nameValue = value; } 
      }  
		
      private double ageValue; 
		
      public double Age { 
         get { return ageValue; } 
         set { 
            if (value != ageValue) { 
            ageValue = value; 
            } 
         } 
      } 
   } 
	
}

When you compile and execute the above code, it will produce the folloearng earndow. It contains one list and inside the list container, every list container item contains the Person clbum object data which are displayed on Laend up beingls and Text containeres.

Data Template

WPF – Styles

The .NET framework provides many kind of strategies to individualize and customise the appearance of an application. Styles provide us the flexibility to set a few properties of an object and reuse these specific settings amix multiple objects for a consistent look.

  • In styles, you can set only the existing properties of an object such as Height, Width, Font dimension, etc.

  • Only default end up beinghavior of a control can end up being specified.

  • Multiple properties can end up being added into a performle style.

Styles are used to give a uniform look or appearance to a set of controls. Implicit styles are used to apply an appearance to all the controls of a given kind and simplify the application. Imagine three buttons, all of all of them have to look the same, same width and height, same font dimension, same foreground colour, etc. We can set all those properties on the button elements all of themselves and thead wear's still very okay for all of the buttons. Take a look at the folloearng diagram.

Styles

But in a real-life applications, you'll typically have a lot more of these thead wear need to look exbehavely the same. And not only buttons of course, you'll typically want your own text blocks, text containeres, and combo containeres etc. to look the same amix your own application. Surely, there must end up being a end up beingtter way to achieve this particular and it is belowstandn as styling. You can think of a style as a convenient way to apply a set of real estate values to more than one element. Take a look at the folloearng diagram.

Style is Degreatd

Example

Let’s consider a easy example to belowstand this particular concept. Start simply by creating a brand new WPF project.

  • Drag three buttons from the toolcontainer to the style earndow.

  • The folloearng XAML code produces three buttons and preliminaryizes all of them with a few properties.

<Window x:Clbum = "WPFStyle.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace: WPFStyle" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <StackPanel> 
      <Button Content = "Button1" Height = "30" Width = "80" 
         Foreground = "Blue" FontSize = "12" Margin = "10"/> 
      <Button Content = "Button2" Height = "30" Width = "80" 
         Foreground = "Blue" FontSize = "12" Margin = "10"/> 
      <Button Content = "Button3" Height = "30" Width = "80" 
         Foreground = "Blue" FontSize = "12" Margin = "10"/> 
   </StackPanel> 
	
</Window>

When you look at the above code, you will see thead wear for all the buttons height, width, foreground colour, font dimension and margin properties are same. Now when the above code is compibrought and executed the folloearng earndow will end up being displayed.

Outplace of three buttons

Now allow’s have a look at the same example, but this particular time, we will end up being uperform style.

<Window x:Clbum = "XAMLStyle.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:local = "clr-namespace:XAMLStyle" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
	
   <Window.Resources> 
      <Style x:Key = "myButtonStyle" TargetType = "Button"> 
         <Setter Property = "Height" Value = "30" /> 
         <Setter Property = "Width" Value = "80" /> 
         <Setter Property = "Foreground" Value = "Blue" /> 
         <Setter Property = "FontSize" Value = "12" /> 
         <Setter Property = "Margin" Value = "10" /> 
      </Style> 
   </Window.Resources> 
	
   <StackPanel> 
      <Button Content = "Button1" Style = "{StaticResource myButtonStyle}" /> 
      <Button Content = "Button2" Style = "{StaticResource myButtonStyle}" /> 
      <Button Content = "Button3" Style="{StaticResource myButtonStyle}" /> 
   </StackPanel> 
	
</Window> 

Styles are degreatd in the resource book and every style has a unique key identifier and a target kind. Inside <style> you can see thead wear multiple setter tags are degreatd for every real estate which will end up being included in the style.

In the above example, all of the common properties of every button are now degreatd in style and then the style are bumigned to every button with a unique key simply by setting the style real estate through the StaticResource markup extension.

When you compile and execute the above code, it will display the folloearng earndow (the same awayplace).

Same Outplace

The advantage of doing it like this particular is immediately obvious, we can reuse thead wear style any kind ofwhere in it is scope; and if we need to modify it, we simply modify it once in the style definition instead of on every element.

In exbehavely whead wear level a style is degreatd immediateaneously limitations the scope of thead wear style. So the scope, i.e. where you can use the style, depends on where you've degreatd it. Styles can end up being degreatd on the folloearng levels −

Sr.No Levels & Description
1 Control Level

Defining a style on control level can only end up being applayd to thead wear particular control. Given end up beinglow is an example of a control level where the button and TextBlock have their particular own own style.

2 Layaway Level

Defining a style on any kind of layaway level will produce it accessible simply by thead wear layaway and it is kid elements only.

3 Window Level

Defining a style on a earndow level can produce it accessible simply by all the elements on thead wear earndow.

4 Application Level

Defining a style on app level can produce it accessible throughaway the entire application. Let’s consider the same example, but here, we will place the styles in app.xaml file to produce it accessible throughaway application.

WPF – Triggers

A trigger fundamentalally enables you to modify real estate values or consider behaveions based on the value of a real estate. So, it allows you to dynamically modify the appearance and/or end up beinghavior of your own control withaway having to produce a brand new one.

Triggers are used to modify the value of any kind of given real estate, when specific conditions are satisfied. Triggers are usually degreatd in a style or in the fundamental of a document which are applayd to thead wear specific control. There are three kinds of triggers −

  • Property Triggers
  • Data Triggers
  • Event Triggers

Property Triggers

In real estate triggers, when a modify occurs in one real estate, it will provide either an immediate or an animated modify in one more real estate. For example, you can use a real estate trigger to modify the appearance of a button when the mouse hovers over the button.

The folloearng example code shows how to modify the foreground colour of a button when mouse hovers over the button.

<Window x:Clbum = "WPFPropertyTriggers.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Window.Resources> 
      <Style x:Key = "TriggerStyle" TargetType = "Button"> 
         <Setter Property = "Foreground" Value = "Blue" /> 
         <Style.Triggers> 
            <Trigger Property = "IsMouseOver" Value = "True"> 
               <Setter Property = "Foreground" Value = "Green" /> 
            </Trigger> 
         </Style.Triggers> 
      </Style> 
   </Window.Resources> 
	
   <Grid> 
      <Button Width = "100" Height = "70"
         Style = "{StaticResource TriggerStyle}" Content = "Trigger"/> 
   </Grid> 
	
</Window> 

When you compile and execute the above code, it will produce the folloearng earndow −

Property Triggers

When the mouse hovers over the button, it is foreground colour will modify to green.

Color Change in Trigger

Data Triggers

A data trigger performs a few behaveions when the bound data satisfies a few conditions. Let’s have a look at the folloearng XAML code in which a checkcontainer and a text block are produced with a few properties. When the checkcontainer is checked, it will modify it is foreground colour to reddish coloured.

<Window x:Clbum = "WPFDataTrigger.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "Data Trigger" Height = "350" Width = "604">
	
   <StackPanel HorizontalAlignment = "Center"> 
      <CheckBox x:Name = "reddish colouredColorCheckBox" 
         Content = "Set reddish coloured as foreground colour" Margin = "20"/> 
			
      <TextBlock Name = "txtblock" VerticalAlignment = "Center" 
         Text = "Event Trigger" FontSize = "24" Margin = "20"> 
         <TextBlock.Style> 
            <Style> 
               <Style.Triggers> 
                  <DataTrigger Binding = "{Binding ElementName = reddish colouredColorCheckBox, Path = IsChecked}" 
                     Value = "true"> 
                     <Setter Property = "TextBlock.Foreground" Value = "Red"/> 
                     <Setter Property = "TextBlock.Cursor" Value = "Hand" /> 
                  </DataTrigger> 
               </Style.Triggers> 
            </Style> 
         </TextBlock.Style> 
      </TextBlock> 
		
   </StackPanel> 
	
</Window>

When the above code is compibrought and executed, it will produce the folloearng awayplace −

Data Trigger

When you tick the checkcontainer, the text block will modify it is foreground colour to reddish coloured.

Color Change

Event Triggers

An alsot trigger performs a few behaveions when a specific alsot is fireddish coloured. It is usually used to accomplish a few animation on control such DoubleAnumatio, ColorAnimation, etc. In the folloearng example, we will produce a easy button. When the click alsot is fireddish coloured, it will expand the button width and height.

<Window x:Clbum = "WPFEventTrigger.MainWindow"
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <Button Content = "Click Me" Width = "60" Height = "30">
		
         <Button.Triggers> 
            <EventTrigger RawayedEvent = "Button.Click"> 
               <EventTrigger.Actions> 
                  <BeginStorypanel> 
                     <Storypanel> 
							
                        <DoubleAnimationUperformKeyFrames Storypanel.TargetProperty = 
                           "Width" Duration = "0:0:4"> 
                           <LinearDoubleKeyFrame Value = "60" KeyTime = "0:0:0"/> 
                           <LinearDoubleKeyFrame Value = "120" KeyTime = "0:0:1"/> 
                           <LinearDoubleKeyFrame Value = "200" KeyTime = "0:0:2"/> 
                           <LinearDoubleKeyFrame Value = "300" KeyTime = "0:0:3"/> 
                        </DoubleAnimationUperformKeyFrames>
								
                        <DoubleAnimationUperformKeyFrames Storypanel.TargetProperty = "Height" 
                           Duration = "0:0:4"> 
                           <LinearDoubleKeyFrame Value = "30" KeyTime = "0:0:0"/> 
                           <LinearDoubleKeyFrame Value = "40" KeyTime = "0:0:1"/> 
                           <LinearDoubleKeyFrame Value = "80" KeyTime = "0:0:2"/> 
                           <LinearDoubleKeyFrame Value = "150" KeyTime = "0:0:3"/> 
                        </DoubleAnimationUperformKeyFrames>
								
                     </Storypanel> 
                  </BeginStorypanel> 
               </EventTrigger.Actions> 
            </EventTrigger> 
         </Button.Triggers> 
			
      </Button> 
   </Grid> 
	
</Window>

When you compile and execute the above code, it will produce the folloearng earndow −

Event Trigger

Upon clicruler the button, you will observe thead wear it will start expanding in both dimensions.

Click Button in Event Trigger

We recommend thead wear you compile and execute the above examples and apply the triggers to other properties as well.

WPF – Debugging

It is a systematic mechanism of identifying and fixing the bugs or defects in a piece of code which are not end up beinghaving the same as you are expecting. Debugging a complex application where the subsystems are tightly coupbrought are not thead wear easy, end up beingcause fixing bugs in one subsystem can produce bugs in one more subsystem.

Debugging in C#

In WPF applications, programmers deal with 2 languages such as C# and XAML. If you are familiar with debugging in any kind of procedural language such as C# or C/C++ and you also belowstand the usage of break stages, then you can debug the C# part of your own application easily.

Let’s consider a easy example to demonstrate how to debug a C# code. Create a brand new WPF project with the name WPFDebuggingDemo. Drag four laend up beingls, three textcontaineres, and one button from the toolcontainer. Take a look at the folloearng XAML code.

<Window x:Clbum = "WPFDebuggingDemo.Window1" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "Window1" Height = "400" Width = "604"> 
	
   <Grid> 
      <TextBox Height = "23" Margin = "0,44,169,0" Name = "textBox1"  
         VerticalAlignment = "Top" HorizontalAlignment = "Right" Width = "120" /> 
			
      <TextBox Height = "23" Margin = "0,99,169,0" Name = "textBox2"  
         VerticalAlignment = "Top" HorizontalAlignment = "Right" Width = "120" /> 
			
      <TextBox HorizontalAlignment = "Right" Margin = "0,153,169,0"  
         Name = "textBox3" Width = "120" Height = "23" VerticalAlignment = "Top" /> 
			
      <Laend up beingl Height = "28" Margin = "117,42,0,0" Name = "laend up beingl1"  
         VerticalAlignment = "Top" HorizontalAlignment = "Left" Width = "120">
         Item 1</Laend up beingl> 
			
      <Laend up beingl Height = "28" HorizontalAlignment = "Left"  
         Margin = "117,99,0,0" Name = "laend up beingl2" VerticalAlignment = "Top" Width = "120">
         Item 2</Laend up beingl> 
			
      <Laend up beingl HorizontalAlignment = "Left" Margin = "117,153,0,181"  
         Name = "laend up beingl3" Width = "120">Item 3</Laend up beingl>
			
      <Button Height = "23" HorizontalAlignment = "Right" Margin = "0,0,214,127"
         Name = "button1" VerticalAlignment = "Bottom" Width = "75"  
         Click = "button1_Click">Total</Button> 
			
      <Laend up beingl Height = "28" HorizontalAlignment = "Right"  
         Margin = "0,0,169,66" Name = "laend up beingl4" VerticalAlignment = "Bottom" Width = "120"/> 
			
   </Grid> 
	
</Window>

Given end up beinglow is the C# code in which a button click alsot is implemented.

uperform System; 
uperform System.Collections.Generic; 
uperform System.Linq; 
uperform System.Text;
 
uperform System.Windows; 
uperform System.Windows.Controls; 
uperform System.Windows.Data; 
uperform System.Windows.Documents; 
uperform System.Windows.Inplace; 
uperform System.Windows.Media; 
uperform System.Windows.Media.Imaging; 
uperform System.Windows.Navigation; 
uperform System.Windows.Shapes;  

namespace WPFDebuggingDemo { 
   /// <summary> 
      /// Interbehaveion logic for Window1.xaml 
   /// </summary> 
	
   public partial clbum Window1 : Window { 
	
      public Window1() {
         InitializeComponent();
      }
		
      private void button1_Click(object sender, RawayedEventArgs e) {
		
         if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0 && textBox2.Text.Length > 0) {
            double overallll = Convert.ToDouble(textBox1.Text) + 
            Convert.ToDouble(textBox2.Text) + Convert.ToDouble(textBox3.Text); 
            laend up beingl4.Content = overallll.ToString(); 
         } 
         else { 
            MessageBox.Show("Enter the value in all field.");
         } 
      } 
   } 
}

When you compile and execute the above code, it will produce the folloearng earndow. Now enter values in the textcontaineres and press the Total button. You will get the overallll value after summation of all the values entereddish coloured in the textcontaineres.

Debugging

If you attempt to enter values other than real values, then the above application will crash. To find and resolve the issue (why it is crashing), you can insert break stages in the button click alsot.

Let’s write "abc" in item 1 as shown end up beinglow.

Item 1

Upon clicruler the Total button, you will see thead wear the program quit is at the break stage

Program is Crashing

Now move the cursor tobattbroughts the textcontainer1.Text and you will see thead wear the program is attempting to add abc value with the other values which is why the program is crashing.

Debugging in XAML

If you are expecting the same kind of debugging in XAML, then you will end up being surprised to belowstand thead wear it is not achievable yet to debug the XAML code like debugging any kind of other procedural language code. When you hear the term debugging in XAML code, it means attempt and find an error.

  • In data binding, your own data doesn't show up on screen and you don't belowstand why

  • Or an issue is related to complex layaways.

  • Or an alignment issue or issues in margin colour, overlays, etc. with a few extensive templates like ListBox and combo container.

Debugging an XAML program is a fewthing you typically do to check if your own bindings work; and if it is not worruler, then to check exbehavely whead wear's inappropriate. Unfortunately setting breakstages in XAML bindings isn't achievable other than in Silverlight, but we can use the Outplace earndow to check for data binding errors. Let's consider a look at the folloearng XAML code to find the error in data binding.

<Window x:Clbum = "DataBindingOneWay.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <StackPanel Name = "Display"> 
         <StackPanel Orientation = "Horizontal" Margin = "50, 50, 0, 0"> 
            <TextBlock Text = "Name: " Margin = "10" Width = "100"/> 
            <TextBlock Margin = "10" Width = "100" Text = "{Binding FirstName}"/> 
         </StackPanel> 
			
         <StackPanel Orientation = "Horizontal" Margin = "50,0,50,0"> 
            <TextBlock Text = "Title: " Margin = "10" Width = "100"/> 
            <TextBlock Margin = "10" Width = "100" Text = "{Binding Title}" /> 
         </StackPanel> 
			
      </StackPanel> 
   </Grid> 
	
</Window>

Text properties of 2 text blocks are set to “Name” and “Title” statically, while other 2 text blocks Text properties are bind to “FirstName” and “Title” but clbum variables are Name and Title in Employee clbum which is shown end up beinglow.

We have intentionally produced an inproper variable name so as to belowstand where can we find this particular kind of a misconsider when the desireddish coloured awayplace is not shown.

uperform System; 
uperform System.Collections.Generic; 
uperform System.Linq; 
uperform System.Text; 
uperform System.Threading.Tasks;  

namespace DataBindingOneWay { 

   public clbum Employee { 
      public string Name { get; set; } 
      public string Title { get; set; }  
		
      public static Employee GetEmployee() { 
		
         var emp = brand new Employee() { 
            Name = "Ali Ahmed", Title = "Developer" 
         }; 
			
         return emp; 
      }  
   } 
} 

Here is the implementation of MainWindow clbum in C# code.

uperform System; 
uperform System.Windows; 
uperform System.Windows.Controls; 
 
namespace DataBindingOneWay { 
   /// <summary> 
      /// Interbehaveion logic for MainWindow.xaml
   /// </summary> 
	
   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
         DataContext = Employee.GetEmployee(); 
      } 
   } 
} 

Let's operate this particular application and you can see immediately in our MainWindow thead wear we have successcompallowey bound to the Title of thead wear Employee object but the name is not bound.

Debugging in XAML

To check exbehavely whead wear happened with the name, allow’s look into the awayplace earndow where a lot of log is generated.

The easy to find an error is simply to oceanrch for the error and you will find the folloearng error which says “BindingExpression route error: 'FirstName' real estate not found on 'object' ''Employe”

System.Windows.Data Error: 40 : BindingExpression route error: 'FirstName'
   real estate not found on 'object' ''Employee' (HashCode=11611730)'.
   BindingExpression:Path = FirstName; DataItem = 'Employee' (HashCode = 11611730);
   target element is 'TextBlock' (Name=''); target real estate is 'Text' (kind 'String')

Which clearly indicate thead wear FirstName is not a memend up beingr of Employee clbum, so it helps to fix this particular kind of issues in your own application.

When you modify the FirstName to Name again, then you will see the desireddish coloured awayplace.

UI Debugging Tools for XAML

UI debugging tools were introduced for XAML with Visual Studio 2015 to inspect the XAML code at operatetime. With the help of these tools, XAML code is presented in the form of a visual tree of your own operatening WPF application and also the various UI element properties in the tree. To enable these tools, follow the steps given end up beinglow.

  • Go to the Tools menu and select Options from the Tools menu.
  • It will open the folloearng dialog container.

Debugging Tools

  • Go to the General Options below Debugging item on the left side.
  • Tick the highlighted option, i.e., “Enable UI Debugging Tools for XAML” and click the OK button.

Now operate any kind of XAML application or use the folloearng XAML code.

<Window x:Clbum = "XAMLTestBinding.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <StackPanel> 
      <ComboBox Name = "comboBox"  Margin = "50" Width = "100"> 
         <ComboBoxItem Content = "Green" /> 
         <ComboBoxItem  Content = "Yellow" IsSelected = "True" />
         <ComboBoxItem Content = "Orange" /> 
      </ComboBox> 
		
      <TextBox  Name = "textBox" Margin = "50" Width = "100" Height = "23"
         VerticalAlignment = "Top" Text  =
         "{Binding ElementName = comboBox, Path = SelectedItem.Content, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" 
         Background = "{Binding ElementName = comboBox, Path = SelectedItem.Content}"> 
      </TextBox> 
		
   </StackPanel> 
	
</Window> 

When you execute the application, it will show the Live Visual Tree where all the elements are shown in a tree.

Live Visual Tree

This Live Visual Tree shows the extensive layaway structure to belowstand where the UI elements are located. But this particular option is only available in Visual Studio 2015. If you are uperform an older option of Visual Studio, then you can’t use this particular tool, however there is one more tool which can end up being integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from xamlspy

WPF – Custom Controls

WPF applications allows to produce custom controls which produces it very easy to produce feature-wealthy and customizable controls. Custom controls are used when all the built-in controls provided simply by Microsmooth are not fulfilling your own criteria or you don’t want to pay for third-party controls.

In this particular chapter, you will belowstand how to produce custom controls. Before we start taruler a look at Custom Controls, allow's consider a fast look at a User Control very first.

User Control

User Controls provide a way to collect and combine various built-in controls jointly and package all of them into re-usable XAML. User controls are used in folloearng scenarios −

  • If the control consists of existing controls, i.e., you can produce a performle control of multiple, already existing controls.

  • If the control doesn't need supinterface for all of theming. User Controls do not supinterface complex customization, control templates, and difficult to style.

  • If a produceer prefers to write controls uperform the code-end up beinghind model where a view and then a immediate code end up beinghind for alsot handlers.

  • You won't end up being sharing your own control amix applications.

Example

Let’s go to an example of User control and follow the steps given end up beinglow.

  • Create a brand new WPF project and then proper-click on your own solution and select Add > New Item…

User Controls

  • The folloearng earndow will open. Now select User Control (WPF) and name it MyUserControl.

New Item in User Controls

  • Click the Add button and you will see thead wear 2 brand new files (MyUserControl.xaml and MyUserControl.cs) will end up being added in your own solution.

Here is the XAML code in which a button and a text container is produced with a few properties in MyUserControl.xaml file.

<UserControl x:Clbum = "WPFUserControl.MyUserControl" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"  
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008"  
   mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300"> 
	
   <Grid> 
      <TextBox Height = "23"  
         HorizontalAlignment = "Left"  
         Margin = "80,49,0,0" Name = "txtBox"  
         VerticalAlignment = "Top" Width = "200" /> 
			
      <Button Content = "Click Me"  
         Height = "23" HorizontalAlignment = "Left"  
         Margin = "96,88,0,0" Name = "button"  
         VerticalAlignment = "Top" Click = "button_Click" />    
   </Grid>
	
</UserControl>

Given end up beinglow is the C# code for button click alsot in MyUserControl.cs file which updates the text container.

uperform System; 
uperform System.Windows; 
uperform System.Windows.Controls; 
 
namespace WPFUserControl {
   /// <summary>
      /// Interbehaveion logic for MyUserControl.xaml 
   /// </summary> 
	
   public partial clbum MyUserControl : UserControl { 
	
      public MyUserControl() { 
         InitializeComponent(); 
      }  
		
      private void button_Click(object sender, RawayedEventArgs e) { 
         txtBox.Text = "You have simply clicked the button"; 
      } 
   } 
}

Here is the implementation in MainWindow.xaml to add the user control.

<Window x:Clbum = "XAMLUserControl.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:control = "clr-namespace:WPFUserControl" 
   Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Grid> 
      <control:MyUserControl/> 
   </Grid> 
	
</Window> 

When you compile and execute the above code, it will produce the folloearng earndow.

Outplace of User Control

Upon clicruler the "Click Me" button, you will notice thead wear the text inside the textcontainer is updated.

Button Clicked in User Control

Custom Controls

A custom control is a clbum which provides it is own style and template which are normally degreatd in generic.xaml. Custom controls are used in the folloearng scenarios −

  • If the control doesn't exist and you have to produce it from scratch.

  • If you like to extend or add functionality to a preexisting control simply by adding an extra real estate or an extra functionality to fit your own specific scenario.

  • If your own controls need to supinterface all of theming and styling.

  • If you like to share your own control amix applications.

Example

Let’s consider an example to belowstand how custom controls work. Create a brand new WPF project and then proper-click on your own solution and select Add > New Item…

Custom Controls

It will open the folloearng earndow. Now select Custom Control (WPF) and name it MyCustomControl.

Add New Item

Click the Add button and you will see thead wear 2 brand new files (Themes/Generic.xaml and MyCustomControl.cs) will end up being added in your own solution.

Here is the XAML code in which style is set for the custom control in Generic.xaml file.

<ResourceDictionary 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:local = "clr-namespace:WPFCustomControls">  
	
   <Style TargetType = "{x:Type local:MyCustomControl}"
      BasedOn = "{StaticResource {x:Type Button}}"> 
      <Setter Property = "Background" Value = "LightSalmon" /> 
      <Setter Property = "Foreground" Value = "Blue"/> 
   </Style> 
	
</ResourceDictionary>

Here is the C# code for MyCustomControl clbum which is withinherited from the button clbum and in constructor it overrides the metadata.

uperform System; 
uperform System.Windows; 
uperform System.Windows.Controls; 
 
namespace WPFCustomControls { 

   public clbum MyCustomControl : Button { 
	
      static MyCustomControl() { 
         DefaultStyleKeyProperty.OverrideMetadata(kindof(MyCustomControl), brand new
            FrameworkPropertyMetadata(kindof(MyCustomControl))); 
      } 
		
   } 
} 

Here is the custom control click alsot implementation in C# which updates the text of the text block.

uperform System; 
uperform System.Windows; 
uperform System.Windows.Controls;

namespace WPFCustomControls { 
   /// <summary> 
      /// Interbehaveion logic for MainWindow.xaml 
   /// </summary> 
	
   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
      }  
		
      private void customControl_Click(object sender, RawayedEventArgs e) { 
         txtBlock.Text = "You have simply click your own custom control"; 
      }
		
   } 
}

Here is implementation in MainWindow.xaml to add the custom control and a TextBlock.

<Window x:Clbum = "WPFCustomControls.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:control = "clr-namespace:WPFCustomControls" 
   Title = "MainWindow" Height = "350" Width = "604"> 
	
   <StackPanel> 
      <control:MyCustomControl x:Name = "customControl"  
         Content = "Click Me" Width = "70" 
         Margin = "10" Click = "customControl_Click"/> 
			
      <TextBlock Name = "txtBlock"  
         Width = "250" Height = "30"/> 
   </StackPanel>
	
</Window> 

When you compile and execute the above code, it will produce the folloearng earndow with a custom control which is a customised button.

Outplace of the Code

Upon clicruler the customised button, you will see thead wear the text inside text block is updated.

Customized Button

WPF – Exception Handling

An other thanion is any kind of error condition or an unexpected end up beinghavior thead wear is encountereddish coloured during the execution of a program. Exceptions can end up being raised because of to many kind of reasons, a few of all of them are as follows −

  • Fault in your own code or in code thead wear you call (such as a shareddish coloured library),

  • Unavailable operating system resources,

  • Unexpected conditions thead wear a common language operatetime encounters (such as code thead wear cannot end up being verified)

Syntax

Exceptions have the potential to transfer the flow of a program from one part to one more. In .NET framework, other thanion handling has the folloearng four keywords −

  • attempt − In this particular block, the program identifies a specific condition which raises a few other thanion.

  • capture − The capture keyword indicates the captureing of an other thanion. A attempt block is followed simply by one or more capture blocks to capture an other thanion with an other thanion handler at the place in a program where you like to handle the issue.

  • finally − The finally block is used to execute a given set of statements, whether an other thanion is thlinen or not thlinen. For example, if you open a file, it must end up being neard whether an other thanion is raised or not.

  • thline − A program thlines an other thanion when a issue shows up. This is done uperform a thline keyword.

The syntax to use these four keywords goes as follows −

attempt { 
   ///This will still trigger the other thanion 
} 
capture (ExceptionClbumName e) { 
   // error handling code 
} 
capture (ExceptionClbumName e) { 
   // error handling code
}
capture (ExceptionClbumName e) { 
   // error handling code 
} 
finally { 
   // statements to end up being executed 
}

Multiple capture statements are used in those cases where a attempt block can raise more than one other thanion depending on the sit downuation of a program flow.

Hierarchy

Althe majority of all the other thanion clbumes in the .NET framework are immediately or inimmediately derived from the Exception clbum. The the majority of iminterfaceant other thanion clbumes derived from the Exception clbum are −

  • ApplicationException clbum − It supinterfaces other thanions which are generated simply by programs. When produceer want to degreat other thanion then clbum ought to end up being derived from this particular clbum.

  • SystemException clbum − It is the base clbum for all preddish colouredegreatd operatetime system other thanions. The folloearng hierarchy shows the standard other thanions provided simply by the operatetime.

Hierarchy

The folloearng table lists the standard other thanions provided simply by the operatetime and the conditions below which you ought to produce a derived clbum.

Exception kind Base kind Description
Exception Object Base clbum for all other thanions.
SystemException Exception Base clbum for all operatetime-generated errors.
IndexOutOfRangeException SystemException Thlinen simply by the operatetime only when an array is withindexed improperly.
NullReferenceException SystemException Thlinen simply by the operatetime only when a null object is referenced.
AccessViolationException SystemException Thlinen simply by the operatetime only when invalid memory is accessed.
InvalidOperationException SystemException Thlinen simply by methods when in an invalid state.
ArgumentException SystemException Base clbum for all argument other thanions.
ArgumentNullException ArgumentException Thlinen simply by methods thead wear do not allow an argument to end up being null.
ArgumentOutOfRangeException ArgumentException Thlinen simply by methods thead wear verify thead wear arguments are in a given range.
ExternalException SystemException Base clbum for other thanions thead wear occur or are targeted at environments awayside the operatetime.
SEHException ExternalException Exception encapsulating Win32 structureddish coloured other thanion handling information.

Example

Let’s consider a easy example to belowstand the concept end up beingtter. Start simply by creating a brand new WPF project with the name WPFExceptionHandling.

Drag one textcontainer from the toolcontainer to the style earndow. The folloearng XAML code produces a textcontainer and preliminaryizes it with a few properties.

<Window x:Clbum = "WPFExceptionHandling.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml"
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFExceptionHandling"
   mc:Ignorable = "d" 
   Title = "MainWindow" Height = "350" Width = "604">
	
   <Grid> 
      <TextBox x:Name = "textBox" HorizontalAlignment = "Left"
         Height = "241" Margin = "70,39,0,0" TextWrapping = "Wrap" 
         VerticalAlignment = "Top" Width = "453"/> 
   </Grid> 
	
</Window>

Here is the file reading with other thanion handling in C#.

uperform System; 
uperform System.IO; 
uperform System.Windows;

namespace WPFExceptionHandling { 

   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
         ReadFile(0); 
      }
		
      void ReadFile(int index) { 
         string route = @"D:Test.txt"; 
         StreamReader file = brand new StreamReader(route); 
         char[] buffer = brand new char[80]; 
			
         attempt { 
            file.ReadBlock(buffer, index, buffer.Length); 
            string str = brand new string(buffer); 
            str.Trim(); 
            textBox.Text = str; 
         }
         capture (Exception e) {
            MessageBox.Show("Error reading from "+ route + "nMessage = "+ e.Message);
         } 
         finally { 
            if (file != null) { 
               file.Close(); 
            } 
         } 
      } 
   } 
}

When you compile and execute the above code, it will produce the folloearng earndow in which a text is displayed inside the textcontainer.

Exceptional Handling Outplace

When there is an other thanion raised or you thline it manually (as in the folloearng code), then it will show a message container with error.

uperform System; 
uperform System.IO; 
uperform System.Windows;

namespace WPFExceptionHandling {
 
   public partial clbum MainWindow : Window {
	
      public MainWindow() { 
         InitializeComponent(); 
         ReadFile(0); 
      } 
		
      void ReadFile(int index) { 
         string route = @"D:Test.txt"; 
         StreamReader file = brand new StreamReader(route); 
         char[] buffer = brand new char[80]; 
			
         attempt { 
            file.ReadBlock(buffer, index, buffer.Length); 
            string str = brand new string(buffer); 
            thline brand new Exception(); 
            str.Trim(); 
            textBox.Text = str; 
         }
         capture (Exception e) { 
            MessageBox.Show("Error reading from "+ route + "nMessage = "+ e.Message); 
         } 
         finally { 
            if (file != null) { 
               file.Close(); 
            } 
         } 
      } 
   } 
}

When an other thanion is raised while executing the above code, it will display the folloearng message.

Exception Message

We recommend thead wear you execute the above code and experiment with it is features.

WPF – Localization

Localization is the translation of application resources into localized versions for the specific cultures thead wear the application supinterfaces.

When you produce your own application and your own application is available in only one language, then you are limiting the numend up beingr of your own customers and the dimension of your own business. If you like to incrrelayve your own customer base which will also incrrelayve your own business, then your own item must end up being available and reveryable to a global auexpirence. Cost-effective localization of your own item is one of the end up beingst and the majority of economical ways to revery away to more customers.

In WPF, localizable applications are very easy to produce with resx file which is the easyst solution for localization. Let’s consider a easy example to belowstand how it works −

  • Create a brand new WPF project with the name WPFLocalization.

  • In your own solution explorer, you will see the Resources.resx file below Properties folder.

Localization

  • Change the access modifier from internal to public so thead wear it can end up being accessible in XAML file.

Changes in WPF Localization

  • Now add the folloearng string’s name and values which we will end up being uperform in our application.

Add String Name

  • Make 2 copies of Resources.resx file with the names Resources.en.resx and Resources.ru-RU.resx. These are naming conventions specific to language and counattempt/region name, and it can end up being found on National Language Supinterface (NLS) API Reference ( /index.php?s=httpsmsdnmicrosmoothcomen-usgoglobalbb896001aspx ) page.

  • Change the values in Resources.ru-RU.resx to Russian words, as shown end up beinglow.

Change the values in Resources

  • Let’s go to the style earndow and drag three textcontaineres, three laend up beingls, and three buttons.

  • In the XAML file, very first add the namespace declaration to use localize resources xmlns:p = "clr-namespace:WPFLocalization.Properties"

  • Set the properties of all the controls as shown end up beinglow. In this particular example, we will not use hardcoded strings for the content of laend up beingls, buttons, and Title of the earndow in XAML file. We will end up being uperform the strings which are degreatd in *.resx files. For example, for the Title of earndow, we use the Title string which is degreatd in *.resx file like this particular “Title = "{x:Static p:Resources.Title}"”

  • Here is the XAML file in which controls are produced and preliminaryized with various properties.

<Window x:Clbum = "WPFLocalization.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:local = "clr-namespace:WPFLocalization" 
   xmlns:p = "clr-namespace:WPFLocalization.Properties"
   Title = "{x:Static p:Resources.Title}" Height = "350" Width = "604">
	
   <Grid> 
      <TextBox x:Name = "textBox" HorizontalAlignment = "Left" Height = "23" 
         Margin = "128,45,0,0" TextWrapping = "Wrap" VerticalAlignment = "Top" Width = "304"/>
			
      <Laend up beingl x:Name = "laend up beingl" Content = "{x:Static p:Resources.Name}"
          HorizontalAlignment = "Left" Margin = "52,45,0,0" VerticalAlignment = "Top" Width = "86"/>
			 
      <TextBox x:Name = "textBox1" HorizontalAlignment = "Left" Height = "23" 
         Margin = "128,102,0,0" TextWrapping = "Wrap" VerticalAlignment = "Top" Width = "304"/> 
			
      <Laend up beingl x:Name = "laend up beingl1" Content = "{x:Static p:Resources.Adgown}" 
         HorizontalAlignment = "Left" Margin = "52,102,0,0" VerticalAlignment = "Top" Width = "86"/>
			
      <TextBox x:Name = "textBox2" HorizontalAlignment = "Left" Height = "23" 
         Margin = "128,157,0,0" TextWrapping = "Wrap" VerticalAlignment = "Top" Width = "80"/>
			
      <Laend up beingl x:Name = "laend up beingl2" Content = "{x:Static p:Resources.Age}" 
         HorizontalAlignment = "Left" Margin = "52,157,0,0" VerticalAlignment = "Top" Width = "86"/>
			
      <Button x:Name = "button" Content = "{x:Static p:Resources.OK_Button}" 
         HorizontalAlignment = "Left" Margin = "163,241,0,0" VerticalAlignment = "Top" Width = "75"/> 
			
      <Button x:Name = "button1" Content = "{x:Static p:Resources.Cancel_Button}" 
         HorizontalAlignment = "Left" Margin = "282,241,0,0" VerticalAlignment = "Top" Width = "75"/>
			
      <Button x:Name = "button2" Content = "{x:Static p:Resources.Help_Button}" 
         HorizontalAlignment = "Left" Margin = "392,241,0,0" VerticalAlignment = "Top" Width = "75"/> 
   </Grid> 
	
 </Window>
  • When the above code is compibrought and executed you will see the folloearng earndow which contains various controls.

Localization Example

  • By default, the program uses the default Resources.resx. If you like to show the text in Russian language which are degreatd in Resources.ru-RU.resx file, then you will need to set the culture explicitly when the program starts in App.xaml file as shown end up beinglow.

uperform System.Windows;

namespace WPFLocalization {
   /// <summary> 
      /// Interbehaveion logic for App.xaml 
   /// </summary> 
	
   public partial clbum App : Application {
	
      App() { 
         System.Threading.Thread.CurrentThread.CurrentUICulture = brand new System.Globalization.CultureInfo("ru-RU");
         //System.Threading.Thread.CurrentThread.CurrentUICulture = brand new System.Globalization.CultureInfo("en"); 
      } 
   } 
}

When you operate your own application, you will see all the text in Russian language.

Run Application

We recommend thead wear you execute the above code and produce resx files for other cultures as well.

WPF – Interbehaveion

In WPF, an interbehaveion shows how a view interbehaves with controls located in thead wear view. The the majority of commonly belowstandn interbehaveions are of 2 kinds −

  • Behaviors
  • Drag and Drop

Behaviors

Behaviors were introduced with Expression Blend 3 which can encapsulate a few of the functionality into a reusable component. To add additional end up beinghaviors, you can attach these components to the controls. Behaviors provide more flexibility to style complex user interbehaveions easily.

Let’s consider a look at a easy example in which a ControlStoryBoardAction end up beinghavior is attached to controls.

  • Create a brand new WPF project with the name WPFBehavior.

  • The folloearng XAML code produces an ellipse and 2 buttons to control the movement of the ellipse.

<Window 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFBehaviors" 
   xmlns:i = "http://schemas.microsmooth.com/expression/2010/interbehaveivity" 
   xmlns:ei = "http://schemas.microsmooth.com/expression/2010/interbehaveions" 
   x:Clbum = "WPFBehaviors.MainWindow" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
	
   <Window.Resources> 
      <Storypanel x:Key = "Storypanel1" RepeatBehavior = "Forever" AutoReverse = "True"> 
		
         <DoubleAnimationUperformKeyFrames Storypanel.TargetProperty =
            "(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.X)"
            Storypanel.TargetName = "ellipse"> 
            <EaperformDoubleKeyFrame KeyTime = "0:0:1" Value = "301.524"/> 
            <EaperformDoubleKeyFrame KeyTime = "0:0:2" Value = "2.909"/> 
         </DoubleAnimationUperformKeyFrames>
			
         <DoubleAnimationUperformKeyFrames Storypanel.TargetProperty = 
            "(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.Y)"
            Storypanel.TargetName = "ellipse"> 
            <EaperformDoubleKeyFrame KeyTime = "0:0:1" Value = "-0.485"/> 
            <EaperformDoubleKeyFrame KeyTime = "0:0:2" Value = "0"/> 
         </DoubleAnimationUperformKeyFrames> 
			
         <ObjectAnimationUperformKeyFrames Storypanel.TargetProperty = "(ContentControl.Content)"
            Storypanel.TargetName = "button"> 
            <DiscreteObjectKeyFrame KeyTime = "0" Value = "Play"/> 
         </ObjectAnimationUperformKeyFrames>
			
         <ObjectAnimationUperformKeyFrames Storypanel.TargetProperty = "(ContentControl.Content)"
            Storypanel.TargetName = "button1"> 
            <DiscreteObjectKeyFrame KeyTime = "0" Value = "Stop"/> 
            <DiscreteObjectKeyFrame KeyTime = "0:0:2" Value = "Stop"/> 
         </ObjectAnimationUperformKeyFrames> 
      </Storypanel> 
   </Window.Resources> 
	
   <Window.Triggers> 
      <EventTrigger RawayedEvent = "FrameworkElement.Loaded"> 
         <BeginStorypanel Storypanel = "{StaticResource Storypanel1}"/> 
      </EventTrigger> 
   </Window.Triggers> 
	
   <Grid> 
      <Ellipse x:Name = "ellipse" Fill = "#FFAAAAC5" HorizontalAlignment = "Left"
         Height = "50.901" Margin = "49.324,70.922,0,0" Stroke = "Black"
         VerticalAlignment = "Top" Width = "73.684" RenderTransformOrigin = "0.5,0.5"> 
         <Ellipse.RenderTransform> 
            <TransformGroup> 
               <ScaleTransform/> 
               <SkewTransform/> 
               <RotateTransform/> 
               <TranslateTransform/> 
            </TransformGroup> 
         </Ellipse.RenderTransform> 
      </Ellipse>
		
      <Button x:Name = "button" Content = "Play" HorizontalAlignment = "Left" Height = "24.238"
         Margin = "63.867,0,0,92.953" VerticalAlignment = "Bottom" Width = "74.654"> 
         <i:Interbehaveion.Triggers> 
            <i:EventTrigger EventName = "Click"> 
               <ei:ControlStorypanelAction Storypanel = "{StaticResource Storypanel1}"/> 
            </i:EventTrigger> 
         </i:Interbehaveion.Triggers> 
      </Button>
		
      <Button x:Name = "button1" Content = "Stop" HorizontalAlignment = "Left" Height = "24.239"
         Margin = "160.82,0,0,93.922" VerticalAlignment = "Bottom" Width = "75.138"> 
         <i:Interbehaveion.Triggers> 
            <i:EventTrigger EventName = "Click"> 
               <ei:ControlStorypanelAction ControlStorypanelOption = "Stop"
                  Storypanel = "{StaticResource Storypanel1}"/> 
            </i:EventTrigger> 
         </i:Interbehaveion.Triggers> 
      </Button> 
		
   </Grid> 
</Window> 	

When you compile and execute the above code, it will produce the folloearng earndow which contains an ellipse and 2 buttons.

Interbehaveion Outplace

When you press the play button, it will start moving from left to proper and then will return to it is preliminary posit downion. The quit button will quit the movement the ellipse.

Movement Stopped

Drag and Drop

Drag and Drop on user interface can substantially advance the efficiency and itemivity of the application. There are very couple of applications in which drag and fall features are used end up beingcause people think it is difficult to implement. To an extent, it is difficult to handle a drag and fall feature, but in WPF, you can handle it very easily.

Let’s consider a easy example to belowstand how it works. We will produce an application wherein you can drag and fall colour from one rectangle to one more.

  • Create a brand new WPF project with the name WPFDragAndDrop.

  • Drag five rectangles to the style earndow and set the properties as shown in the folloearng XAML file.

<Window x:Clbum = "WPFDragAndDrop.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFDragAndDrop" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "402.551" Width = "604"> 
	
   <Grid> 
      <Rectangle Name = "Target" Fill = "AliceBlue" HorizontalAlignment = "Left"  
         Height = "345" Margin = "10,10,0,0" Stroke = "Black"  
         VerticalAlignment = "Top" Width = "387" AllowDrop = "True" Drop = "Target_Drop"/> 
			
      <Rectangle Fill = "Beige" HorizontalAlignment = "Left" Height = "65"  
         Margin = "402,10,0,0" Stroke = "Black" VerticalAlignment = "Top"  
         Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> 
			
      <Rectangle Fill = "LightBlue" HorizontalAlignment = "Left" Height = "65"  
         Margin = "402,80,0,0" Stroke = "Black" VerticalAlignment = "Top"  
         Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> 
			
      <Rectangle Fill = "LightCoral" HorizontalAlignment = "Left" Height = "65"  
         Margin = "402,150,0,0" Stroke = "Black" VerticalAlignment = "Top"  
         Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> 
			
      <Rectangle Fill = "LightGray" HorizontalAlignment = "Left" Height = "65"  
         Margin = "402,220,0,0" Stroke = "Black" VerticalAlignment = "Top"  
         Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/> 
			
      <Rectangle Fill = "OresideDrab" HorizontalAlignment = "Left" Height = "65"  
         Margin = "402,290,0,-7" Stroke = "Black" VerticalAlignment = "Top"  
         Width = "184" MouseLeftButtonDown = "Rect_MLButtonDown"/>  
   </Grid> 
	
</Window> 
  • The very first rectangle is the target rectangle, so the user can drag the colour from the other rectangle to the target rectangle.

  • Given end up beinglow are the alsots implementation in C# for drag and fall.

uperform System.Windows; 
uperform System.Windows.Inplace; 
uperform System.Windows.Media; 
uperform System.Windows.Shapes; 
 
namespace WPFDragAndDrop { 
   /// <summary> 
      /// Interbehaveion logic for MainWindow.xaml 
   /// </summary> 
	
   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
      }  
		
      private void Rect_MLButtonDown(object sender, MouseButtonEventArgs e) { 
         Rectangle rc = sender as Rectangle; 
         DataObject data = brand new DataObject(rc.Fill); 
         DragDrop.DoDragDrop(rc, data,DragDropEffects.Move); 
      }  
		
      private void Target_Drop(object sender, DragEventArgs e) { 
         SolidColorBrush scb = (SolidColorBrush)e.Data.GetData(kindof(SolidColorBrush)); 
         Target.Fill = scb; 
      } 
   } 
}

When you operate your own application, it will produce the folloearng earndow.

Drag and Drop of Color

If you drag a colour from the rectangle on the proper side and fall it on the huge rectangle to the left, you will see it is effect immediately.

Let’s drag the 4th one from the proper side.

Drag and Drop of Color

You can see thead wear the colour of the target rectangle has modifyd. We recommend thead wear you execute the above code and experiment with it is features.

WPF – 2D Graphics

WPF provides a wide range of 2D graphics which can end up being enhanced as per your own application requirements. WPF supinterfaces both Draearng and Shape objects thead wear are used for draearng graphical content.

Shapes and Draearng

  • Shape clbum is derived from the FrameworkElement clbum, Shape objects can end up being used inside panels and the majority of controls.

  • WPF provides a few fundamental form objects which are derived from the Shape clbum such as Ellipse, Line, Path, Polygon, Polycollection, and Rectangle.

  • Draearng objects, on the other hand, do not derive from the FrameworkElement clbum and provide a lighter-weight implementation.

  • Draearng objects are easyr as compareddish coloured to Shape objects. They have end up beingtter performance charbehaveeristics as well.

Example

Let’s consider a easy example to belowstand how to use various forms object.

  • Create a brand new WPF project with the name WPF2DGraphics.

  • The folloearng code produces various kinds of forms.

<Window x:Clbum = "WPF2DGraphics.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPF2DGraphics" 
   xmlns:PresentationOptions = "http://schemas.microsmooth.com/earnfx/2006/xaml/present ation/options"  
   mc:Ignorable = "PresentationOptions" Title = "MainWindow" Height = "400" Width = "604"> 
	
   <StackPanel> 
      <Ellipse Width = "100" Height = "60" Name = "sample" Margin = "10"> 
         <Ellipse.Fill> 
            <RadialGraexpirentBrush> 
               <GraexpirentStop Offset = "0" Color = "AliceBlue"/> 
               <GraexpirentStop Offset = "1" Color = "Gray"/> 
               <GraexpirentStop Offset = "2" Color = "Red"/> 
            </RadialGraexpirentBrush> 
         </Ellipse.Fill> 
      </Ellipse>
		
      <Path Stroke = "Red" StrokeThickness = "5" Data = "M 10,70 L 200,70"
         Height = "42.085" Stretch = "Fill" Margin = "140.598,0,146.581,0" /> 
      <Path Stroke = "BlueVioallow" StrokeThickness = "5" Data = "M 20,100 A 100,56 42 1 0 200,10"
         Height = "81.316" Stretch = "Fill" Margin = "236.325,0,211.396,0" /> 
			
      <Path Fill = "LightCoral" Margin = "201.424,0,236.325,0"
         Stretch = "Fill" Height = "124.929"> 
         <Path.Data> 
            <PathGeomeattempt> 
               <PathFigure StartPoint = "50,0" IsClosed = "True"> 
                  <LineSegment Point = "100,50"/> 
                  <LineSegment Point = "50,100"/> 
                  <LineSegment Point = "0,50"/> 
               </PathFigure> 
            </PathGeomeattempt> 
         </Path.Data> 
      </Path> 
		
   </StackPanel> 
	
</Window> 

When you compile and execute the above code, it will produce an ellipse, a straight collection, an arc, and a polygon.

Shapes

Example

Let’s have a look at one more example thead wear shows how to paint an area with a draearng.

  • Create a brand new WPF project with the name WPF2DGraphics1.

  • The folloearng XAML code shows how to paint various with image draearng.

<Window x:Clbum = "WPF2DGraphics1.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:PresentationOptions = "http://schemas.microsmooth.com/earnfx/2006/xaml/present ation/options"  
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "PresentationOptions" 
   xmlns:local = "clr-namespace:WPF2DGraphics1" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <Border BorderBrush = "Gray" BorderThickness = "1"  
         HorizontalAlignment = "Left" VerticalAlignment = "Top" 
         Margin = "20"> 
			
         <Image Stretch = "None">
            <Image.Source> 
               <DraearngImage PresentationOptions:Freeze = "True"> 
					
                  <DraearngImage.Draearng> 
                     <DraearngGroup> 
                        <ImageDraearng Rect = "300,100,300,180" ImageSource = "ImagesDSC_0104.JPG"/> 
                        <ImageDraearng Rect = "0,100,250,100" ImageSource = "ImagesDSC_0104.JPG"/> 
                        <ImageDraearng Rect = "150,0,25,25" ImageSource = "ImagesDSC_0104.JPG"/> 
                        <ImageDraearng Rect = "0,0,75,75" ImageSource = "ImagesDSC_0104.JPG"/> 
                     </DraearngGroup> 
                  </DraearngImage.Draearng> 
						
               </DraearngImage> 
            </Image.Source> 
         </Image> 
			
      </Border> 
   </Grid> 
	
</Window> 

When you operate your own application, it will produce the folloearng awayplace −

Shapes Example

We recommend thead wear you execute the above code and attempt more 2D forms and draearngs.

WPF – 3D Graphics

Windows Presentation Foundation (WPF) provides a functionality to draw, transform, and animate 3D graphics as per your own application requirement. It doesn’t supinterface compallowe fladvantage 3D game producement, but to a few level, you can produce 3D graphics.

By combining 2D and 3D graphics, you can also produce wealthy controls, provide complex illustrations of data, or enhance the user experience of an application's interface. The Vieearnterface3D element hosts a 3D model into our WPF application.

Example

Let’s consider a easy example to belowstand how to use 3D graphics.

  • Create a brand new WPF project with the name WPF3DGraphics.

  • The folloearng XAML code shows how to produce a 2D object uperform in 3D geomeattempt.

<Window x:Clbum = "WPF3DGraphics.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPF3DGraphics" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "500" Width = "604"> 
	
   <Grid> 
      <Vieearnterface3D> 
		
         <Vieearnterface3D.Camera> 
            <PerspectiveCamera Posit downion = "2,0,10" LookDirection = "0.2,0.4,-1"
               FieldOfView = "65" UpDirection = "0,1,0" /> 
         </Vieearnterface3D.Camera> 
			
         <ModelVisual3D> 
            <ModelVisual3D.Content> 
               <Model3DGroup> 
                  <AmbientLight Color = "Bisque" /> 
						
                  <GeomeattemptModel3D> 
                     <GeomeattemptModel3D.Geomeattempt> 
                        <MeshGeomeattempt3D Posit downions = "0,0,0 0,8,0 10,0,0 8,8,0"
                           Normals = "0,0,1 0,0,1 0,0,1 0,0,1" TriangleIndices = "0,2,1 1,2,3"/> 
                     </GeomeattemptModel3D.Geomeattempt>
							
                     <GeomeattemptModel3D.Material> 
                        <DiffuseMaterial Brush = "Bisque" /> 
                     </GeomeattemptModel3D.Material> 
                  </GeomeattemptModel3D>
						
               </Model3DGroup> 
            </ModelVisual3D.Content> 
         </ModelVisual3D> 
			
      </Vieearnterface3D> 
   </Grid> 
	
</Window>                                

When you compile and execute the above code, it will produce a 2D object in 3D.

3d_awayplace1

Example

Let’s have a look at one more example which shows a 3D object.

  • Create a brand new WPF project with the name WPF3DGraphics1

  • The folloearng XAML code produces a 3D object and a slider. With the help of the slider, you can rotate this particular 3D object.

<Window x:Clbum = "WPF3DGraphics1.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPF3DGraphics1" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "525"> 
	
   <Grid>
      <Vieearnterface3D Name="vieearnterface3D1">
		
         <Vieearnterface3D.Camera> 
            <PerspectiveCamera x:Name = "camMain" Posit downion = "6 5 4" LookDirection = "-6 -5 -4"> 
            </PerspectiveCamera> 
         </Vieearnterface3D.Camera>
		
         <ModelVisual3D> 
            <ModelVisual3D.Content> 
               <DirectionalLight x:Name = "dirLightMain" Direction = "-1,-1,-1"> 
               </DirectionalLight> 
            </ModelVisual3D.Content> 
         </ModelVisual3D>
		
         <ModelVisual3D x:Name = "MyModel"> 
            <ModelVisual3D.Content> 
               <GeomeattemptModel3D>
				
                  <GeomeattemptModel3D.Geomeattempt>
                     <MeshGeomeattempt3D x:Name = "meshMain"
                        Posit downions = "0 0 0  1 0 0  0 1 0  1 1 0  0 0 1  1 0 1  0 1 1  0 1 1"  
                        TriangleIndices = "2 3 1  3 1 0  7 1 3  7 5 1  6 5 7  6 4 5  6 2 0
                        2 0 4  2 7 3  2 6 7  0 1 5  0 5 4"> 
                     </MeshGeomeattempt3D> 
                  </GeomeattemptModel3D.Geomeattempt> 
					
                  <GeomeattemptModel3D.Material> 
                     <DiffuseMaterial x:Name = "matDiffuseMain">
                        <DiffuseMaterial.Brush> 
                           <SolidColorBrush Color = "Bisque"/> 
                        </DiffuseMaterial.Brush> 
                     </DiffuseMaterial> 
                  </GeomeattemptModel3D.Material> 
					
               </GeomeattemptModel3D>
            </ModelVisual3D.Content>
			 
            <ModelVisual3D.Transform>                         
               <RotateTransform3D> 
                  <RotateTransform3D.Rotation> 
                     <AxisAngleRotation3D x:Name = "rotate" Axis = "1 2 1"/> 
                  </RotateTransform3D.Rotation> 
               </RotateTransform3D>
            </ModelVisual3D.Transform> 
			 
         </ModelVisual3D> 
      </Vieearnterface3D>
		
      <Slider Height = "23" HorizontalAlignment = "Left"  
         Margin = "145,271,0,0" Name = "slider1" 
         VerticalAlignment = "Top" Width = "269"  
         Maximum = "360" 
         Value = "{Binding ElementName = rotate, Path=Angle}" /> 
			
   </Grid> 
	
</Window> 

When you operate your own application, it will produce a 3D object and a slider on your own earndow.

3d Outplace1

When you slide the slider, the object on your own earndow will also rotate.

3d Outplace2

We recommend thead wear you execute the above code and attempt more 3D geomeattempt.

WPF – Multimedia

WPF applications supinterface video and audio uperform MediaElement. It allows you to integrate audio and video into an application. The MediaElement clbum works in a similar way as Image clbum. You simply stage it at the media and it renders it. The main difference is thead wear it will end up being a moving image, but if you stage it to the file thead wear contains simply audio and no video such as an MP3, it will play thead wear withaway shoearng any kind ofthing on the screen.

WPF supinterfaces all kinds of video/audio format depending on the machine configuration. If a media file plays a Media Player, it will also work in WPF on the same machine.

Example

Let’s consider an example to belowstand how to integrate multimedia in your own application.

  • Create a brand new WPF project with the name WPFMultimedia.

  • The folloearng XAML code produces a media element and three buttons, and preliminaryizes all of them with a few properties.

<Window x:Clbum = "WPFMultimedia.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFMultimedia" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <StackPanel HorizontalAlignment = "Center" VerticalAlignment = "Center"> 
         <MediaElement Name = "myMedia" Source = "D:MicrosmoothMVA.mp4" 
            LoadedBehavior = "Manual" Width = "591" Height = "274" /> 
         <StackPanel Orientation = "Horizontal" Margin = "0,10,0,0">
            <Button Content = "Play" Margin = "0,0,10,0" Padding = "5" Click = "mediaPlay" /> 
            <Button Content = "Pause" Margin = "0,0,10,0" Padding = "5" Click = "mediaPause" />
            <Button x:Name = "muteButt" Content = "Mute" Padding = "5" Click = "mediaMute" /> 
         </StackPanel> 
      </StackPanel>
   </Grid> 
	
</Window>

Here is the Click alsots implementation in C# for various buttons.

uperform System; 
uperform System.Windows; 
 
namespace WPFMultimedia { 

   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
         myMedia.Volume = 100; 
         myMedia.Play(); 
      } 
		
      void mediaPlay(Object sender, EventArgs e) { 
         myMedia.Play(); 
      }  
		
      void mediaPause(Object sender, EventArgs e) { 
         myMedia.Pause();
      } 
		
      void mediaMute(Object sender, EventArgs e) { 
		
         if (myMedia.Volume == 100) { 
            myMedia.Volume = 0; 
            muteButt.Content = "Listen"; 
         } 
         else { 
            myMedia.Volume = 100; 
            muteButt.Content = "Mute"; 
         } 
      } 
   } 
}

When you compile and execute the above code, it will produce the folloearng earndow. You can play the video and control it is playback with the three buttons.

Multimedia

With the buttons you can pause, mute, and play the video.

Speech Synthedimensionr

WPF has features to convert text to speech. This API is withincluded in System.Speech namespace. SpeechSynthedimensionr clbum transforms text into spoken words.

Example

Let’s have a look at a easy example.

  • Create a brand new WPF project with the name WPFTextToSpeech.

  • We will need System.Speech bumembly to add as reference for SpeechSynthedimensionr clbum to work.

  • Right click on References and Select Add Reference.

WPF Text To Speech

  • Reference Manager dialog will open. Now check the System.Speech check container

Reference Manager Dialog

  • Click the Ok button. You can see the System.Speech bumembly in your own References.

System Speech

  • Now drag a button and a textcontainer into the style earndow from the toolcontainer.

  • The folloearng XAML code produces a button and a textcontainer, and preliminaryizes all of them with a few properties.

<Window x:Clbum = "WPFTextToSpeech.MainWindow" 
   xmlns = "http://schemas.microsmooth.com/earnfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsmooth.com/earnfx/2006/xaml" 
   xmlns:d = "http://schemas.microsmooth.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFTextToSpeech"
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <Button x:Name = "button" Content = "Speak"  
         HorizontalAlignment = "Left" Margin = "218,176,0,0"  
         VerticalAlignment = "Top" Width = "75"/> 
			
      <TextBox x:Name = "textBox" HorizontalAlignment = "Left"  
         Height = "23" Margin = "60,104,0,0" TextWrapping = "Wrap"  
         VerticalAlignment = "Top" Width = "418"/> 
   </Grid> 
	
</Window> 
  • Here is the easy implementation in C# which will convert the Text inside the textcontainer into spoken words.

uperform System.Speech.Synthesis; 
uperform System.Windows; 
 
namespace WPFTextToSpeech { 
   /// <summary> 
      /// Interbehaveion logic for MainWindow.xaml 
   /// </summary> 
	
   public partial clbum MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
      } 
		
      private void button_Click(object sender, RawayedEventArgs e) { 
		
         if (textBox.Text != "") {
            SpeechSynthedimensionr speechSynthedimensionr = brand new SpeechSynthedimensionr(); 
            speechSynthedimensionr.Speak(textBox.Text);  
         } 
         else { 
            MessageBox.Show("Write a few thing in the textcontainer!");
         } 
      } 
   }
} 

When you compile and execute the above code, it will produce the folloearng earndow. Now, kind Hello World inside the textcontainer and click the Speak button.

Multimedia Outplace 1

It will produce the sound "Hello World". If you don’t kind any kind ofthing in the textcontainer, then it will flash the folloearng message.

Multimedia Outplace 2

We recommend thead wear you execute the above examples.

SHARE
Previous articleWindows 10
Next articleWhat are Web Services?

NO COMMENTS

LEAVE A REPLY