WPF
WPF
WPF
1.1 1.2 1.3 WPF Windows-based tutorials WPF Web-based tutorials WPF basic tutorials
Introduction Of WPF:
WPF Stands for (Windows Presentation Foundation) Microsoft introduced WPF(Windows Presentation Foundation) API (Application Programming Interface) in .NET3.0 framework for the first time. WPF merged all the related And unrelated APIs into a single unified object model. So if you want to use 2D and 3D graphics or multimedia for your application you do not use to need use different APIs. WPF provides all the functionalities you need to develop richer GUI applications .Using WPF You can develop GUI for both windows application and web application. Birth Of WPF: Microsoft has developed numerous graphical interface toolkits like C++ Win32 API, VB6, MFC, etc. to build desktop applications. These technologies are capable of designing a good GUI interface for the Windows Applications. But these lacks in some additional and advanced features, such as, 2D & 3D Rendering support, Multimedia Support, Animation Support, etc. which are essential now a days. So Microsoft has introduced WPF(Windows Presentation Foundation) API in .NET3.0 framework for the first time. It is released in the year 2007. .NET 3.0 is officially shipped for the first time with Windows Vista OS. But Windows XP and 2003 versions can also use .NET 3.0. Visual Studio 2005 is the first gateway to program .NET 3.0 applications. So to develop WPF application you need Visual Studio 2005 or later. New Features In WPF: The followinig Figure gives you an overview of the main new features of WPF.
Architecture Of WPF:
In This Architecture These Three assemblies can be categorized as * Managed Layer * UnManaged Layer * Core API Managed Layer : Managed layer of Windows Presentation Foundation is built using a number of assemblies. These assemblies build up the WPF framework, communicates with lower level unmanaged API to render its content. The few assemblies that comprise the WPF framework are : 1. PresentationFramework.dll : Creates the High level elements like layout panels, controls, windows, styles etc. 2. PresentationCore.dll : It holds base types such as UIElement, Visual from which all shapes and controls are Derived in PresentationFramework.dll.
3. WindowsBase.dll : They hold even more basic elements which are capable to be used outside the WPF environment like Dispatcher object, Dependency Objects. I will discuss each of them later. Unmanaged Layer (milcore.dll): The unmanaged layer of Windows Presentation Foundation is called milcore or Media Integration Library Core. It basically translates theWindows Presentation Foundation higher level objects like layout panels, buttons, animation etc into textures that Direct3D expects. It is the main rendering engine of WPF. WindowsCodecs.dll : This is Diffrent low level API which is used for imaging support in WPF applications. WindowsCodecs.dll comprises of a number of codecs which encodes / decodes images into vector graphics that would be rendered into WPF screen. Direct3D : It is the low level API in which the graphics of Windows Presentation Foundation is rendered. User32 : It is the primary core api which every program uses. It actually manages memory and process separation. GDI & Device Drivers : GDI and Device Drivers are specific to the operating system which is also used from the application to access low level APIs. Class Hierarchy Of WPF:
In Above Figure all Classes of Wpf (Windows Prensentaion Foundation) We Discuused in Detail Difference Between WPF And SilverLight: 1. WPF is based off of the desktop CLR which is the full version of the CLR.
2. Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth of CLR features. It also has a much smaller version of the BCL 3. WPF you can create Windows App, Navigation app and XBAP (IE based) applicationWith Silverlight you can create only XAP (Browser based application.). 4. WPF supports 3 types of routed events (direct, bubbling, and tunneling). Silverlight supports direct and bubbling only. 5. Silveright doesnt support MultiBinding. 6. Silverlight supports the XmlDataProvider but not the ObjectDataProvider. WPF supports both. Advantage of WPF:
1. Broad Integration: Prior to WPF, it was very difficult to use 3D, Video, Speech, and
rich document viewing in addition to normal 2D Graphics and controls would have to learn several independent technologies. WPF covers all these with consisting programming model as well as tight integration when each type of media gets composited and rendered. Resolution Independence: WPF applications are device independent i.e., smart client applications. Like normal applications it wont get decrease the size as the resolution gets increase. This is possible because WPF emphasis on vector graphics. Hardware Acceleration: WPF is built on top of Direct 3D, content in a WPF application whether 2D or 3D, Graphics or text is converted to 3D triangles, textures and other Direct 3D objects and then rendered by hardware. WPF applications can get the benefit of hardware acceleration for smoother graphics and all round better performance. Declerative Programming: WPF takes the declarative programming to the next level with the introduction of Extensible Application Markup Language(XAML), pronounced as Zammel . XAML is like HTML in web used for creating the interface, resulting graphical designers are empowered to contribute directly to the look and feel of applications. Rich Composition and Customization: WPF controls are extremely compostable. Eg: we can create combo box with animated buttons. WPF Windows Based Controls
2. 3.
4.
5.
1. Button Control In WPF 2. Border Control In WPF 3. Label Control in WPF 4. TextBox Control In WPF 5. Canvas Control In WPF 6. CheckBox Control In WPF 7. ComboBox In WPF 8. Stack Panel Control 9. Expander Control 10. DockPanel Control 11. Document Viewer Control 12. Ellipse Control 13. Content Control
14. Frame Control 15. GroupBox Control 16. Grid Control 17. Progressbar Control 18. Menu Control 19. ListView Control 20. Adding Item in ListView Dynamically 21. Formatting And Style Of ListView 22. RadioButton Control 23. Tab Control 24. PasswordBox Control 25. Scroll Viewer Control 26. Slider Control 27. ViewBox Control 28. Separator Control 29. TreeView Control 30. UniformGrid Control 31. WrappedPanel Control 32. Image Control 33. Rectangle Control
Button Control In WPF
The Button element represents a WPF Button control in XAML. <Button></Button> The Width and Height attributes of the Button element represent the width and the height of a Button. The Content property of the Button element sets the text of a button. The x:Name attribute represents the name of the control, which is a unique identifier of a control.
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1"> <Grid> <Button Margin="71,136,77,86" Name="button1">Button</Button> </Grid> </Window>
Adding a Button Click Event Handler The Click attribute of the Button element adds the click event handler. The following code adds the click event handler for a Button.
<Button Height="23" Margin="94,0,108,80" Name="OK" VerticalAlignment="Bottom" Click="button1_Click">Button</Button> <TextBlock Height="21" Margin="61.812,42.723,96.354,0" Name="textBlock1" VerticalAlignment="Top" /> </Grid> </Window>
private void button1_Click(object sender, RoutedEventArgs e) { Random generator = new Random(); int randomValue; randomValue = generator.Next(1, 10); textBlock1.Text += " " + randomValue.ToString(); }
Properties of Button Name AllowDrop AreAnyTouchesCaptured Description Gets or sets a value indicating whether this element can be used as the target of a drag-anddrop operation. Gets a value that indicates whether at least one touch is captured to this element.
Gets a value that indicates whether at least one AreAnyTouchesCapturedWithin touch is captured to this element or to any child elements in its visual tree. Gets a value that indicates whether at least one AreAnyTouchesDirectlyOver touch is pressed over this element. Gets a value that indicates whether at least one AreAnyTouchesOver touch is pressed over this element or any child elements in its visual tree. Gets or sets a cached representation of the CacheMode UIElement. ClickMode Gets or sets when the Click event occurs. Gets or sets the geometry used to define the Clip outline of the contents of an element. Gets or sets a value indicating whether to clip the content of this element (or content coming from ClipToBounds the child elements of this element) to fit into the size of the containing element. Gets or sets the command to invoke when this Command button is pressed. CommandBindings Gets a collection of CommandBinding objects
associated with this element. A CommandBinding enables command handling for this element, and declares the linkage between a command, its events, and the handlers attached by this element. Gets or sets the parameter to pass to the Command property. Gets or sets the element on which to raise the specified command. Gets or sets the content of a ContentControl. Gets or sets a composite string that specifies how to format the Content property if it is displayed as a string. Gets or sets the data template used to display the content of the ContentControl. Gets or sets a template selector that enables an application writer to provide custom templateselection logic. Gets the collection of input bindings associated with this element. Gets or sets the context for input used by this FrameworkElement.
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Border BorderThickness="5" BorderBrush="Green" CornerRadius="10"
Background="LightGray" HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="250"> <Canvas Background="LightCyan" > <Rectangle Canvas.Left="30" Canvas.Top="20" Height="200" Width="200" Stroke="Black" StrokeThickness="10" Fill="Red" /> </Canvas> </Border> </Grid> </Window>
<Label Name="Label1" Content="Hello! I am Label Control" Width="200" Height="30" Canvas.Left="10" Canvas.Top="10" FontSize="14" FontFamily="Georgia" FontWeight="Bold" Background="Black"
Output
Adding Contents to a Label Control The Content property of the Label control allows you to set any other controls as the content of a Label control. The code snippet in Listing 3 adds some ellipse controls to a Label control.
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid Width="331.785"> <Label Canvas.Left="10" Canvas.Top="50"> <StackPanel Orientation="Horizontal"> <Ellipse Width="100" Height="100" Fill="Red" /> <Ellipse Width="80" Height="80" Fill="Orange" />
<Ellipse Width="60" Height="60" Fill="Yellow" /> <Ellipse Width="40" Height="40" Fill="Green" /> <Ellipse Width="20" Height="20" Fill="Blue" /> <Ellipse Width="15" Height="15" Fill="Indigo" /> <Ellipse Width="10" Height="10" Fill="Violet" /> </StackPanel> </Label> </Grid> </Window>
Output-
Formatting a Label The BorderBrush property of the Label sets a brush to draw the border of a Label. You may use any brush to fill the border. Setting Image as Background of a Label
<Label Height="28" HorizontalAlignment="Left" Margin="10,10,0,0" Name="label1" VerticalAlignment="Top" Width="120"></Label> <Image Source="F:\Anilnewtopic\images\border1.JPG" Stretch="Fill"
Output
Setting Background and Foreground Colors The Background and Foreground attributes set the background and foreground colors of text box.
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <TextBox Width="200" Height="40" Canvas.Top="50" Canvas.Left="20" Background="Red" Foreground="Yellow"> This is TextBox !!
Output-
Wrapping and Scrolling Text The TextWrapping attributes sets the wrapping of text and VerticalScrollBarVisibility and HorizontalScrollBarVisibility sets the vertical and horizontal scroll bars visible.
Restricting Input Text MaxHeight, MaxWidth, MaxLines, and MaxLength attributes of text box restricts the maximum height, maximum width, maximum number of lines, and maximum length of the text box. Similarly MinHeight, MinWidht, MinLines, and MinLength restricts the minimum height, minimum width, minimum number of lines, and minimum length of the text box. Setting IsReadOnly attribute to true makes the text box non editable.
Child elements on a Canvas are never resized. The vertical and horizontal alignments on child elements do not work. Child elements are placed on positions set by the Canvas Left, Top, Right, and Bottom properties. Margin does work partially. If Left property of Canvas is set, Right property does not work. If Top property of Canvas is set, Bottom property does not work. Properties The Canvas control has three properties. The Left property represents the distance between the left side of a control and its parent container Canvas. The Top property represents the distance between the top of a control and its parent container Canvas.
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="396.25" Width="453.75"> <Grid Height="343.75" Width="332.5"> <Canvas Background="LightCyan" > <Rectangle Canvas.Left="10" Canvas.Top="10" Height="200" Width="200" Stroke="Black" StrokeThickness="10" Fill="Red" />
</Canvas>
</Grid> </Window>
Output
The Content attribute represents the text of a CheckBox. The Name attribute represents the name of the control, which is a unique identifier of a control. The Foreground attribute defines the foreground color of the text of the CheckBox. The Content attribute defines the text of the CheckBox. FontFamily, FontStyle, FontWeight, FontSize and FontStretch are font related attribute The IsChecked property represents the state of the CheckBox control. The IsThreeState property represents whether the CheckBox has two or three states. Three states are checked, unchecked, or indeterminate. Code for CheckBox Control is given Below-
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="396.25" Width="453.75"> <Grid> <CheckBox Name="McCheckBox" Foreground="Orange" Canvas.Left="20" Canvas.Top="10" Content="Check Me" FontFamily="Georgia" FontSize="20" FontWeight="Bold"> </CheckBox> </Grid> </Window>
Output
Adding Events on CheckBox The Checked and Unchecked attributes of the CheckBox element adds the checked and unchecked event handler. These events are fired when a CheckBox state is changed to checked and unchecked respectively.
<CheckBox Name="McCheckBox" Canvas.Left="10" Canvas.Top="10" Content="Check Me" IsChecked="True" IsThreeState="True" Checked="McCheckBox_Checked" Unchecked="McCheckBox_Unchecked"> </CheckBox>
Output
ComboBox In WPF
The Width and Height properties represent the width and the height of a ComboBox. The x:Name property represents the name of the control, which is a unique identifier of a control. The Margin property sets the location of a ComboBox on the parent control. The HorizontalAlignment and VerticalAlignment properties are used to set horizontal and vertical alignments.
VerticalAlignment="Top" SelectionChanged="comboBox1_SelectionChanged"> <ComboBoxItem Background="Tomato" BorderBrush="Cyan" >Infosis</ComboBoxItem> <ComboBoxItem Background="SpringGreen" BorderBrush="Bisque">TCS</ComboBoxItem> <ComboBoxItem Background="SteelBlue" BorderBrush="Brown">Tech Mahindra</ComboBoxItem> <ComboBoxItem Background="Violet" BorderBrush="Chartreuse">Birla Soft</ComboBoxItem> <ComboBoxItem Background="YellowGreen" BorderBrush="Chocolate">AMDOCS</ComboBoxItem> <ComboBoxItem Background="SteelBlue" BorderBrush="DimGray">Nagarro</ComboBoxItem> </ComboBox>
Output-
comboBox2.IsEnabled = true; comboBox2.Items.Clear(); if (comboBox1.SelectedIndex == 0) { comboBox2.Items.Add("Java"); comboBox2.Items.Add(".Net"); comboBox2.Items.Add("PHP"); comboBox2.Items.Add("Mainframe"); } else if (comboBox1.SelectedIndex == 1) { comboBox2.Items.Add("SAP"); comboBox2.Items.Add("ERP"); comboBox2.Items.Add("Networking"); comboBox2.Items.Add("C/C++"); } else { comboBox2.Items.Add("Networking"); comboBox2.Items.Add("C/C++");
} }
As with the other layout panels, the StackPanel has a collection of Children that it literally shoves one after the other. You set the orientation to either horizontal or vertical to control where the items go. As shown in picture above. You might use the StackPanel if you have a series of controls with a set width or height that you want to show up in a row. For example, you might use StackPanel when you have a series of controls in a side panel (like the accordion control in Microsoft Outlookyou can expand/contract sections for mail, calendar, tasks, and so on). The controls can all change size, and the other controls will automatically be moved to accommodate the space. Code for Stack Panel
<StackPanel Orientation="Vertical"> <Button Width="200">First</Button> <Button HorizontalAlignment="Left">Second</Button> <Button Padding="10 4">Third</Button> <Button Margin="20 20">Fourth</Button> <Button Padding="10 4" HorizontalAlignment="Right">Fifth</Button> <Button HorizontalAlignment="Stretch">Sixth</Button> </StackPanel>
Adding scrolling support Adding scrolling is easy, and, once you get used to the idea of control composition, fairly intuitive. We simply put the StackPanel (or anything else we want to automatically scroll) inside a ScrollViewer. Code for this
<Button Width="200" >First</Button> <Button HorizontalAlignment ="Left">Second</Button> <Button Padding="10 4">Third</Button> <Button Margin="20 20">Fourth</Button> <Button Padding="10 4" HorizontalAlignment="Right">Fifth</Button> <Button HorizontalAlignment="Stretch">Sixth</Button> </StackPanel> </ScrollViewer>
The Expander control works similarly to the sections in Windows Explorer that allow you to show or hide different sections
<ScrollViewer VerticalScrollBarVisibility="Auto"> <StackPanel Orientation="Vertical"> <Expander Header="My Documents" BorderThickness="3" BorderBrush="Aquamarine" Background="Chocolate"> <StackPanel Background="Aqua" > <Label >Books</Label>
<Expander Header="My Computers" BorderThickness="3" BorderBrush="AntiqueWhite" Background="Chocolate"> <StackPanel> <Button>Local Disk C:</Button> <Button>Local Disk D:</Button> <Button>Local Disk E:</Button> <Button>Local Disk F:</Button> <Button>Local Disk G:</Button> <Button>Local Disk H:</Button> </StackPanel> </Expander> </StackPanel> </ScrollViewer>
The Expander can only contain one thing: its contents. If we want to add multiple items, we have to put something inside the Expander that can hold some number of other things. The StackPanel, as with all the other layout panels, can hold multiple items, so we can add another StackPanel. The StackPanel itself solves some specific layout scenarios, but its quite flexible. It could be used, for example, to build a calculator. You should be able to see how this would work one vertical StackPanel containing a number of vertical StackPanels for the buttons. It wouldnt be easy, but it would be possible. In the next section, we will talk about the DockPanel. The DockPanel can be used to solve some of the same problems but in a different way. As with the StackPanel, the DockPanel, while flexible, is designed to handle a different set of scenarios.
<DockPanel x:Name="dockPanel1"> <ToolBarTray Background="White" DockPanel.Dock="Top"> <ToolBar Band="1" BandIndex="1"> <Button>File</Button> <Button>Edit</Button> <Separator/> <Button>Gelp</Button> </ToolBar> </ToolBarTray> <StatusBar DockPanel.Dock="Bottom"> <StatusBarItem> <TextBlock>Ready</TextBlock> </StatusBarItem> </StatusBar> <StackPanel DockPanel.Dock="Left"> <Expander Header="Useful"> <StackPanel> <Button>Don't</Button> <Button>Press</Button> <Button>Me!</Button> </StackPanel> </Expander>
<Expander Header="Less useful"></Expander> <Expander Header="Silly"></Expander> </StackPanel> <Button Padding="10 10"> <TextBlock TextWrapping="Wrap" TextAlignment="Center">This is all of the remaining space that is not docked</TextBlock> </Button> </DockPanel>
You may have multiple assemblies installed on your machine. Make sure you select Version 12 for Microsoft.Office.Interop.Word assemblies as you see in Figure bellow, otherwise your conversion will fail.
Once you have added the reference to assemblies, you must import the following namespaces to your code behind. using using using using System.IO; Microsoft.Office.Interop.Word; Microsoft.Win32; System.Windows.Xps.Packaging;
Convert Doc to XPS The SaveAs method of Document class available in OfficeInterop allows us to save a word document as an XPS document. However, you must make sure you have version 12 of assembly added to your project as I mentioned before. The ConvertWordDocToXPSDoc method takes a full path of a word document file and new full path of XPS document and converts doc file to an xps file.
private XpsDocument ConvertWordDocToXPSDoc(string wordDocName, string xpsDocName) { // Create a WordApplication and add Document to it Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application(); wordApplication.Documents.Add(wordDocName); Document doc = wordApplication.ActiveDocument; // You must make sure you have Microsoft.Office.Interop.Word.Dll version
12. // Version 11 or previous versions do not have WdSaveFormat.wdFormatXPS option try { doc.SaveAs(xpsDocName, WdSaveFormat.wdFormatXPS); wordApplication.Quit(); XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read); return xpsDoc; } catch (Exception exp) { string str = exp.Message; } return null; }
<Grid> <DocumentViewer HorizontalAlignment="Left" Margin="0,42,0,0" Name="documentViewer1" VerticalAlignment="Top" Height="508" Width="766" /> <TextBox Height="29" HorizontalAlignment="Left" Margin="6,6,0,0" Name="SelectedFileTextBox" VerticalAlignment="Top" Width="276" /> <Button Content="Browse" Height="30" HorizontalAlignment="Right" Margin="0,6,353,0" Name="BrowseButton" VerticalAlignment="Top" Width="122" Click="BrowseButton_Click" /> </Grid>
Output-
<Button Height="73" HorizontalAlignment="Right" Margin="0,17,19,0" Name="button3" VerticalAlignment="Top" Width="67">Button</Button> <Button HorizontalAlignment="Left" Margin="0,89,0,100" Name="button4" Width="71">Button</Button> <Button Margin="0,89,86,100" Name="button5" HorizontalAlignment="Right" Width="68">Button</Button> <Button HorizontalAlignment="Right" Margin="0,89,19,100" Name="button6" Width="67">Button</Button> <Button Height="51" Margin="0,0,19,51" Name="button7" VerticalAlignment="Bottom">Button</Button>
Output-
<Window x:Class="WpfApplication5.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid Width="224"> <TextBlock>Outside area of frame</TextBlock> <Frame Source="Page1.xaml">
The Window looks like as below in picture. The Blue area is the Page1.xaml and white area is outside of the Frame.
Now you can manage contents of a frame the way you want. For example, the following code rotates the contents of frame to 45 angle.
Output -
<Window x:Class="WpfApplication5.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <GroupBox Header="GroupBox" Margin="13,28,34,43" Name="groupBox1"> <CheckBox Height="21" Name="checkBox1">CheckBox</CheckBox> </GroupBox> <CheckBox Height="16" Margin="19,82,139,0" Name="checkBox2" VerticalAlignment="Top">CheckBox</CheckBox> <Button Height="23" Margin="125,96,79,0" Name="button1" VerticalAlignment="Top"> Button</Button> </Grid> </Window>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="75" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions>
A Grid has RowDefinitions and ColumnDefinitions that specify the height (specific to the row), the width (specific to the column), and possibly other dimensional aspects. Normally, you would expect to see a combination of row/cell or row/column objects to lay out the grid; however, WPF works differently. Each control has a Grid.Row and Grid.Column, which specifies the row/column to render in.
The resize behaviour of the controls is defined by the HorizontalAlignment and VerticalAlignment properties who define the anchors. The distance between the anchor and the grid line is specified by the margin of the control.. Define Rows and Columns in Grid:
The grid has one row and column by default. To create additional rows and columns, you have to add RowDefinition items to the RowDefinitions collection and ColumnDefinition items to the ColumnDefinitions collection. The following example shows a grid with three rows and two columns. The size can be specified as an absolute amount of logical units, as a percentage value or automatically. Fixed Fixed size of logical units (1/96 inch) Auto Takes as much space as needed by the contained control Star (*) Takes as much space as available, percentally divided over all star-sized columns. Star-sizes are like percentages, except that the sum of all star columns does not have to be 100%. Remember that star-sizing does not work if the grid size is calculated based on its content. How to Add Control To Grid: To add controls to the grid layout panel just put the declaration between the opening and closing tags of the Grid. Keep in mind that the row- and columndefinitions must precced any definition of child controls. The grid layout panel provides the two attached properties Grid.Column and Grid.Row to define the location of the control..
<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> <RowDefinition Height="28" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Name:"/> <Label Grid.Row="1" Grid.Column="0" Content="EMail:"/> <Label Grid.Row="2" Grid.Column="0" Content="Comment:"/> <TextBox Grid.Column="1" Grid.Row="0" Margin="3" /> <TextBox Grid.Column="1" Grid.Row="1" Margin="3"
/> />
XAML Code
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid Height="284" Background="Beige" Width="343"> <Grid.RowDefinitions> <RowDefinition Height="Auto" MinHeight="25" /> <RowDefinition Height="Auto" MinHeight="27" /> <RowDefinition Height="174*" /> <RowDefinition Height="31.447*" /> <RowDefinition Height="28" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" MinWidth="61" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Name:"/> <Label Grid.Row="1" Grid.Column="0" Content="E-Mail:"/> <Label Grid.Row="2" Content="Comment:" Grid.RowSpan="2" <TextBox Grid.Column="1" Grid.Row="0" Margin="3" /> <TextBox Grid.Column="1" Grid.Row="1" Margin="3" />
/>
<TextBox Grid.Column="1" Grid.Row="2" Margin="3" Grid.RowSpan="2" /> <Button Grid.Column="1" Grid.Row="4" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="Discard " /> <Button Grid.Column="1" Grid.Row="1" HorizontalAlignment="Right" MinWidth="80" Margin="0,5.999,-79.547,0" Content="Send" Height="21.277" Grid.RowSpan="2" VerticalAlignment="Top" Width="80" /> </Grid> </Window>
ProgressBar.Value from 0 to 100 over the course of 1 second. We set the autoreverse property to true, to allow the animation to go forwards and backwards. The xaml to do this would be: .XAML Code:
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid Background="Beige"> <ProgressBar Margin="119,136,126,0" Name="ProgressBar1" Height="24" VerticalAlignment="Top"> <ProgressBar.RenderTransform> <RotateTransform Angle="0" CenterX="75" CenterY="12" /> </ProgressBar.RenderTransform> <ProgressBar.Triggers> <EventTrigger RoutedEvent="ProgressBar.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="ProgressBar1" Storyboard.TargetProperty="Value" From="0" To="100" Duration="0:0:1" AutoReverse="True" RepeatBehavior="Forever" /> <DoubleAnimation Storyboard.TargetName="ProgressBar1" Storyboard.TargetProperty="(RenderTransform).(RotateTransform.Angle)" From="0" To="360" Duration="0:0:2" AutoReverse="False" RepeatBehavior="Forever" /> </Storyboard>
</ProgressBar>
</Grid> </Window>
The Menu tag in XAML creates a menu control. The Name property defines the name of the menu and Height and Width represents the height and width of a menu control. Syntax Of Menu Control: <Menu Margin="37,15,63,0" Name="menu1" Height="22" VerticalAlignment="Top" /> This Tag Creates a Menu Control. Important Properties: Name --> Defines the name of the menu. Height --> Defines the Height of the menu Width --> Defines the width of the menu Margin --> Defines the position of the menu Background--> Defines backcolor of the menu HorizontalAlignment --> Defines the horizontal alignment of the menu inside the parent control. HorizontalContentAlignment --> Defines the horizontal alignment for the menu content. VerticalAlignment --> Defines the vertical alignment of the menu inside the parent control. VerticalContentAlignment --> Defines the content alignment for the menu content. ToolTip --> defines the tooltip for the menu.
A MenuItem can have other MenuItem tags within it as child/sub menus and can go up to several levels. The following code adds three children menu items to first menu item.
<MenuItem Header="_File"> <MenuItem Header="_Open" IsCheckable="true"/> <MenuItem Header="_Close" IsCheckable="true"/> <MenuItem Header="_Save" IsCheckable="true"/> </MenuItem>
The MenuItem.ToolTip tag adds a tooltip to a menu item. The following code adds a tooltip to the Open menu item. <MenuItem Header="_Open" IsCheckable="true"> <MenuItem.ToolTip> <ToolTip> Open a file. </ToolTip> </MenuItem.ToolTip> </MenuItem>
Adding an Event Trigger to a MenuItem: The Click event is used to add the menu item click event handler. The following code adds a click event handler for a menu item.
<MenuItem IsCheckable="true" Header="_Open" Click="MenuItem_Click"> The event handler is defined like following in the code behind. I added a message box when the menu item is clicked. private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Menu item clicked"); } XAML Code Of Menu Control: <Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid> <Menu IsMainMenu="True" Background="WhiteSmoke"> <MenuItem Header="_File" Click="MenuItem_Click" FontSize="15" Foreground="Blue"> <MenuItem Header="_Open" IsCheckable="true"
Click="MenuItem_Click"> <MenuItem.ToolTip> <ToolTip> Open a file. </ToolTip> </MenuItem.ToolTip> </MenuItem> <MenuItem Header="_Close" IsCheckable="true"/> <MenuItem Header="_Save" IsCheckable="true"/> </MenuItem> <MenuItem Header="_Edit" Click="MenuItem_Click_1" Foreground="Blue" FontSize="15" /> <MenuItem Header="_View" Click="MenuItem_Click_2" Foreground="Blue" FontSize="15" /> <MenuItem Header="_Window" FontSize="15" Foreground="Blue" /> <MenuItem Header="_Help" Click="MenuItem_Click_3" Foreground="Blue" FontSize="15" /> </Menu> </Grid> </Window>
Adding ListView Items: A ListView control hosts a collection of ListViewItem. The following code snippet adds items to a ListView control.
XAML CODE:
<ListView Margin="35,40,0,97" Name="ListView1" HorizontalAlignment="Left" Width="183"> <ListViewItem Content="C"></ListViewItem> <ListViewItem Content="C++"></ListViewItem> <ListViewItem Content="Java"></ListViewItem> <ListViewItem Content=".Net"></ListViewItem> <ListViewItem Content="Oracle"></ListViewItem> <ListViewItem Content="SilverLight"></ListViewItem> <ListViewItem Content="SharePoint"></ListViewItem> <ListViewItem Content="WPF"></ListViewItem> <ListViewItem Content="WCF"></ListViewItem> </ListView>
Output:
The button click event handler looks like following. On this button click, we find the index of the selected item and call ListView.Items.RemoveAt method as following.
Example:
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid Background="Beige"> <ListView Margin="8,47,0,80" Name="ListView1" HorizontalAlignment="Left" Width="127"> <ListViewItem Content="C" Background="LightPink" Foreground="Blue" ></ListViewItem> <ListViewItem Content="C++" Background="Violet" Foreground="Blue" ></ListViewItem> <ListViewItem Content="Java" Background="Silver" Foreground="Blue" ></ListViewItem> <ListViewItem Content=".Net" Background="CadetBlue" Foreground="Blue" ></ListViewItem> <ListViewItem Content="Oracle"></ListViewItem> <ListViewItem Content="SilverLight" Background="MediumSpringGreen" Foreground="Blue" ></ListViewItem> <ListViewItem Content="SharePoint" Background="DarkOrange" Foreground="Blue" ></ListViewItem> <ListViewItem Content="WPF" Background="Bisque" Foreground="Blue" ></ListViewItem> <ListViewItem Content="WCF" Background="Gold" Foreground="Blue" ></ListViewItem> </ListView> <TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0" Name="textBox1" VerticalAlignment="Top" Width="127" /> <Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="76" Click="button1_Click"> Add Item
</Button> <Button Height="23" Margin="140,47,0,0" Name="button2" VerticalAlignment="Top" Click="button2_Click" HorizontalAlignment="Left" Width="76">Delete Item</Button> </Grid> </Window>
background and foreground colors of a RadioButton. The following code sets the name, height, and width of a RadioButton control. The code also sets horizontal alignment to left and vertical alignment to top RadioButton Height="18" Margin="92,58,0,0" Name="radioButton1" > "VerticalAlignment="Top
XAML Code
<Window x:Class="WpfApplication7.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Crimson" Foreground="DarkBlue">BCA</RadioButton>
<Label Height="32" Margin="20,15,0,0" Name="label1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="171" FontSize="18" Foreground="DarkGreen">Plese Select Course</Label>
<Button Height="22.861" HorizontalAlignment="Right" Margin="0,53.139,18,0" Name="button1" VerticalAlignment="Top" Width="102" Click="button1_Click">Find Selected Item</Button>
</Grid> </Window>
.XAML.CS Code:
if (radioButton1.IsChecked == true) {
The Background and Foreground properties represent the background and foreground colors of a TabControl. The following code sets the name, height, and width of a RadioButton control. The code also sets horizontal alignment to left and vertical alignment to top <TabControl> <TabItem Header="Tab 1">Home</TabItem> <TabItem Header="Tab 2">Services</TabItem> <TabItem Header="Tab 3">Help</TabItem> <TabItem Header="Tab 4">Contact Us</TabItem> </TabControl> Example
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid> <TabControl Margin="19,21,0,0" Name="tabControl1" Height="267" VerticalAlignment="Top" HorizontalAlignment="Left" Width="256" IsTabStop="True"> <TabItem Header="Home" IsSelected="True" IsTabStop="False"> <Image ></Image>
</TabItem> <TabItem Header="Courses" IsSelected="True" Background="Goldenrod"> <TextBlock Background="Gray"> </TextBlock> </TabItem> <TabItem Header="Contact Us" IsSelected="True"> </TabItem> </TabControl> </Grid> </Window>
{ Console.WriteLine(PasswordBox1.Password); } Example
XAML Code<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid Background="AliceBlue"> <PasswordBox Height="23" Margin="85,91,0,0" Name="passwordBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="102" Password="gupta" /> <TextBox Height="23" Margin="85,56,113,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="102 " /> <Label Height="23" HorizontalAlignment="Left" Margin="17,56,0,0" Name="label1" VerticalAlignment="Top" Width="81">Username</Label> <Label Height="23" HorizontalAlignment="Left" Margin="17,91,0,0" Name="label2" VerticalAlignment="Top" Width="81">Password</Label> <Button Margin="85,130,0,0" Name="button1" Click="button1_click" HorizontalAlignment="Left" Width="85" Height="29" VerticalAlignment="Top">Login</Button>
</Grid> </Window>
Example:
XAML Code-
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid> <ScrollViewer HorizontalScrollBarVisibility="Visible" > <Grid Background="Aqua"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" MinWidth="60" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Label Margin="5" Grid.Column="0" Grid.Row="0">List of Student :</Label> <Label Margin="5" Grid.Column="0" Grid.Row="1">Address:</Label> <Label Margin="5" Grid.Column="0" Grid.Row="2">Comment:</Label> <RichTextBox Margin="5" Grid.Column="1" Grid.Row="0" MinWidth="100" /> <RichTextBox Margin="5" Grid.Column="1" Grid.Row="1" MinWidth="100" /> <RichTextBox Margin="5" Grid.Column="1" Grid.Row="2" MinWidth="100" /> </Grid> </ScrollViewer> </Grid> </Window>
Orientation: Gets to values, Horizontal or Vertical and specifies the orientation of slider Control. SmallChange: The amount that should be added or subtracted to or from Value attribute when user clicks on thumb. TickPlacement: Determines the place that ticks should be placed. Ticks: A required attribute and a set of double values for ticks. Value: ByDefault selected value for tick.
In Above Code The Width and Height property represent the width and the height of the control. The Name property represents name of the control, which is a unique identifier of the control. The Background property is used to set the background color of the control. The Minimum and Maximum properties represent the minimum and maximum values of the slider range. Example: Original Image:
XAML Code -
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid Background="LightCoral"> <Grid.RowDefinitions> <RowDefinition Height="200" /> <RowDefinition Height="30" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> </Grid.ColumnDefinitions> <Rectangle Width="250" HorizontalAlignment="Left" Margin="25,0,0,0" Height="200" VerticalAlignment="Top"> <Rectangle.Fill> <ImageBrush x:Name="imageBrush" ImageSource="D:\Documents and Settings\All Users\ Documents\My Pictures\Sample Pictures\Sunset.jpg"/> </Rectangle.Fill> </Rectangle>
<Slider Ticks="1, 2, 3, 4, 5, 6, 7, 8, 9, 10" Value="1" Delay="100" Interval="5" TickPlacement="BottomRight" Minimum="1" Maximum="10" AutoToolTipPlacement="BottomRight" ValueChanged="slider_ValueChanged" Grid.Row="1" Margin="25,0,0,0" HorizontalAlignment="Left"
.CS Code-
ImageBrush imageBrush = this.FindName("imageBrush") as ImageBrush; imageBrush.Viewbox = new Rect(0.3, 0.3, 1 / value, 1 / value); }
XAML Code-
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="400" /> </Grid.RowDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0" Stretch="Uniform" > <Rectangle.Fill> <!-- Here By passing the four value in ViewBox I will select a area from Real Image--> <ImageBrush ImageSource="D:\Documents and Settings\All Users\Documents\My Pictures \Sample Pictures\Sunset.jpg" Viewbox="0.2,0.3,0.1,0.5" /> </Rectangle.Fill> </Rectangle> </Grid> </Window>
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417"> <Grid Height="260" Width="302"> <GroupBox Name="settingsGroupBox" Header="Select Course" Margin="4,4,32,99" Background="Azure"> <StackPanel Height="141" Width="259" Background="Honeydew"> <StackPanel.Resources> <!-- Give the CheckBoxes some room to breath. --> <Style TargetType="CheckBox"> <Setter Property="Margin" Value="4" /> </Style> </StackPanel.Resources> <!-- Some CheckBoxes that represent settings. -->
<CheckBox Name="chk1" > .Net FrameWork With C# </CheckBox > <CheckBox Name="chk2"> java And Advanced Java </CheckBox> <CheckBox Name="chk3"> PHP,CAKE PHP,Smarty </CheckBox> <CheckBox Name="chk4" > Oracle,Sql Server </CheckBox> <!-- A separator between settings and buttons. --> <Line Margin="0,4" SnapsToDevicePixels="True" Stroke="{Binding ElementName=settingsGroupBox, Path=BorderBrush}" Stretch="Fill" X1="0" X2="1" /> <!-- The standard OK and Cancel Buttons. --> <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" > <StackPanel.Resources> <Style TargetType="Button"> <Setter Property="Margin" Value="4" /> <Setter Property="Width" Value="60" /> </Style> </StackPanel.Resources> <Button Click="Button_Click">_OK</Button> <Button Click="Button_Click_1">_Cancel</Button> </StackPanel> </StackPanel> </GroupBox> </Grid> </Window>
.CS Code-
MessageBox.Show("Your Selected chk1.Content); } else if (chk2.IsChecked == true) { MessageBox.Show("Your Selected chk2.Content); } else if (chk3.IsChecked == true) { MessageBox.Show("Your Selected chk3.Content); } else if (chk4.IsChecked == true) { MessageBox.Show("Your Selected chk4.Content); } }
Course is::" +
Course is::" +
Course is::" +
Course is::" +
Design Output:
can say TreeView control is a hierarchical structure to display the data. its look like a tree. it also contain root node, parent node and child node like tree. Features: Internet Explorer Favorites style view. Append a number to any node, allowing you to create an Outlook style folder list with message counts. Choose Font and Color on an item-by-item basis, and set the control's back color. Bolding of items Info Tip (multi-line tooltip) support with full control over Info Tip color Works with Microsoft or API ImageList. Item check boxes Full-Row select mode Single-Click expand mode Supports Two Images per item: one standard icon and a state icon. Disable Custom Draw for maximum speed Speed-optimized Clear method
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417" Loaded="Window_Loaded"> <Grid> <ListView> <TreeView Name="tree1" Background="LightCyan" > <TreeViewItem Header="File" Background="Red" FontSize="15"> </TreeViewItem> <TreeViewItem Header="Edit" Background="Red" FontSize="15" > </TreeViewItem> </TreeView> </ListView> </Grid> </Window>
private void Window_Loaded(object sender, RoutedEventArgs e) { Dictionary<string, List<string>> items = new Dictionary<string, List<string>>() { {"File",new List<string>() {"New","Open","ADD","Save","Save As","Close"}}, {"Edit",new List<string>() {"Undo","Cut","Copy","Paste","Delete"}}, }; foreach (TreeViewItem tv in tree1.Items) { foreach (string item in items[tv.Header.ToString()]) tv.Items.Add(item); } }
Designed Output-
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="370" Width="417" Loaded="Window_Loaded"> <Grid> <UniformGrid Margin="15,15,15,15" Name="uniformGrid1"> <Image Source="2.jpeg" Name="img1" ></Image> <Image Source="2.jpeg" Name="img2" ></Image> <Image Source="2.jpeg" Name="img3" ></Image> <Line></Line> <Line></Line>
<Line></Line> <Image Source="2.jpeg" Name="img4" ></Image> <Image Source="2.jpeg" Name="img5" ></Image> <Image Source="2.jpeg" Name="img6" ></Image> </UniformGrid> </Grid> </Window>
Output-
XAML Code-
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="336" Width="430" Loaded="Window_Loaded"> <Grid x:Name="LayoutRoot" Background="White" > <WrapPanel Orientation="Vertical" Margin="0,0,0,-39"> <Image Source="2.jpeg" Width="102" Height="57" /> <Ellipse Width="80" Height="80" Fill="Orange" /> <Image Source="2.jpeg" Width="100.224" Height="66" /> <Ellipse Width="40" Height="40" Fill="Green" /> <Ellipse Width="20" Height="20" Fill="Blue" />
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="312" Width="240" Loaded="Window_Loaded"> <Grid> <Image Margin="8,9,0,0" Name="image1" Stretch="Fill" Height="231" VerticalAlignment="Top" HorizontalAlignment="Left" Width="197" /> </Grid> </Window>
private void Window_Loaded(object sender, RoutedEventArgs e) { image1.Source = new BitmapImage(new Uri("2.jpeg", UriKind.Relative)); }
Designed Output-
<Window x:Class="WpfApplication7.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="312" Width="240" Loaded="Window_Loaded"> <Grid> <Rectangle Margin="14,40,0,0" Name="rectangle1" Stroke="Violet" StrokeThickness="9" Height="100" VerticalAlignment="Top" HorizontalAlignment="Left" Width="200" Fill="Pink" RadiusX="6" RadiusY="6" /> </Grid>
</Window>
in This code The Fill attributes fill a rectangle with a color. The following code fills a rectangle with pink color. By setting RadiusX and RadiusY attributes, you can also draw a rectangle with rounded corders. Output:
1. Button Control In WPF 2. Border Control In WPF 3. Label Control in WPF 4. TextBox Control In WPF 5. Canvas Control In WPF 6. CheckBox Control In WPF 7. ComboBox In WPF 8. Stack Panel Control 9. Expander Control 10. Ellipse Control 11. Grid Control 12. Progressbar Control 13. Menu Control 14. ListView Control 15. Adding Item in ListView Dynamically
16. Formatting And Style Of listView 17. Radiobutton Control 18. Tab Control 19. PasswordBox Control 20. Scroll Viewer Control 21. Slider Control 22. ViewBox Control 23. Separator Control 24. TreeView Control 25. UniformGrid Control 26. WrappedPanel Control 27. Image Control 28. Rectangle Control
Button Control In WPF Web Base
The Button element represents a WPF Button control in XAML. <Button></Button> The Width and Height attributes of the Button element represent the width and the height of a Button. The Content property of the Button element sets the text of a button. The x:Name attribute represents the name of the control, which is a unique identifier of a control.
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1"> <Grid> <Button Height="23" Margin="97,125,128,0" Name="button1" VerticalAlignment="Top">Button</Button> </Grid> </Page>
Name AllowDrop
Description Gets or sets a value indicating whether this element can be used as the target of a drag-anddrop operation. Gets a value that indicates whether at least one touch is captured to this element.
AreAnyTouchesCaptured
Gets a value that indicates whether at least one AreAnyTouchesCapturedWithin touch is captured to this element or to any child elements in its visual tree. AreAnyTouchesDirectlyOver Gets a value that indicates whether at least one touch is pressed over this element. Gets a value that indicates whether at least one touch is pressed over this element or any child elements in its visual tree. Gets or sets a cached representation of the UIElement. Gets or sets when the Click event occurs. Gets or sets the geometry used to define the outline of the contents of an element.
AreAnyTouchesOver
ClipToBounds
Gets or sets a value indicating whether to clip the content of this element (or content coming from the child elements of this element) to fit into the size of the containing element. Gets or sets the command to invoke when this button is pressed. Gets a collection of CommandBinding objects associated with this element. A CommandBinding enables command handling for this element, and declares the linkage between a command, its events, and the handlers attached by this element. Gets or sets the parameter to pass to the Command property. Gets or sets the element on which to raise the specified command. Gets or sets the content of a ContentControl. Gets or sets a composite string that specifies how to format the Content property if it is displayed as a string. Gets or sets the data template used to display the content of the ContentControl. Gets or sets a template selector that enables an application writer to provide custom templateselection logic. Gets the collection of input bindings associated with this element. Gets or sets the context for input used by this FrameworkElement.
Command
CommandBindings
CommandParameter
CommandTarget Content
ContentStringFormat
ContentTemplate
ContentTemplateSelector
InputBindings
InputScope
Adding a Button Click Event Handler The Click attribute of the Button element adds the click event handler. The following code adds the click event handler for a Button.
</Button>
<Page x:Class="WpfBrowserApplication2.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1"> <Grid> <Button Height="23" Margin="97,125,128,0" Name="button1" VerticalAlignment="Top" Click="button1_Click">Click me</Button> </Grid> </Page>
namespace WpfBrowserApplication2 { /// <summary> /// Interaction logic for Page1.xaml /// </summary> public partial class Page1 : Page { public Page1() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Please Dont Click Me Again"); } } }
Output :
BorderBrush="Green" CornerRadius="10" Background="LightGray" HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="250"> <Canvas Background="LightPink" > <Rectangle Canvas.Left="30" Canvas.Top="20" Height="200" Width="200" Stroke="Black" StrokeThickness="10" Fill="Red" /> </Canvas> </Border> </Grid> </Page>
<Label Margin="19,31,9.156,0" Name="label1" Height="28" VerticalAlignment="Top" Background="Teal" Foreground="Cornsilk" Grid.ColumnSpan="2">Label</Label> <Button Height="23" Margin="19,87,19.14,0" Name="button1" VerticalAlignment="Top" Click="button1_Click">Click Me</Button> <Button Grid.Column="1" Height="23" Margin="0,87,9.156,0" Name="button2" VerticalAlignment="Top" Click="button2_Click">Cancel</Button> Output:
Formatting a Label:
The BorderBrush property of the Label sets a brush to draw the border of a Label. You may use any brush to fill the border. The following code snippet uses a linear gradient brush to draw the border with a combination of red and blue color. <Label.BorderBrush> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" > <GradientStop Color="Blue" Offset="0" />
The Background and Foreground properties of the Label set the background and foreground colors of a Label. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a Label.
<Label.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" > <GradientStop Color="Blue" Offset="0.1" /> <GradientStop Color="Orange" Offset="0.25" /> <GradientStop Color="Green" Offset="0.75" /> <GradientStop Color="Black" Offset="1.0" /> </LinearGradientBrush> </Label.Background> <Label.Foreground> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" > <GradientStop Color="Orange" Offset="0.25" /> <GradientStop Color="Green" Offset="1.0" /> </LinearGradientBrush> </Label.Foreground> The new Label looks like Figure .
Setting Image as Background of a Label: To set an image as background of a Label, we can set an image as the Background of the Label. The following code snippet sets the background of a Label to an image.
<Label.Background> <ImageBrush ImageSource="Garden.jpg" /> </Label.Background>
Setting Background and Foreground Colors The Background and Foreground attributes set the background and foreground colors of text box.
<Page x:Class="WpfBrowserApplication2.Page4" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page4" Height="318" Width="391"> <Grid Background="LightCyan" Height="297" Width="343"> <TextBox Canvas.Top="50" Canvas.Left="20" Background="Coral" Margin="126,134,54,0" Height="28" VerticalAlignment="Top" Name="textBox1"> </TextBox> <Label Height="28" Margin="12,68,0,0" Name="label1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="78">Name:</Label> <TextBox Height="23" Margin="126,68,54,0" Name="textBox2" VerticalAlignment="Top" /> <TextBox Height="23" Margin="126,103,54,0" Name="textBox3" VerticalAlignment="Top" /> <Label Height="28" HorizontalAlignment="Left" Margin="12,103,0,0" Name="label2" VerticalAlignment="Top" Width="86"> Father Name:</Label> <Label HorizontalAlignment="Left" Margin="12,134,0,132" Name="label3" Width="56">City:</Label> <Button Height="22" Margin="97,0,128,91" Name="button1" VerticalAlignment="Bottom" Click="button1_Click">Button</Button> <Label Height="28" Margin="20,0,171,53" Name="label4" VerticalAlignment="Bottom">Label</Label> <Label Height="28" Margin="20,0,171,27" Name="label5" VerticalAlignment="Bottom">Label</Label> <Label Height="28" Margin="20,0,161,0" Name="label6" VerticalAlignment="Bottom">Label</Label> </Grid>
</Page>
private void button1_Click(object sender, RoutedEventArgs e) { label4.Content = "Welcome Mr." + textBox2.Text; label5.Content = "Father Name::" + textBox3.Text; label6.Content = "City::" + textBox1.Text; }
Wrapping and Scrolling Text The TextWrapping attributes sets the wrapping of text and VerticalScrollBarVisibility and HorizontalScrollBarVisibility sets the vertical and horizontal scroll bars visible.
The IsReadOnly property of the TextBox sets the text box read only. By default, it is false.
IsReadOnly="True" Restricting Input Text MaxHeight, MaxWidth, MaxLines, and MaxLength attributes of text box restricts the maximum height, maximum width, maximum number of lines, and maximum length of the text box. Similarly MinHeight, MinWidht, MinLines, and MinLength restricts the minimum height, minimum width, minimum number of lines, and minimum length of the text box. Setting IsReadOnly attribute to true makes the text box non editable. Spell Checking : Spell checking can be enabled on the text box control by setting the SpellCheck.IsEnabled to true. When you set the SpellChek.IsEnabed to true then text box control will automatically detect the wrong word and underlined these words with red line as see in the Image 2, the similar kind of behavior you have seen while typing in the Microsoft Word.
Now as you have experience it in Microsoft Word that you can right click on the red underlined word and it will give you suggestions of the word in list box. From the list of the suggested option for the wrong word you can choose the correct word.
In the Image you can see that I have entered wrong words like wrog entere and TextBox. You can place mouse on any of the word and select the correct word from the suggestion which are appears by right clicking on the word It Has A Real Undo Stack: Have you ever written code that manually called the Undo method of the TextBox control, and been disappointed with the results. Spoilers follow for those who have not tried this: it only keeps track of the last state of the text. Since the advent of Adobe Photoshop* in the late middle ages, people have grown accustomed to programs being able to undo as many actions as they have done. Well with the WPF TextBox control that functionality is built-in. If you find implementing a custom Undo Stack fun, then cling tightly to the WinForms TextBox, if you would rather forego that task so that you can focus on a more important problems continue reading. What code do you need to get it working? Check it out: wpfTextBox.IsUndoEnabled = true; wpfTextBox.UndoLimit = 1024; Oh yeah, and whereas the System.Windows.Forms.TextBox control has an Undo method, the WPF equivalent supports this beautiful couple: wpfTextBox.Undo(); wpfTextBox.Redo(); Just be sure to never include those two lines of code one right after another like that.
XAML Code: <Canvas Name="cnvMain" Background="Red" Height="300" Width="300"> </Canvas> C# Code: Canvas cnvMain = New Canvas(); cnvMain.Height = 300; cnvMain.Width = 300; cnvMain.Background = New SolidColorBrush(Colors.Red); Since, page does not have children property, add above Canvas in the page using following Code. pgMain.Content = cnvMain; If you have used canvas as a container control, all the controls those are added as child controls of Canvas should have main two properties. 1) Canvas.Top 2) Canvas.Left These two properties are used for the proper positioning of the controls which are inside the Canvas. These properties (Left and Top) are related to the parent canvas for any control. An example will help you understand this easily. If you want to add a TextBlock inside the canvas, you can add it using Following Code. XAML Code: <Canvas Name="cnvMain" Background="Red" Height="300" Width="300"> <TextBlock Name="tbTest" Height="40" Width="100" Text="Hello"> </TextBlock> </Canvas> C# Code: TextBlock tbTest = new TextBlock(); tbTest.Height = 40; tbTest.Width = 100; tbTest.Text = "Hello"; cnvMain.Children.Add(tbTest); Check output of the above code. You will see that TextBlock having Text "Hello" Would appear in the Top Left Corner of the Canvas. Now, if you want to set the position of this control inside the Canvas, you can use Canvas.Left and Canvas.Top property in the XAML code. If you want to set these properties runtime then, you must use following piece of code for that,
tbTest.SetValue(Canvas.LeftProperty, 30.0); tbTest.SetValue(Canvas.TopProperty, 100.0); These properties are Attached or dependent properties, means those are dependent upon their parent control. To set such properties we should use, SetValue() function. These are some of the basic properties. You can use properties which are useful for you. One very important feature provided by Visual Studio is intellisence. Use it and explore the properties related to the controls. Example:
<Page x:Class="WpfBrowserApplication2.CANVAS" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="CANVAS"> <Grid> <Grid> <Border Background="Plum" CornerRadius="20" BorderBrush="Yellow" BorderThickness="2"> <Canvas> <TextBox Background="PaleGreen" Grid.Row="0" Grid.Column="0" Canvas.Top="10" Canvas.Left="10" Height="30" FontSize="15" Foreground="white"> Canvas Layout 1 </TextBox> <TextBox Background="AliceBlue" Grid.Row="1" Grid.Column="0" Canvas.Top="50" Canvas.Left="120" Height="30" FontSize="15" Foreground="white"> Canvas Layout 2 </TextBox> <TextBox Background="White" Grid.Row="1" Grid.Column="1" Canvas.Top="115" Canvas.Right="70" Height="30" FontSize="15" Foreground="Red"> Canvas Layout 3 </TextBox> <TextBox Background="Green" Grid.Row="1" Grid.Column="1" Canvas.Bottom="50" Canvas.Right="120" Height="30" FontSize="15" Foreground="white"> Canvas Layout 4 </TextBox> <TextBox Background="OrangeRed" Grid.Row="0" Grid.Column="1" Canvas.Bottom="10" Canvas.Right="10" Height="30" FontSize="15" Foreground="white"> Canvas Layout 5
Output:
Properties: With the following tag I created the CheckBox, in which Height is height of the checkbox, Name is the nameof the checkbox. Background the the color of the box, Borderbrush is the color of the border, Forground is the color of the text. <CheckBox Height="15" Margin="16,17,122,0" Name="chkA2zdotnet" VerticalAlignment="Top" Background="Cyan" BorderBrush="Blue" Foreground="Chocolate" FlowDirection="LeftToRight" HorizontalContentAlignment="Left" VerticalContentAlignment="Center">A2ZDotnet.com</CheckBox> The Content attribute represents the text of a CheckBox. The Name attribute represents the name of the control, which is a unique identifier of a control. The Foreground attribute defines the foreground color of the text of the CheckBox. The Content attribute defines the text of the CheckBox. FontFamily, FontStyle, FontWeight, FontSize and FontStretch are font related attribute The IsChecked property represents the state of the CheckBox control. The IsThreeState property represents whether the CheckBox has two or three states. Three states are checked, unchecked, or indeterminate. Example:
<Grid> <StackPanel Background="BlueViolet" Height="104" VerticalAlignment="Top"> <CheckBox Name="cbxOne" IsChecked="False" Foreground="White" FontSize="16 " Checked="cbxOne_Checked">Check Box One</CheckBox> <CheckBox Name="cbxTwo" IsChecked="True" Foreground="White" FontSize="16">Check Box Two</CheckBox> <CheckBox Name="cbxThree" IsChecked="True" Foreground="White" FontSize="16" > Check Box Three</CheckBox> <CheckBox Name="cbxFour" IsChecked="True" Foreground="White" FontSize="16" Checked="cbxFour_Checked">Check Box Four</CheckBox> </StackPanel> <Button HorizontalAlignment="Left" Margin="10,112,0,0" Name="button1" Width="75" Height="23" VerticalAlignment="Top" Click="button1_Click_1">Button</Button> </Grid> </Page>
XAML.CS CODE:
sb.AppendLine("Box three is Checked"); else sb.AppendLine("Box Three is Unchecked"); if ((bool)cbxFour.IsChecked) sb.AppendLine("Box four is Checked"); else sb.AppendLine("Box four is Unchecked");
MessageBox.Show(sb.ToString(), "CheckBox");
<ComboBoxItem Background="Tomato" BorderBrush="Cyan" >Infosis</ComboBoxItem> <ComboBoxItem Background="SpringGreen" BorderBrush="Bisque">Microsoft</ComboBoxItem> <ComboBoxItem Background="SteelBlue" BorderBrush="Brown">L & T Infotech</ComboBoxItem> <ComboBoxItem Background="Violet" BorderBrush="Chartreuse">R4R tech soft</ComboBoxItem> <ComboBoxItem Background="YellowGreen" BorderBrush="Chocolate">NIIT</ComboBoxItem> <ComboBoxItem Background="SteelBlue" BorderBrush="DimGray">CSC</ComboBoxItem> </ComboBox> comboBox2.IsEnabled = true; comboBox2.Items.Clear(); if (comboBox1.SelectedIndex == 0) { comboBox2.Items.Add("Interview Question"); comboBox2.Items.Add("Java Interview Question"); comboBox2.Items.Add("PHP Interview Question"); comboBox2.Items.Add("PlaceMent paper"); } else if (comboBox1.SelectedIndex == 1) { comboBox2.Items.Add("SAP"); comboBox2.Items.Add("ERP"); comboBox2.Items.Add("Networking"); comboBox2.Items.Add("C/C++"); } else { comboBox2.Items.Add("Networking"); comboBox2.Items.Add("C/C++"); } Adding and Deleting ComboBox Items at Run-time: Output:
.CS Code:
private void button1_Click(object sender, RoutedEventArgs e) { comboBox1.Items.Add(textBox1.Text); } private void button2_Click(object sender, RoutedEventArgs e) { comboBox1.Items.RemoveAt(comboBox1.Items.IndexOf(comboBox1.Selecte dItem)); }
The StackPanel, as the name implies, arranges content either horizontally or vertically. Vertical is the default, but this can be changed using the Orientation property. Content is automatically stretched based on the orientation (see screenshot below), and this can be controlled by changing the HorizontalAlignment or VerticalAlignment properties.
<StackPanel Width="Auto" Height="Auto"> <Button Content="Button" /> <Button Content="Button" HorizontalAlignment="Left" /> <Button Content="Button" HorizontalAlignment="Center" /> <Button Content="Button" HorizontalAlignment="Right" /> </StackPanel>
<StackPanel Width="Auto" Height="Auto" Orientation="Horizontal"> <Button Content="Button" /> <Button Content="Button" VerticalAlignment="Top" /> <Button Content="Button" VerticalAlignment="Center" /> <Button Content="Button" VerticalAlignment="Bottom" /> </StackPanel>
The Expander Control is like GroupBox. We will use StackPanel control and RadioButton in this example. An Expander control provides a way to provide content in an expandable area that resembles a window and includes a header. The Expander Control is the simple control. Output:
<Page x:Class="WpfBrowserApplication3.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1"> <Grid Width="276" Height="283"> <StackPanel Background="DarkSalmon" Margin="0,0,117,0"> <Expander Header="Friends List"> <StackPanel> <RadioButton GroupName="One" IsChecked="True">Option 1</RadioButton> <RadioButton GroupName="One" IsChecked = "False">Option 2</RadioButton>
</StackPanel> </Expander> <Expander Header="Girls Friend List"> <StackPanel> <RadioButton GroupName="One" IsChecked="True"> <Hyperlink NavigateUri="http://www.google.com" >Radhika Awasthi </Hyperlink></RadioButton> <RadioButton GroupName="One" IsChecked="True"> <Hyperlink NavigateUri="http://www.google.com" >Archana Gupta </Hyperlink></RadioButton> <RadioButton GroupName="One" IsChecked="True"> <Hyperlink NavigateUri="http://www.google.com" > bharti Pathak</Hyperlink> </RadioButton> <RadioButton GroupName="One" IsChecked="True"> <Hyperlink NavigateUri="http://www.google.com" >Anshu Rana</Hyperlink> </RadioButton> </StackPanel> </Expander> <Expander Header="College Friends"> <StackPanel> <RadioButton GroupName="One" IsChecked="True"> <Hyperlink NavigateUri="http://www.google.com" >kamal Mishra</Hyperlink></RadioButton> <RadioButton GroupName="One" IsChecked="True"> <Hyperlink NavigateUri="http://www.google.com" >Dinesh Gupta</Hyperlink></RadioButton> <RadioButton GroupName="One" IsChecked="True"> <Hyperlink NavigateUri="http://www.google.com" >Aditya </Hyperlink> </RadioButton>
</StackPanel> </Expander>
The Expander can only contain one thing: its contents. If we want to add multiple items, we have to put something inside the Expander that can hold some number of other things. The StackPanel, as with all the other layout panels, can hold multiple items, so we can add another StackPanel. The StackPanel itself solves some specific layout scenarios, but its quite flexible. It could be used, for example, to build a calculator. You should be able to see how this would work one vertical StackPanel containing a number of vertical StackPanels for the buttons. It wouldnt be easy, but it would be possible. In the next section, we will talk about the DockPanel. The DockPanel can be used to solve some of the same problems but in a different way. As with the StackPanel, the DockPanel, while flexible, is designed to handle a different set of scenarios.
<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Ellipse Fill="Blue" Stroke="Red" Canvas.Left="100" Canvas.Top="10" Width="160" Height="90"> <Ellipse.RenderTransform> <RotateTransform Angle="45"/> </Ellipse.RenderTransform> </Ellipse> </Canvas>
Output:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="75" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions>
A Grid has RowDefinitions and ColumnDefinitions that specify the height (specific to the row), the width (specific to the column), and possibly other dimensional aspects. Normally, you would expect to see a combination of row/cell or row/column objects to lay out the grid; however, WPF works differently. Each control has a Grid.Row and Grid.Column, which specifies the row/column to render in. The resize behaviour of the controls is defined by the HorizontalAlignment and VerticalAlignment properties who define the anchors. The distance between the anchor and the grid line is specified by the margin of the control..
Define Rows and Columns in Grid: The grid has one row and column by default. To create additional rows and columns, you have to add RowDefinition items to the RowDefinitions collection and ColumnDefinition items to the ColumnDefinitions collection. The following example shows a grid with three rows and two columns. The size can be specified as an absolute amount of logical units, as a percentage value or automatically. Fixed Fixed size of logical units (1/96 inch) Auto Takes as much space as needed by the contained control Star (*) Takes as much space as available, percentally divided over all star-sized columns. Star-sizes are like percentages, except that the sum of all star columns does not have to be 100%. Remember that star-sizing does not work if the grid size is calculated based on its content. How to Add Control To Grid: To add controls to the grid layout panel just put the declaration between the opening and closing tags of the Grid. Keep in mind that the row- and columndefinitions must precced any definition of child controls. The grid layout panel provides the two attached properties Grid.Column and Grid.Row to define the location of the control..
<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> <RowDefinition Height="28" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Name:"/> <Label Grid.Row="1" Grid.Column="0" Content="E-Mail:"/> <Label Grid.Row="2" Grid.Column="0" Content="Comment:"/> <TextBox Grid.Column="1" Grid.Row="0" Margin="3" /> <TextBox Grid.Column="1" Grid.Row="1" Margin="3" /> <TextBox Grid.Column="1" Grid.Row="2" Margin="3" /> <Button Grid.Column="1" Grid.Row="3" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="Send" /> </Grid>
.XAML CODE:
<Page x:Class="WpfBrowserApplication5.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1"> <Grid Height="284" Background="Coral" Width="354"> <Grid.RowDefinitions> <RowDefinition Height="Auto" MinHeight="25" /> <RowDefinition Height="Auto" MinHeight="27" /> <RowDefinition Height="174*" /> <RowDefinition Height="31.447*" />
<RowDefinition Height="28" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" MinWidth="61" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Grid.Row="0" Grid.Column="0" Content="Name:"/> <Label Grid.Row="1" Grid.Column="0" Content="E-Mail:"/> <Label Grid.Row="2" Content="Comment:" Grid.RowSpan="2" /> <TextBox Grid.Column="1" Grid.Row="0" Margin="3" /> <TextBox Grid.Column="1" Grid.Row="1" Margin="3" /> <TextBox Grid.Column="1" Grid.Row="2" Margin="3" Grid.RowSpan="2" /> <Button Grid.Column="1" Grid.Row="4" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="Discard " /> <Button Grid.Column="1" Grid.Row="1" HorizontalAlignment="Right" MinWidth="80" Margin="0,5.999,-79.547,0" Content="Send" Height="21.277" Grid.RowSpan="2" VerticalAlignment="Top" Width="80" /> </Grid> </Page>
ProgressBar Control in WPF WEB BASED: The ProgressBar tag in XAML represents a WPF ProgressBar control. <ProgressBar></ProgressBar> The Width and Height properties represent the width and the height of a ProgressBar. The Name property represents the name of the control, which is a unique identifier of a control. The Margin property tells the location of a ProgressBar on the parent control. The HorizontalAlignment and VerticalAlignment properties are used to set horizontal and vertical alignments. Syntax of ProgressBar:
<p
Setting up ProgressBar Value : The Value property of ProgressBar sets up the current value of a ProgressBar control. In the following code, I set the Value property to 60 . <ProgressBar Margin="10,10,0,13" Name="PBar" HorizontalAlignment="Left" VerticalAlignment="Top" Width="300" Height="30" Value="60" > </ProgressBar>
Next up, we are going to add an animation that will automatically fill and unfill the progress bar. So we are going to add a Trigger that fires after our progress bar has loaded. That trigger will fire a storyboard with an animation. The animation will be set to increase the ProgressBar.Value from 0 to 100 over the course of 1 second. We set the autoreverse property to true, to allow the animation to go forwards and backwards. The xaml to do this would be: .XAML Code:
<Page x:Class="WpfBrowserApplication5.Page4"
</ProgressBar.RenderTransform>
<DoubleAnimation
</Storyboard> </BeginStoryboard>
</EventTrigger>
</ProgressBar.Triggers> </ProgressBar>
</Grid> </Page>
After Rotation:
</p
This Tag Creates a Menu Control. Important Properties: Name --> Defines the name of the menu. Height --> Defines the Height of the menu Width --> Defines the width of the menu Margin --> Defines the position of the menu Background--> Defines backcolor of the menu HorizontalAlignment --> Defines the horizontal alignment of the menu inside the parent control. HorizontalContentAlignment --> Defines the horizontal alignment for the menu content. VerticalAlignment --> Defines the vertical alignment of the menu inside the parent control. VerticalContentAlignment --> Defines the content alignment for the menu content. ToolTip --> defines the tooltip for the menu.
A MenuItem can have other MenuItem tags within it as child/sub menus and can go up to several levels. The following code adds three children menu items to first menu item.
<MenuItem Header="_File"> <MenuItem Header="_Open" IsCheckable="true"/> <MenuItem Header="_Close" IsCheckable="true"/> <MenuItem Header="_Save" IsCheckable="true"/> </MenuItem>
Adding Tooltips to Menus: The MenuItem.ToolTip tag adds a tooltip to a menu item. The following code adds a tooltip to the Open menu item.
</MenuItem>
Adding an Event Trigger to a MenuItem: The Click event is used to add the menu item click event handler. The following code adds a click event handler for a menu item. <MenuItem IsCheckable="true" Header="_Open" Click="MenuItem_Click"> The event handler is defined like following in the code behind. I added a message box when the menu item is clicked. private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Menu item clicked"); } .XAML Code Of Menu Control:
<Page x:Class="WpfBrowserApplication5.Page2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page2"> <Grid> <Menu IsMainMenu="True" Background="LightCyan"> <MenuItem Header="_File" Click="MenuItem_Click" FontSize="15" Foreground="Blue"> <MenuItem Header="_Open" IsCheckable="true" Click="MenuItem_Click"> <MenuItem.ToolTip> <ToolTip> Open a file. </ToolTip> </MenuItem.ToolTip> </MenuItem> <MenuItem Header="_Close" IsCheckable="true"/> <MenuItem Header="_Save" IsCheckable="true"/> </MenuItem>
<MenuItem FontSize="15" /> <MenuItem FontSize="15" /> <MenuItem <MenuItem FontSize="15" /> </Menu> </Grid> </Page>
Header="_Edit" Click="MenuItem_Click_1" Foreground="Blue" Header="_View" Click="MenuItem_Click_2" Foreground="Blue" Header="_Window" FontSize="15" Foreground="Blue" /> Header="_Help" Click="MenuItem_Click_3" Foreground="Blue"
Output:
Syntax: <ListView Margin="10,10,0,13" Name="ListView1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200" /> Adding ListView Items: A ListView control hosts a collection of ListViewItem. The following code snippet adds items to a ListView control. XAML CODE:
<ListView Margin="35,40,0,97" Name="ListView1" HorizontalAlignment="Left" Width="183"> <ListViewItem Content="C"></ListViewItem> <ListViewItem Content="C++"></ListViewItem> <ListViewItem Content="Java"></ListViewItem> <ListViewItem Content=".Net"></ListViewItem> <ListViewItem Content="Oracle"></ListViewItem> <ListViewItem Content="SilverLight"></ListViewItem> <ListViewItem Content="SharePoint"></ListViewItem> <ListViewItem Content="WPF"></ListViewItem> <ListViewItem Content="WCF"></ListViewItem> </ListView>
Output:
Example:
Deleting ListView Items: The button click event handler looks like following. On this button click, we find the index of the selected item and call ListView.Items.RemoveAt method as following. private void button2_Click(object sender, RoutedEventArgs e) { ListView1.Items.RemoveAt( ListView1.Items.IndexOf(ListView1.SelectedItem)); } Example: After press Delete Button it Will Delete From ListBox:
Example:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page4" Loaded="Page_Loaded"> <Grid Background="Beige"> <ListView Margin="8,47,0,80" Name="ListView1" HorizontalAlignment="Left" Width="127"> <ListViewItem Content="C" Background="LightPink" Foreground="Blue" ></ListViewItem> <ListViewItem Content="C++" Background="Violet" Foreground="Blue" ></ListViewItem> <ListViewItem Content="Java" Background="Silver" Foreground="Blue" ></ListViewItem> <ListViewItem Content=".Net" Background="CadetBlue" Foreground="Blue" ></ListViewItem> <ListViewItem Content="Oracle"></ListViewItem> <ListViewItem Content="SilverLight" Background="MediumSpringGreen" Foreground="Blue" > </ListViewItem> <ListViewItem Content="SharePoint" Background="DarkOrange" Foreground="Blue" > </ListViewItem> <ListViewItem Content="WPF" Background="Bisque" Foreground="Blue" ></ListViewItem> ListViewItem Content="WCF" Background="Gold" Foreground="Blue" ></ListViewItem> </ListView> <TextBox Height="23" HorizontalAlignment="Left" Margin="8,14,0,0" Name="textBox1" VerticalAlignment="Top" Width="127" /> <Button Height="23" Margin="140,14,0,0" Name="button1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="76" Click="button1_Click"> Add Item </Button> <Button Height="23" Margin="140,47,0,0" Name="button2" VerticalAlignment="Top" Click="button2_Click" HorizontalAlignment="Left" Width="76">Delete Item</Button> </Grid> </Page> Example: Design Output:
<RadioButton Height="18" Margin="92,58,0,0" Name="radioButton1" VerticalAlignment="Top" <HorizontalAlignment="Left" Width="82">RadioButton</RadioButton In the following tag I create the RadioButton in which Height is height of the RadioButton,
Name is the nameof the RadioButton, text in the between the RadioButton tag is the centent visibile to user. The Background and Foreground properties represent the background and foreground colors of a RadioButton. The following code sets the name, height, and width of a RadioButton control. The code also sets horizontal alignment to left and vertical alignment to top <RadioButton Height="18" Margin="92,58,0,0" Name="radioButton1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="82">RadioButton</RadioButton> Example:
.XAML Code:
<Page x:Class="WpfBrowserApplication5.Page5" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page5" Background="LightGoldenrodYellow" Height="182" Width="275" Loaded="Page_Loaded"> <Grid> <RadioButton Height="18" Margin="92,58,0,0" Name="radioButton1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="82" Background="Crimson" Foreground="DarkBlue">M.Tech</RadioButton> <RadioButton Height="17" Margin="92,85,126,0" Name="radioButton2"
VerticalAlignment="Top" Checked="radioButton2_Checked" Background="Crimson" Foreground="DarkBlue">B.Tech</RadioButton> <RadioButton Height="17" Margin="92,115,126,0" Name="radioButton3" VerticalAlignment="Top" Checked="radioButton3_Checked" Background="Crimson" Foreground="DarkBlue">MCA</RadioButton> <RadioButton Height="20" Margin="92,141,126,0" Name="radioButton4" VerticalAlignment="Top" Background="Crimson" Foreground="DarkBlue">BCA</RadioButton> <Label Height="32" Margin="20,15,0,0" Name="label1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="171" FontSize="18" Foreground="DarkGreen">Plese Select Course</Label> <Button Height="22.861" HorizontalAlignment="Right" Margin="0,53.139,18,0" Name="button1" VerticalAlignment="Top" Width="102" Click="button1_Click">Find Selected Item</Button> </Grid> </Page>
.XAML.CS Code:
private void button1_Click(object sender, RoutedEventArgs e) { if (radioButton1.IsChecked == true) { MessageBox.Show("Your Selected Course is " + radioButton1.Content); } else if (radioButton2.IsChecked == true) { MessageBox.Show("Your Selected Course is " + radioButton2.Content); } else if (radioButton3.IsChecked == true) { MessageBox.Show("Your Selected Course is " + radioButton3.Content); } else if (radioButton4.IsChecked == true) { MessageBox.Show("Your Selected Course is " + radioButton4.Content); } }
is a Boolean value that specifies if a tab is selected. Bassically only one tab can be selected at a time otherwise the first tab in list will be selected. Two elements play main roles in Creating a tab control: TabControl and TabItem. TabControl is the container of one or more TabItem elements. Syntax of TabControl: <TabControl Margin="41,46,0,0" Name="tabControl1" Height="100" VerticalAlignment="Top" HorizontalAlignment="Left" Width="200" /> In the following tag I create the TabControl in which Height is height of the TabControl, Name is the name of the TabControl, The Background and Foreground properties represent the background and foreground colors of a TabControl. The following code sets the name, height, and width of a RadioButton control. The code also sets horizontal alignment to left and vertical alignment to top <TabControl> <TabItem Header="Tab <TabItem Header="Tab <TabItem Header="Tab <TabItem Header="Tab </TabControl> Example: 1">Home</TabItem> 2">Services</TabItem> 3">Help</TabItem> 4">Contact Us</TabItem>
.XAML CODE:
<Page x:Class="WpfBrowserApplication5.Page6" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page6" Height="493" Width="345" Loaded="Page_Loaded"> <Grid> <TabControl Margin="19,21,0,0" Name="tabControl1" Height="267" VerticalAlignment="Top" HorizontalAlignment="Left" Width="256" IsTabStop="True"> <TabItem Header="Home" IsSelected="True" IsTabStop="False"> <Image Source="images.jpeg" ImageFailed="Image_ImageFailed"></Image> </TabItem> <TabItem Header="Courses" IsSelected="True" Background="Goldenrod"> <TextBlock Background="Gray"> <Image Source="11.jpg" ></Image><LineBreak></LineBreak> <Label Name="label1" Content=" Username" FontSize="15"></Label>
<TextBox Name="textbox1" Text="" Height="35" Width="120" > </TextBox><LineBreak></LineBreak> <RadioButton GroupName="a" FontSize="16" Name="radiobutton1">MCA</RadioButton> <LineBreak></LineBreak> <RadioButton GroupName="a" FontSize="16" Name="radiobutton2">B.Tech. </RadioButton> <LineBreak></LineBreak> <RadioButton GroupName="a" FontSize="16" Name="radiobutton3">M.Tech. </RadioButton> <LineBreak></LineBreak> <RadioButton GroupName="a" FontSize="16" Name="radiobutton4">BCA </RadioButton> <LineBreak></LineBreak> <Button Name="button1" Click="button1_Click" > submit </Button> </TextBlock> </TabItem> <TabItem Header="Contact Us" IsSelected="True"> <Image Source="user-admin.png" </TabItem> </TabControl> </Grid> </Page> />
.XAML.CS CODE:
if (radiobutton1.IsChecked == true) { MessageBox.Show("Hi!!!! " + textbox1.Text + " " + "You Selected "+
radiobutton1.Content); } else if(radiobutton2.IsChecked == true) MessageBox.Show("Hi:: " + textbox1.Text + "" + "Your Selected Course is:::" + radiobutton2.Content); } else if (radiobutton3.IsChecked == true) { MessageBox.Show("Hi:: " + textbox1.Text + "" + "Your Selected Course is->" + radiobutton3.Content); {
} else if (radiobutton4.IsChecked == true) { MessageBox.Show("Hi:: " + textbox1.Text + "" + "Your Selected Course is->" + radiobutton4.Content); } }
Properties: Password property contains the password in the passwordbox and PasswordChar is the masking character for the password. Following tag create the Password Box control with the masking character as * and maximum password length of 50 characters. The MaxLength property is used to get and set the maximum number of characters you can enter in a PasswordBox. <PasswordBox Height="23" Margin="40,74,118,0" Name="PasswordBox1" VerticalAlignment="Top" PasswordChar="*" MaxLength="50" /> Events: PasswordChanged event is main event of the control and is raised when password property has been changed. To handle the event add the PasswordChanged="Password1_OnPasswordChanged" in the xaml and write the handler as protected void Password1_OnPasswordChanged(object sender, RoutedEventArgs e) { Console.WriteLine(PasswordBox1.Password); } .XAML CODE :
<Page x:Class="WpfBrowserApplication5.Page3" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page3"> <Grid Background="AliceBlue"> <PasswordBox Height="23" Margin="85,91,0,0" Name="passwordBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="102" Password="gupta" /> <TextBox Height="23" Margin="85,56,113,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="102 " /> <Label Height="23" HorizontalAlignment="Left" Margin="17,56,0,0" Name="label1" VerticalAlignment="Top" Width="81">Username</Label> <Label Height="23" HorizontalAlignment="Left" Margin="17,91,0,0" Name="label2" VerticalAlignment="Top" Width="81">Password</Label> <Button Margin="81,150,144,127" Name="button1" Click="button1_Click">Button</Button> </Grid> </Page>
Output:
Syntax of ScrollViewer:
.XAML.CS CODE:
<Page x:Class="WpfBrowserApplication5.Page10" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page10"> <Grid> <ScrollViewer HorizontalScrollBarVisibility="Visible" > <Grid Background="Aqua"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" MinWidth="60" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Label Margin="5" Grid.Column="0" Grid.Row="0">List of Student :</Label> <Label Margin="5" Grid.Column="0" Grid.Row="1">Address:</Label> <Label Margin="5" Grid.Column="0" Grid.Row="2">Comment:</Label> <RichTextBox Margin="5" Grid.Column="1" Grid.Row="0" MinWidth="100" /> <RichTextBox Margin="5" Grid.Column="1" Grid.Row="1" MinWidth="100" /> <RichTextBox Margin="5" Grid.Column="1" Grid.Row="2" MinWidth="100" /> </Grid> </ScrollViewer> </Grid> </Page>
Maximum: Maximum value for slider. Minimum: Minimum value for slider. Orientation: Gets to values, Horizontal or Vertical and specifies the orientation of slider Control. SmallChange: The amount that should be added or subtracted to or from Value attribute when user clicks on thumb. TickPlacement: Determines the place that ticks should be placed. Ticks: A required attribute and a set of double values for ticks. Value: ByDefault selected value for tick.
<Slider Name="Slider1" Width="200" Height="20" Background="Gray" Maximum="80" Minimum="0"> </Slider> In Above Code The Width and Height property represent the width and the height of the control. The Name property represents name of the control, which is a unique identifier of the control. The Background property is used to set the background color of the control. The Minimum and Maximum properties represent the minimum and maximum values of the slider range. Example: Original Image:
<Page x:Class="WpfBrowserApplication5.Page8" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation " xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page8"> <Grid Background="LightCoral"> <Grid.RowDefinitions> <RowDefinition Height="200" /> <RowDefinition Height="30" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> </Grid.ColumnDefinitions> <Rectangle Width="250" HorizontalAlignment="Left" Margin="25,0,0,0" Height="200" VerticalAlignment="Top"> <Rectangle.Fill> <ImageBrush x:Name="imageBrush" ImageSource="Images.jpeg" /> </Rectangle.Fill> </Rectangle>
Maximum="10" AutoToolTipPlacement="BottomRight" ValueChanged="slider_ValueChanged" Grid.Row="1" Margin="25,0,0,0" HorizontalAlignment="Left" Width="250" Height="30" VerticalAlignment="Top"> </Slider> </Grid> </Page>
.CS CODE:
private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { double value = e.NewValue; ImageBrush imageBrush = this.FindName("imageBrush") as ImageBrush; imageBrush.Viewbox = new Rect(0.3, 0.3, 1 / value, 1 / value); }
.XAML CODE:
<Page x:Class="WpfBrowserApplication5.Page12" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page12" Width="344"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="400" /> </Grid.RowDefinitions>
<Rectangle Grid.Row="0" Grid.Column="0"> <Rectangle.Fill> <!-- Here By passing the four value in ViewBox I will select a area from Real Image--> <ImageBrush ImageSource="main_flash.jpg" Viewbox="0.4,0.12,0.7,0.8" /> </Rectangle.Fill> </Rectangle> </Grid> </Page>
<Page x:Class="WpfBrowserApplication5.Page16" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page16"> <Grid Height="260" Width="302"> <GroupBox Name="settingsGroupBox" Header="Select Course" Margin="4,4,32,99" Background="Azure"> <StackPanel Height="141" Width="259" Background="Honeydew"> <StackPanel.Resources> <!-- Give the CheckBoxes some room to breath. --> <Style TargetType="CheckBox"> <Setter Property="Margin" Value="4" /> </Style> </StackPanel.Resources> <!-- Some CheckBoxes that represent settings. --> <CheckBox Name="chk1" > .Net FrameWork With C# </CheckBox > <CheckBox Name="chk2"> java And Advanced Java </CheckBox> <CheckBox Name="chk3"> PHP,CAKE PHP,Smarty </CheckBox> <CheckBox Name="chk4" >
Oracle,Sql Server </CheckBox> <!-- A separator between settings and buttons. --> <Line Margin="0,4" SnapsToDevicePixels="True" Stroke="{Binding ElementName=settingsGroupBox, Path=BorderBrush}" Stretch="Fill" X1="0" X2="1" /> <!-- The standard OK and Cancel Buttons. --> <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" > <StackPanel.Resources> <Style TargetType="Button"> <Setter Property="Margin" Value="4" /> <Setter Property="Width" Value="60" /> </Style> </StackPanel.Resources> <Button Click="Button_Click">_OK</Button> <Button Click="Button_Click_1">_Cancel</Button> </StackPanel> </StackPanel> </GroupBox> </Grid> </Page>
.XAML.CS CODE:
private void Button_Click(object sender, RoutedEventArgs e) { if (chk1.IsChecked == true) { MessageBox.Show("Your Selected Course is::" + chk1.Content); } else if(chk2.IsChecked == true) { MessageBox.Show("Your Selected Course is::" + chk2.Content); } else if (chk3.IsChecked == true) { MessageBox.Show("Your Selected Course is::" + chk3.Content);
Design Output:
<Page x:Class="WpfBrowserApplication5.Page13" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page13" Loaded="Page_Loaded"> <Grid> <ListView> <TreeView Name="tree1" Background="LightCyan" > <TreeViewItem Header="File" Background="Red" FontSize="15"> </TreeViewItem> <TreeViewItem Header="Edit" Background="Red" FontSize="15" > </TreeViewItem> </TreeView> </ListView> </Grid> </Page>
.XAML.CS CODE: private void Page_Loaded(object sender, RoutedEventArgs e) { Dictionary<string, List<string>> items = new Dictionary<string, List<string>>() { {"File",new List<string>() {"New","Open","ADD","Save","Save As","Close"}}, {"Edit",new List<string>() {"Undo","Cut","Copy","Paste","Delete"}}, }; foreach (TreeViewItem tv in tree1.Items) { foreach (string item in items[tv.Header.ToString()]) tv.Items.Add(item);} } }
Design Output:
<Page x:Class="WpfBrowserApplication5.Page15" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page15" Loaded="Page_Loaded"> <Grid> <UniformGrid Margin="15,15,15,15" Name="uniformGrid1"> <Image Source="user-admin.png" MouseDown="img1_MouseDown" Name="img1" ></Image> <Image <Image <Image <Image <Image <Image Source="user-admin.png" Source="user-admin.png" Source="user-admin.png" Source="user-admin.png" Source="user-admin.png" Source="user-admin.png" Name="img2" ></Image> Name="img3" ></Image> Name="img4" ></Image> Name="img5" ></Image> Name="img6" ></Image> Name="img7" ></Image>
<Image Source="user-admin.png" Name="img8" ></Image> <Image Source="user-admin.png" Name="img9" ></Image> </UniformGrid> </Grid> </Page>
Design Output:
Example:
.XAML.CS CODE <Page x:Class="WpfBrowserApplication5.Page14" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentatio n" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page14"> <Grid x:Name="LayoutRoot" Background="White" > <WrapPanel Orientation="Vertical"> <Image Source="_homebanner_1.gif" Width="97.135" Height="28" /> <Ellipse Width="80" Height="80" Fill="Orange" /> <Image Source="main_flash.jpg" Width="69.999" Height="26" /> <Ellipse Width="40" Height="40" Fill="Green" /> <Ellipse Width="20" Height="20" Fill="Blue" /> <Rectangle Width="100" Height="100" Fill="Cyan" Cursor="None"
FlowDirection="RightToLeft"></Rectangle> <Rectangle Width="80" Height="80" Fill="DarkGoldenrod"></Rectangle> <Rectangle Width="60" Height="60" Fill="Chartreuse"></Rectangle> <Rectangle Width="40" Height="40" Fill="Coral"></Rectangle> <Rectangle Width="20" Height="20" Fill="DarkGoldenrod"></Rectangle> </WrapPanel> </Grid> </Page>
<Page x:Class="WpfBrowserApplication6.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1" Loaded="Page_Loaded"> <Grid> <Image Margin="8,9,0,0" Name="image1" Stretch="Fill" Height="231" VerticalAlignment="Top" ImageFailed="image1_ImageFailed" HorizontalAlignment="Left" Width="197" /> <Button Height="23" HorizontalAlignment="Right" Margin="0,22,12,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">Button</Button> <Label Height="28" HorizontalAlignment="Right" Margin="0,64,12,0" Name="label1" VerticalAlignment="Top" Width="75">Label</Label> </Grid> </Page>
.CS code: private void Page_Loaded(object sender, RoutedEventArgs e) { image1.Source = new BitmapImage(new Uri("college-students-2.jpg", UriKind.Relative));
Design Output:
<Page x:Class="WpfBrowserApplication6.Page2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page2"> <Grid> <Rectangle Margin="14,40,0,0" Name="rectangle1" Stroke="Violet" StrokeThickness="9" Height="100" VerticalAlignment="Top" HorizontalAlignment="Left" Width="200" Fill="Pink" RadiusX="6" RadiusY="6" /> </Grid> </Page>
in This code The Fill attributes fill a rectangle with a color. The following code fills a rectangle with pink color. By setting RadiusX and RadiusY attributes, you can also draw a rectangle with rounded corders. Output:
1. Introduction Of WPF 2. Birth Of WPF With Advantages 3. The IDE of WPF 4. Programming With WPF 5. Application in WPF
Architecture of WPF
Go to File menu choose new project and then WPF Application-as shown in below picture.
Then you will get space for working like in below picture.
Extensible Application Markup Language (XAML) XAML is an XML based language that is used as a foundation for the WPF. It allows forms to be created using a syntax very similar to ASP.NET and HTML. For example, a button in html:
and In WPF
Birth Of WPF
Microsoft has developed numerous graphical interface toolkits like C++ Win32 API, VB6, MFC, etc. to build desktop applications. These technologies are capable of designing a good GUI interface for the Windows Applications. But these lacks in some additional and advanced features, such as, 2D & 3D Rendering support, Multimedia Support, Animation Support, etc. which are essential now a days. So Microsoft has introduced WPF(Windows Presentation Foundation) API in .NET3.0 framework for the first time. It is released in the year 2007. .NET 3.0 is officially shipped for the first time with Windows Vista OS. But Windows XP and 2003 versions can also use .NET 3.0. Visual Studio 2005 is the first gateway to program .NET 3.0 applications. So to develop WPF application you need Visual Studio 2005 or later. What's New: .NET 2.0 supports 3D and Multimedia features, but the programmer has to use a number of unrelated APIs. For supporting 3D graphics he has to use DirectX APIs, to use multimedia he has to use Windows Media Player API, etc. So the programmer has to know all the different technologies to build a richer GUI. But it is very difficult to master all the different technologies and integrate them. So WPF merged all the unrelated APIs into a single unified object model. So if you want to use 3D graphics or multimedia for your application you do not use to need use different APIs. WPF provides all the functionality you need to develop richer GUI applications. Introducing XAML(An Integral Part Of WPF) WPF provides us the capability to design windows applications like an ASP.NET application using markup language. Microsoft called this as XAML(Extended Application Markup Language). XAML provides a separation of coding from designing. So you can develop your application using the toolbox and properties window like the general windows application or in a different form like web applications using markup language. XAML is capable to provide all the simple UI elements (such as labels, textboxes, etc.) to complex functionality (animation, graphics rendering and multimedia support). If you want to animate a button with a picture on it you only need a few line of XAML code. WPF elements can also be customized using styles and templates, minimizing your efforts. There are also a lot of tools to generate XAML code for you. You have to just define the UI in a drag and drop manner. You can also apply rendering effects and animations to these UI using a simple IDE. Then the IDE will give you the XAML code to be used in your application. WPF Advantages:
1. Broad Integration: Prior to WPF, it was very difficult to use 3D, Video, Speech, and rich document viewing in addition to normal 2D Graphics and controls would have to learn several independent technologies. WPF covers all these with consisting programming model as well as tight integration when each type of media gets composited and rendered. 2. Resolution Independence: WPF applications are device independent i.e., smart client applications. Like normal applications it wont get decrease the size as the resolution gets increase. This is possible because WPF emphasis on vector graphics. 3. Hardware Acceleration: WPF is built on top of Direct 3D, content in a WPF application whether 2D or 3D, Graphics or text is converted to 3D triangles, textures and other Direct 3D objects and then rendered by hardware. WPF applications can get the benefit of hardware acceleration for smoother graphics and all round better performance. 4. Declerative Programming: WPF takes the declarative programming to the next level with the introduction of Extensible Application Markup Language(XAML), pronounced as Zammel. XAML is like HTML in web used for creating the interface, resulting graphical designers are empowered to contribute directly to the look and feel of applications. 5. Rich Composition and Customization: WPF controls are extremely compostable. Eg: we can create combo box with animated buttons.
1.WPF ToolBox: The menu bar is situated under the title bar of the window. The menu bar has menus like File, Edit, View, Properties, Build, Debug, Tools etc. You can work with the different menu items as in case of Windows application development 2.The Tool Bar: The tool bar is situated below menu bar. The tool bar has options to save project, copy and paste, build, run,etc.
3.The Toolbox: By default the tool box will appear in the left pane. You can make it auto hide, floating or docking as per your choice. It has all the controls to work with. It contains the common controls like Button, Label, TextBox, etc. These controls work in a similar manner as that of Window Application. 4.The Solution Explorer: The solution Explorer is situated at the upper right corner of the IDE. It displays the classes, forms, modules, properties and preferences used by our application in a tree view. It makes the application development easy by displaying all the related items at one place. You can also make it floating, docking, or auto hide as per you choice. 5.The Property Window: The property window is situated below the Solution Explorer. The property window shows what properties the selected object has. You can set the different properties of the objects selected. You can also set these properties by coding manually. But it is easier to set the property by using the Property Window. The property window plays a vital role while developing WPF application. We can set the different 3D effects and other properties of control using this property window without knowing the XAML. The Property Window in WPF has some extra properties for each control than that of Windows application. You can make it floating, docking, or auto hide as per you choic 6.The WPF Form Designer: The WPF form designer has the same setting as that of Window Form Designer, but with some differences. The WPF designer contains a Zoom Tool to zoom the whole window so that you can develop your application more easily. You can place controls on the form by drag and drop method and resize it. It will display the distances from the window wall while resizing a control. It also provides to define grids in the window. 7.The XAML Editor: By default the XAML editor is displayed in split view below the WPD designer. You can choose your view to only Design or XAML according to your choice. In XAML editor you can define the XAML code to generate controls or set their properties. In split view it is easy to work as you can see how the different XAML tags affect the design. You can also take your XAML editor above the designer by clicking on the double arrow button present in the middle of designer and XAML editor headings below the designer.
WPF offers additional programming enhancements for Windows client application development. One obvious enhancement is the ability to develop an application using both markup and code-behind, an experience that ASP.NET developers should be familiar with. Development and maintenance costs are reduced because appearance-specific markup is not tightly coupled with behavior-specific code. Development is more efficient because designers can implement an application's appearance simultaneously with developers who are implementing the application's behavior. Multiple design tools can be used to implement and share XAML markup, to target the requirements of the application development contributors. Globalization and localization for WPF applications is greatly simplified Markup XAML is an XML-based markup language that is used to implement an application's appearance declaratively. It is typically used to create windows, dialog boxes, pages, and user controls, and to fill them with controls, shapes, and graphics.
Code-Behind The main behavior of an application is to implement the functionality that responds to user interactions, including handling events (for example, clicking a menu, tool bar, or button) and calling business logic and data access logic in response. In WPF, this behavior is generally implemented in code that is associated with markup. This type of code is known as code-behind. To understand Code behind i have taken example for Button click event to show the message box. For this just double click on Button you will go to the code behind of button and write the code as follows for button click event.
namespace WpfApplication1 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { // Show message box when button is clicked } } } MessageBox.Show("Welcome to WPF Programming!");
Applications of WPF
WPF has comprehensive features for creating user experiences with rich content. To package this content and deliver it to users as "applications," WPF provides types and services that are collectively known as the application model. The application model supports the development of both standalone and browser-hosted applications. Standalone Applications For standalone applications, you can use the Window class to create windows and dialog boxes that are accessed from menu bars and tool bars. Additionally, you can use the following WPF dialog boxes: MessageBox, OpenFileDialog, SaveFileDialog, and PrintDialog. Like in below image-
Browser-Hosted Applications For browser-hosted applications, known as XAML browser applications (XBAPs), you can create pages (Page) and page functions (PageFunction<T>) that you can navigate between using hyperlinks (Hyperlink classes). For Browser-Hosted Application we will discuss later. Now we are starting with Standalone Application. Controls in Windows WPFThe built-in WPF controls are listed here. Buttons: Button and RepeatButton. Dialog Boxes: OpenFileDialog, PrintDialog, and SaveFileDialog. Digital Ink: InkCanvas and InkPresenter.
Documents: DocumentViewer, FlowDocumentPageViewer, FlowDocumentReader, FlowDocumentScrollViewer, and StickyNoteControl. Input: TextBox, RichTextBox, and PasswordBox. Layout: Border, BulletDecorator, Canvas, DockPanel, Expander, Grid, GridView, GridSplitter, GroupBox, Panel, ResizeGrip, Separator, ScrollBar, ScrollViewer, StackPanel, Thumb, Viewbox, VirtualizingStackPanel, Window, and WrapPanel. Media: Image, MediaElement, and SoundPlayerAction. Menus: ContextMenu, Menu, and ToolBar. Navigation: Frame, Hyperlink, Page, NavigationWindow, and TabControl. Selection: CheckBox, ComboBox, ListBox, TreeView, RadioButton, and Slider. User Information: AccessText, Label, Popup, ProgressBar, StatusBar, TextBlock, and ToolTip.
1. WindowsBase.dll: This assembly defines the core types that constitute the
infrastructure WPF API. for WPF GUI layer.
2. PresentationCore.dll: As the name specifies this assembly specifies different types 3. PresentationFoundation.dll: It defines the WPF control types, animation,
multimedia and data binding support. It also specifies some other functionality. 4. The above three namespaces are managed namespaces. Besides these three namespaces WPF also uses an unmanaged library, i.e. milcore.dll. This library is responsible to work with DirectX layer. It acts as a bridge between the managed WPF assemblies and the DirectX layer. Some WPF Classes: All these three assemblies provides a number of new namespaces and hundreds of new .NET types(classes, interfaces, structures, enumerations and delegates) to work with WPF. The following class diagram and the classs functionality.
DispatcherObject: It is an abstract base class for classes that are bound to one thread. Classes that are derived from DispatcherObject have an associated Dispatcher object that can be used to switch the threads. Application: In every WPF application, one instance of Application class is created. This class implements a singleton pattern for access to the window of application, resources and properties. See the below image.
DependencyObject: It is the base class for all the classes that supports Dependency property. Visual: It is the base class for all the visual elements of WPF. This class includes features for transformation. UIElement: It is the abstract base class for all WPF elements that need basic presentation feature. This class provides evens such as mouse move, drag and drop, click, etc. FrameworkElement: It is derived from base class UIElements and implements the default behaviour of the methods defined by the base class. Shape: Shape is the base class for all the shape elements such as, line, rectangle, ellipse, polygon. Control: It is derived from FrameworkElement and is the base class for all the userinteractive elements. Panel: As the name suggest it is the abstract base class for all the panels and is derived from FrameworkElement. Panel class has a Children property for all the UIElement that is inside a panel and defines methods for arranging the child controls. Panel defines different classes to define the behaviour of child controls such as, WrapPanel, StackPanel, Grid and Canvas. ContentControl: - It is the base class for all the controls that have a single content such as, Buttons, Labels, CheckBox, RadioButton, etc.
You can also find the class hierarchy of your application using Object Browser in VS 2008. To view Object Browser go to view menu and select Object Browser. Object Browser also contains all the namespaces and its classes. See the below image for WPF class hierarchy. It is the class hierarchy of a simple WPF application that we have created earlier. Using Object Browser you can find all the methods, properties and events of a particular class by selecting that class.
Some WPF Namespaces: System. Windows:- It is the core namespace of WPF. You will find all the base classes such as, Application, DependencyObject , DependencyProperty and FrameworkElement here. System. Windows. Controls:- This namespaces contains all the controls of WPF. You will also find classes to work with complex controls such as PopUp, ScrollBar, StatusBar, TabPanel, etc. as well as all the basic controls. System. Windows. Data:- This namespace is used by WPF for Data Binding. System. Windows. Input:- This namespace provides several classes for command handling, keyboard input, etc. System. Windows. Markup:- This namespace helper classes for XAML markup code. System. Windows. Media:- This namespace is responsible to work with images, audio, and multimedia. System. Windows. Shapes:- This namespace provides core classes for UI such as Line, Rectangle, Ellipse, etc. System. Windows. Threading:- This namespace provides classes to work with multiple threads.
System. Windows. Navigation:- This namespace provides classes for navigation between WPF pages particularly when working with Web Applications.
Page 1
Ques: 1 What is WPF? Ans: Windows Presentation Foundation (WPF) is the presentation subsystem feature of the .NET Framework 3.0,that provide good design and advance controls. Silverlight is the Subset of WPF. Through WPF we can create Windows and WebBrowser Application. Ques: 2 What is XBAP? Ans: XBAP means XAML Browser Application. XBAP allows for WPF applications to be used inside a browser. For this .NET framework is required to be installed on the client system and hosted applications run in a partial trust sandbox environment. Ques: 3 What is XAML extensible markup language? Ans: XAML is an extensible markup language based on XML. XAML can be thought of as a declarative script for creating .NET 3.0 UI. It is particularly used in WPF as a user interface markup language to define UI elements, data binding, eventing and other features. It is also used in Windows Workflow Foundation (WF), in which the workflows themselves can be defined in XAML code. Ques: 4 What are dependency properties? Ans: These dependency properties belong to one class but can be used in another. Consider the below code snippet:<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" /> Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is dependency property as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas. Ques: 5 What kind of documents are supported in WPF? Ans: There are two kind of major document supported in WPF Fixed format documents and Flow format document. Fixed format documents look like PDF format. They display content regardless of screen size and resolution. But flow format document adjust depending on screen size and resolution. Ques: 6 Can you explain how we can separate code and XAML?
Ans: This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is. Ques: 7 What is a Routed event? Ans: In WPF application it contains many elements. These elements exist in an element tree relationship with each other. A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event. Ques: 8 Which namespace is used to work with 3D in WPF. Ans: System.Windows.Media.Medi3D namespace is used for working with 3D. Ques: 9 What is the use of System.Windows.Navigation namespace in WPF? Ans: This namespace contains different classes for navigation between windows. Ques: 10 How to define a button USING XAML? Ans: To define a button in WPF using XAML, Syntax is given below<Button Name="btnName">btnCaption</Button> Example:<Button Name="btnClick">Click Me</Button> Here the <Button> element specifies the use of the Button class. Ques: 11 What are the core WPF assemblies? Ans: The core WPF assemblies are, WindowsBase.dll:- This is the core types constituting the infrastructure of WPF API. PresentationCore.dll:- It defines numerous types constituting foundation of WPF GUI layer. PresentationFoundation.dll:- It defines WPF control types, animation & multimedia support, data binding suport and other WPF services. Besides these three libraries WPF also uses an unmanaged binary called milcore.dll which acts as a bridge between WPF assemblies and DirectX runtime layer. Ques: 12 What is the use of System.Windows.Media namespace? Ans: This is the root namespace of several other media related namespaces. It provides different types to work with animations like 3D rendering, text rendering and other multimedia services.
Ques: 13 What is Path animation? Ans: Path animation in which the object moves along the path specified by the Path geometry. As the animation progresses, it reads the X-axis, Y-axis and angle information from the path geometry and generates the output. These are useful when an object has to be animated along a complex path. Ques: 14 What is a Freezable? Ans: A freezable object is one that has a mechanism that allows you to "Freeze" it. This locks downs all the state and makes the object immutable. This makes the object more performant to use and safer to share between threads.
Page 1
Ques: 1 What is a Freezable? Ans: A freezable object is one that has a mechanism that allows you to "Freeze" it. This locks downs all the state and makes the object immutable. This makes the object more performant to use and safer to share between threads. Ques: 2 What is Path animation? Ans: Path animation in which the object moves along the path specified by the Path geometry. As the animation progresses, it reads the X-axis, Y-axis and angle information from the path geometry and generates the output. These are useful when an object has to be animated along a complex path. Ques: 3 What is the use of System.Windows.Media namespace? Ans: This is the root namespace of several other media related namespaces. It provides different types to work with animations like 3D rendering, text rendering and other multimedia services. Ques: 4 What are the core WPF assemblies? Ans: The core WPF assemblies are, WindowsBase.dll:- This is the core types constituting the infrastructure of WPF API. PresentationCore.dll:- It defines numerous types constituting foundation of WPF GUI layer. PresentationFoundation.dll:- It defines WPF control types, animation & multimedia support, data binding suport and other WPF services. Besides these three libraries WPF also uses an unmanaged binary called milcore.dll which acts as a bridge between WPF assemblies and DirectX runtime layer.
Ques: 5 How to define a button USING XAML? Ans: To define a button in WPF using XAML, Syntax is given below<Button Name="btnName">btnCaption</Button> Example:<Button Name="btnClick">Click Me</Button> Here the <Button> element specifies the use of the Button class. Ques: 6 What is the use of System.Windows.Navigation namespace in WPF? Ans: This namespace contains different classes for navigation between windows. Ques: 7 Which namespace is used to work with 3D in WPF. Ans: System.Windows.Media.Medi3D namespace is used for working with 3D. Ques: 8 What is a Routed event? Ans: In WPF application it contains many elements. These elements exist in an element tree relationship with each other. A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event. Ques: 9 Can you explain how we can separate code and XAML? Ans: This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is. Ques: 10 What kind of documents are supported in WPF? Ans: There are two kind of major document supported in WPF Fixed format documents and Flow format document. Fixed format documents look like PDF format. They display content regardless of screen size and resolution. But flow format document adjust depending on screen size and resolution. Ques: 11 What are dependency properties? Ans: These dependency properties belong to one class but can be used in another. Consider the below code snippet:<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" /> Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is dependency property as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas.
Ques: 12 What is XAML extensible markup language? Ans: XAML is an extensible markup language based on XML. XAML can be thought of as a declarative script for creating .NET 3.0 UI. It is particularly used in WPF as a user interface markup language to define UI elements, data binding, eventing and other features. It is also used in Windows Workflow Foundation (WF), in which the workflows themselves can be defined in XAML code. Ques: 13 What is XBAP? Ans: XBAP means XAML Browser Application. XBAP allows for WPF applications to be used inside a browser. For this .NET framework is required to be installed on the client system and hosted applications run in a partial trust sandbox environment. Ques: 14 What is WPF? Ans: Windows Presentation Foundation (WPF) is the presentation subsystem feature of the .NET Framework 3.0,that provide good design and advance controls. Silverlight is the Subset of WPF. Through WPF we can create Windows and WebBrowser Application.
Page 1
Tot Show al Post Your Answers Pos Answers ts
Questions
Last Post
What is full form of WPF? a)Windows Presentation FoundationClass b)Windows Precomputed FoundationClass c)Windows Presentation Functions d)None of These What is XAML? a)Extensible and Markup Language b)Extensible Application Markup Language c)Xtra Application Markup Language d)None of These Does that mean WPF has replaced DirectX? a)Yes b)No Is XAML meant only for WPF ? a)Yes b)No
Show Answers
23.12.10 Anil
Show Answers
23.12.10 Anil