WPF – Elements Tree

WPF – Elements Tree ”; Previous Next There are many technologies where the elements and components are ordered in a tree structure so that the programmers can easily handle the object and change the behavior of an application. Windows Presentation Foundation (WPF) has a comprehensive tree structure in the form of objects. In WPF, there are two ways that a complete object tree is conceptualized − Logical Tree Structure Visual Tree Structure With the help of these tree structures, you can easily create and identify the relationship between UI elements. Mostly, WPF developers and designers either use procedural language to create an application or design the UI part of the application in XAML keeping 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 basic elements of UI are declared by the developer. The logical tree in WPF defines the following − Dependency properties Static and dynamic resources Binding the elements on its name etc. Let’s have a look at the following example in which a button and a list box are created. <Window x:Class = “WPFElementsTree.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/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 root node is the Window and inside the root node, there is only one child, that is StackPanel. But StackPanel contains two child elements, button and list box. List box has three more child list box items. Visual Tree Structure In WPF, the concept of the visual tree describes the structure of visual objects, as represented by the Visual Base Class. It signifies all the UI elements which are rendered to the output screen. When a programmer wants to create a template for a particular control, he is actually rendering the visual tree of that control. The visual tree is also very useful 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 layouts. The routed events mostly travel along the visual tree, not the logical tree. To see the visual tree of the above simple application which contains a button and a list box, let’s compile and execute the XAML code and you will see the following window. When the application is running, you can see the visual tree of the running application in Live Visual Tree window which shows the complete hierarchy of this application, as shown below. The visual tree is typically a superset of the logical tree. You can see here that all the logical elements are also present in the visual tree. So these two trees are really just two different views of the same set of objects that make up the UI. The logical tree leaves out a lot of detail enabling you to focus on the core structure of the user interface and to ignore the details of exactly how it has been presented. The logical tree is what you use to create the basic structure of the user interface. The visual tree will be of interest if you”re focusing on the presentation. For example, if you wish to customize the appearance of any UI element, you will need to use the visual tree. Print Page Previous Next Advertisements ”;

WPF – Templates

WPF – Templates ”; Previous Next A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the control its appearance. In WPF applications, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control. Connectivity between the logic and the template can be achieved by data binding. The main difference between styles and templates are listed below − Styles can only change the appearance of your control with default properties of that control. With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control. There are two types of templates which are most commonly used − Control Template Data Template Control Template The Control Template defines the visual appearance of a control. All of the UI elements have some kind of appearance as well as behavior, e.g., Button has an appearance and behavior. Click event or mouse hover event are the behaviors which are fired in response to a click and hover and there is also a default appearance of button which can be changed by the Control template. Example Let’s take a simple example. We will create two buttons (one is with template and the other one is the default button) and initialize them with some properties. <Window x:Class = “TemplateDemo.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/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> <LinearGradientBrush StartPoint = “0,0.2” EndPoint = “0.2,1.4”> <GradientStop Offset = “0” Color = “Red” /> <GradientStop Offset = “1” Color = “Orange” /> </LinearGradientBrush> </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> <LinearGradientBrush StartPoint = “0,0.2” EndPoint = “0.2,1.4”> <GradientStop Offset = “0” Color = “YellowGreen” /> <GradientStop Offset = “1” Color = “Gold” /> </LinearGradientBrush> </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 following MainWindow. When you move the mouse over the button with custom template, it will change its color as shown below. Data Template A Data Template defines and specifies the appearance and structure of a collection of data. It provides the flexibility to format and define the presentation of the data on any UI element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc. Example Let’s take a simple example to understand the concept of data template. Create a new WPF project with the name WPFDataTemplates. In the following XAML code, we will create a Data Template as resource to hold labels and textboxes. There is a button and a list box as well which to display the data. <Window x:Class = “WPFDataTemplates.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.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> <Label Name = “nameLabel” Margin = “10”/> <TextBox Name = “nameText” Grid.Column = “1” Margin = “10” Text = “{Binding Name}”/> <Label Name = “ageLabel” 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 assigned to DataContext, implementation of Person class and button click event. using System.Collections.Generic; using System.Windows; namespace WPFDataTemplates { public partial class MainWindow : Window { Person src = new Person { Name = “Ali”, Age = 27 }; List<Person> people = new List<Person>(); public MainWindow() { InitializeComponent(); people.Add(src); people.Add(new Person { Name = “Mike”, Age = 62 }); people.Add(new Person { Name = “Brian”, Age = 12 }); this.DataContext = people; } private void Button_Click(object sender, RoutedEventArgs e) { string message = src.Name + ” is ” + src.Age; MessageBox.Show(message); } } public class 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 following window. It contains one list and inside the list box, each list box item contains the Person class object data which are displayed on Labels and Text boxes. Print Page Previous Next Advertisements ”;

WPF – Overview

WPF – Overview ”; Previous Next WPF stands for Windows Presentation Foundation. It is a powerful framework for building Windows applications. This tutorial explains the features that you need to understand to build WPF applications and how it brings a fundamental change in Windows applications. WPF was first introduces in .NET framework 3.0 version, and then so many other features were added in the subsequent .NET framework versions. WPF Architecture Before WPF, the other user interface frameworks offered by Microsoft such as MFC and Windows forms, were just wrappers around User32 and GDI32 DLLs, but WPF makes only minimal use of User32. So, WPF is more than just 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 below. The most important code part of WPF are − Presentation Framework Presentation Core Milcore The presentation framework and the presentation core have been written in managed code. Milcore is a part of unmanaged code which allows tight integration with DirectX (responsible for display and rendering). CLR makes the development process more productive by offering many features such as memory management, error handling, etc. WPF – Advantages In the earlier GUI frameworks, there was no real separation between how an application looks like and how it behaved. Both GUI and behavior was created in the same language, e.g. C# or VB.Net which would require more effort from the developer to implement both UI and behavior associated with it. In WPF, UI elements are designed in XAML while behaviors can be implemented in procedural languages such C# and VB.Net. So it very easy to separate behavior from the designer code. With XAML, the programmers can work in parallel with the designers. The separation between a GUI and its behavior can allow us to easily change the look of a control by using styles and templates. WPF – Features WPF is a powerful framework to create Windows application. It supports many great features, some of which have been listed below − Feature Description Control inside a Control Allows to define a control inside another control as a content. Data binding Mechanism to display and interact with data between UI elements and data object on user interface. Media services Provides an integrated system for building user interfaces with common media elements like images, audio, and video. Templates In WPF you can define the look of an element directly with a Template Animations Building interactivity and movement on user Interface Alternative input Supports multi-touch input on Windows 7 and above. Direct3D Allows to display more complex graphics and custom themes Print Page Previous Next Advertisements ”;

WPF – 2D Graphics

WPF – 2D Graphics ”; Previous Next WPF provides a wide range of 2D graphics which can be enhanced as per your application requirements. WPF supports both Drawing and Shape objects that are used for drawing graphical content. Shapes and Drawing Shape class is derived from the FrameworkElement class, Shape objects can be used inside panels and most controls. WPF provides some basic shape objects which are derived from the Shape class such as Ellipse, Line, Path, Polygon, Polyline, and Rectangle. Drawing objects, on the other hand, do not derive from the FrameworkElement class and provide a lighter-weight implementation. Drawing objects are simpler as compared to Shape objects. They have better performance characteristics as well. Example Let’s take a simple example to understand how to use different shapes object. Create a new WPF project with the name WPF2DGraphics. The following code creates different types of shapes. <Window x:Class = “WPF2DGraphics.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” xmlns:local = “clr-namespace:WPF2DGraphics” xmlns:PresentationOptions = “http://schemas.microsoft.com/winfx/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> <RadialGradientBrush> <GradientStop Offset = “0” Color = “AliceBlue”/> <GradientStop Offset = “1” Color = “Gray”/> <GradientStop Offset = “2” Color = “Red”/> </RadialGradientBrush> </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 = “BlueViolet” 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> <PathGeometry> <PathFigure StartPoint = “50,0” IsClosed = “True”> <LineSegment Point = “100,50”/> <LineSegment Point = “50,100”/> <LineSegment Point = “0,50”/> </PathFigure> </PathGeometry> </Path.Data> </Path> </StackPanel> </Window> When you compile and execute the above code, it will produce an ellipse, a straight line, an arc, and a polygon. Example Let’s have a look at another example that shows how to paint an area with a drawing. Create a new WPF project with the name WPF2DGraphics1. The following XAML code shows how to paint different with image drawing. <Window x:Class = “WPF2DGraphics1.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:PresentationOptions = “http://schemas.microsoft.com/winfx/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> <DrawingImage PresentationOptions:Freeze = “True”> <DrawingImage.Drawing> <DrawingGroup> <ImageDrawing Rect = “300,100,300,180” ImageSource = “ImagesDSC_0104.JPG”/> <ImageDrawing Rect = “0,100,250,100” ImageSource = “ImagesDSC_0104.JPG”/> <ImageDrawing Rect = “150,0,25,25” ImageSource = “ImagesDSC_0104.JPG”/> <ImageDrawing Rect = “0,0,75,75” ImageSource = “ImagesDSC_0104.JPG”/> </DrawingGroup> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Border> </Grid> </Window> When you run your application, it will produce the following output − We recommend that you execute the above code and try more 2D shapes and drawings. Print Page Previous Next Advertisements ”;

WPF – Custom Controls

WPF – Custom Controls ”; Previous Next WPF applications allows to create custom controls which makes it very easy to create feature-rich and customizable controls. Custom controls are used when all the built-in controls provided by Microsoft are not fulfilling your criteria or you don’t want to pay for third-party controls. In this chapter, you will learn how to create custom controls. Before we start taking a look at Custom Controls, let”s take a quick look at a User Control first. User Control User Controls provide a way to collect and combine different built-in controls together and package them into re-usable XAML. User controls are used in following scenarios − If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls. If the control doesn”t need support for theming. User Controls do not support complex customization, control templates, and difficult to style. If a developer prefers to write controls using the code-behind model where a view and then a direct code behind for event handlers. You won”t be sharing your control across applications. Example Let’s go to an example of User control and follow the steps given below. Create a new WPF project and then right-click on your solution and select Add > New Item… The following window will open. Now select User Control (WPF) and name it MyUserControl. Click the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution. Here is the XAML code in which a button and a text box is created with some properties in MyUserControl.xaml file. <UserControl x:Class = “WPFUserControl.MyUserControl” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” xmlns:d = “http://schemas.microsoft.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 below is the C# code for button click event in MyUserControl.cs file which updates the text box. using System; using System.Windows; using System.Windows.Controls; namespace WPFUserControl { /// <summary> /// Interaction logic for MyUserControl.xaml /// </summary> public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } private void button_Click(object sender, RoutedEventArgs e) { txtBox.Text = “You have just clicked the button”; } } } Here is the implementation in MainWindow.xaml to add the user control. <Window x:Class = “XAMLUserControl.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/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 following window. Upon clicking the “Click Me” button, you will notice that the text inside the textbox is updated. Custom Controls A custom control is a class which offers its own style and template which are normally defined in generic.xaml. Custom controls are used in the following scenarios − If the control doesn”t exist and you have to create it from scratch. If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario. If your controls need to support theming and styling. If you want to share your control across applications. Example Let’s take an example to understand how custom controls work. Create a new WPF project and then right-click on your solution and select Add > New Item… It will open the following window. Now select Custom Control (WPF) and name it MyCustomControl. Click the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution. Here is the XAML code in which style is set for the custom control in Generic.xaml file. <ResourceDictionary xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/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 class which is inherited from the button class and in constructor it overrides the metadata. using System; using System.Windows; using System.Windows.Controls; namespace WPFCustomControls { public class MyCustomControl : Button { static MyCustomControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); } } } Here is the custom control click event implementation in C# which updates the text of the text block. using System; using System.Windows; using System.Windows.Controls; namespace WPFCustomControls { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void customControl_Click(object sender, RoutedEventArgs e) { txtBlock.Text = “You have just click your custom control”; } } } Here is implementation in MainWindow.xaml to add the custom control and a TextBlock. <Window x:Class = “WPFCustomControls.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/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 following window with a custom control which is a customized button. Upon clicking the customized button, you will see that the text inside text block is updated. Print Page Previous Next Advertisements ”;

WPF – 3D Graphics

WPF – 3D Graphics ”; Previous Next Windows Presentation Foundation (WPF) provides a functionality to draw, transform, and animate 3D graphics as per your application requirement. It doesn’t support full fledge 3D game development, but to some level, you can create 3D graphics. By combining 2D and 3D graphics, you can also create rich controls, provide complex illustrations of data, or enhance the user experience of an application”s interface. The Viewport3D element hosts a 3D model into our WPF application. Example Let’s take a simple example to understand how to use 3D graphics. Create a new WPF project with the name WPF3DGraphics. The following XAML code shows how to create a 2D object using in 3D geometry. <Window x:Class = “WPF3DGraphics.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/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> <Viewport3D> <Viewport3D.Camera> <PerspectiveCamera Position = “2,0,10” LookDirection = “0.2,0.4,-1” FieldOfView = “65” UpDirection = “0,1,0” /> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <Model3DGroup> <AmbientLight Color = “Bisque” /> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D Positions = “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″/> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial Brush = “Bisque” /> </GeometryModel3D.Material> </GeometryModel3D> </Model3DGroup> </ModelVisual3D.Content> </ModelVisual3D> </Viewport3D> </Grid> </Window> When you compile and execute the above code, it will produce a 2D object in 3D. Example Let’s have a look at another example which shows a 3D object. Create a new WPF project with the name WPF3DGraphics1 The following XAML code creates a 3D object and a slider. With the help of the slider, you can rotate this 3D object. <Window x:Class = “WPF3DGraphics1.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.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> <Viewport3D Name=”viewport3D1″> <Viewport3D.Camera> <PerspectiveCamera x:Name = “camMain” Position = “6 5 4” LookDirection = “-6 -5 -4”> </PerspectiveCamera> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <DirectionalLight x:Name = “dirLightMain” Direction = “-1,-1,-1”> </DirectionalLight> </ModelVisual3D.Content> </ModelVisual3D> <ModelVisual3D x:Name = “MyModel”> <ModelVisual3D.Content> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D x:Name = “meshMain” Positions = “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”> </MeshGeometry3D> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial x:Name = “matDiffuseMain”> <DiffuseMaterial.Brush> <SolidColorBrush Color = “Bisque”/> </DiffuseMaterial.Brush> </DiffuseMaterial> </GeometryModel3D.Material> </GeometryModel3D> </ModelVisual3D.Content> <ModelVisual3D.Transform> <RotateTransform3D> <RotateTransform3D.Rotation> <AxisAngleRotation3D x:Name = “rotate” Axis = “1 2 1″/> </RotateTransform3D.Rotation> </RotateTransform3D> </ModelVisual3D.Transform> </ModelVisual3D> </Viewport3D> <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 run your application, it will produce a 3D object and a slider on your window. When you slide the slider, the object on your window will also rotate. We recommend that you execute the above code and try more 3D geometry. Print Page Previous Next Advertisements ”;

WPF – Discussion

Discuss WPF ”; Previous Next WPF stands for Windows Presentation Foundation. It is a powerful framework for building Windows applications. This tutorial explains the features that you need to understand to build WPF applications and how it brings a fundamental change in Windows applications. Print Page Previous Next Advertisements ”;

WPF – Styles

WPF – Styles ”; Previous Next The .NET framework provides several strategies to personalize and customize the appearance of an application. Styles provide us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc. Only default behavior of a control can be specified. Multiple properties can be added into a single 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 type and simplify the application. Imagine three buttons, all of them have to look the same, same width and height, same font size, same foreground color, etc. We can set all those properties on the button elements themselves and that”s still quite okay for all of the buttons. Take a look at the following diagram. But in a real-life applications, you”ll typically have a lot more of these that need to look exactly the same. And not only buttons of course, you”ll typically want your text blocks, text boxes, and combo boxes etc. to look the same across your application. Surely, there must be a better way to achieve this and it is known as styling. You can think of a style as a convenient way to apply a set of property values to more than one element. Take a look at the following diagram. Example Let’s take a simple example to understand this concept. Start by creating a new WPF project. Drag three buttons from the toolbox to the design window. The following XAML code creates three buttons and initializes them with some properties. <Window x:Class = “WPFStyle.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.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 that for all the buttons height, width, foreground color, font size and margin properties are same. Now when the above code is compiled and executed the following window will be displayed. Now let’s have a look at the same example, but this time, we will be using style. <Window x:Class = “XAMLStyle.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.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 defined in the resource dictionary and each style has a unique key identifier and a target type. Inside <style> you can see that multiple setter tags are defined for each property which will be included in the style. In the above example, all of the common properties of each button are now defined in style and then the style are assigned to each button with a unique key by setting the style property through the StaticResource markup extension. When you compile and execute the above code, it will display the following window (the same output). The advantage of doing it like this is immediately obvious, we can reuse that style anywhere in its scope; and if we need to change it, we simply change it once in the style definition instead of on each element. In what level a style is defined instantaneously limits the scope of that style. So the scope, i.e. where you can use the style, depends on where you”ve defined it. Styles can be defined on the following levels − Sr.No Levels & Description 1 Control Level Defining a style on control level can only be applied to that particular control. Given below is an example of a control level where the button and TextBlock have their own style. 2 Layout Level Defining a style on any layout level will make it accessible by that layout and its child elements only. 3 Window Level Defining a style on a window level can make it accessible by all the elements on that window. 4 Application Level Defining a style on app level can make it accessible throughout the entire application. Let’s take the same example, but here, we will put the styles in app.xaml file to make it accessible throughout application. Print Page Previous Next Advertisements ”;

WPF – Input

WPF – Input ”; Previous Next Windows Presentation Foundation (WPF) provides a powerful API with the help of which applications can get input from various devices such as mouse, keyboard, and touch panels. In this chapter, we will discuss the following types of input which can be handled in WPF applications − Sr. No. Inputs & Description 1 Mouse There are different types of mouse inputs such as MouseDown, MouseEnter, MouseLeave, etc. 2 Keyboard There are many types of keyboard inputs such as KeyDown, KeyUp, TextInput, etc. 3 ContextMenu or RoutedCommands RoutedCommands enable input handling at a more semantic level. These are actually simple instructions as New, Open, Copy, Cut, and Save. 4 Multi Touch Windows 7 and its higher versions have the ability to receive input from multiple touchsensitive devices. WPF applications can also handle touch input as other input, such as the mouse or keyboard, by raising events when a touch occurs. Print Page Previous Next Advertisements ”;

WPF – Data Binding

WPF – Data Binding ”; Previous Next Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface. When a binding is established and the data or your business model changes, then it reflects the updates automatically to the UI elements and vice versa. It is also possible to bind, not to a standard data source, but to another element on the page. Data binding is of two types − one-way data binding and two-way data binding. One-Way Data Binding In one-way binding, data is bound from its source (that is the object that holds the data) to its target (that is the object that displays the data) Let’s take a simple example to understand one-way data binding in detail. First of all, create a new WPF project with the name WPFDataBinding. The following XAML code creates two labels, two textboxes, and one button and initializes them with some properties. <Window x:Class = “WPFDataBinding.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.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> <Label Name = “nameLabel” Margin = “2”>_Name:</Label> <TextBox Name = “nameText” Grid.Column = “1” Margin = “2” Text = “{Binding Name, Mode = OneWay}”/> <Label Name = “ageLabel” Margin = “2” Grid.Row = “1”>_Age:</Label> <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 textboxes bind to “Name” and “Age” which are class variables of Person class which is shown below. In Person class, we have just two variables Name and Age, and its object is initialized in MainWindow class. In XAML code, we are binding to a property Name and Age, but we have not selected what object that property belongs to. The easier way is to assign an object to DataContext whose properties we are binding in the following C# code in MainWindowconstructor. using System.Windows; namespace WPFDataBinding { public partial class MainWindow : Window { Person person = new Person { Name = “Salman”, Age = 26 }; public MainWindow() { InitializeComponent(); this.DataContext = person; } private void Button_Click(object sender, RoutedEventArgs e) { string message = person.Name + ” is ” + person.Age; MessageBox.Show(message); } } public class 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 run this application and you can see immediately in our MainWindow that we have successfully bound to the Name and Age of that Person object. When you press the Show button, it will display the name and age on the message box. Let’s change the Name and Age in the dialog box. If you now click the Show button, it will again display the same message. This because data binding mode is set to one-way in the XAML code. To show the updated data, you will need to understand two-way data binding. Two-Way Data Binding In two-way binding, the user can modify the data through the user interface and have that data updated in the source. If the source changes while the user is looking at the view, you want the view to be updated. Let’s take the same example but here, we will change the binding mode from One Way to Two Way in the XAML code. <Window x:Class = “WPFDataBinding.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.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> <Label Name = “nameLabel” Margin = “2”>_Name:</Label> <TextBox Name = “nameText” Grid.Column = “1” Margin = “2” Text = “{Binding Name, Mode = TwoWay}”/> <Label Name = “ageLabel” Margin = “2” Grid.Row = “1”>_Age:</Label> <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 run this application again. It will produce the same output − Let’s now change the Name and Age values − If you click the Show button now, it will display the updated message. We recommend that you execute the above code with both the cases for a better understanding of the concept. Print Page Previous Next Advertisements ”;