Sie sind auf Seite 1von 9

Defining Styles With Keys

When you want to define more than one style for the same control type then you have to define it with a key and for this use x:Key property while defining the style. <Style TargetType=TextBox x:Key=TextBoxKey1> </Style> When you want to apply the style defined with a key to a control then you have to use Style property of that control using StaticResource markup extension. <TextBox Style={StaticResource TextBoxKey1} . />

Resource Dictionaries
In complex applications you may have large amount of application scoped resources. Specifying all these resources into the App.xaml file can turn into a maintenance issue very quickly. WPF provides a way to split resources into separate files and for this purpose follow the following steps. 1. Add Resource dictionary file to the project by right clicking on the project and choosing Add New Item. In the new item dialog box choose ResourceDictionary provide a name to it and click on add button. 2. Within the added Resource dictionary specify all resources and styles you want for the application and within the App.xaml file write the following within Application.Resources <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source=Pathofresourcedictionaryfile/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> Example : the following example adds a resource dictionary file to the project with the name MyResources.xaml, defines styles within it with key and applies these styles to textboxes on the window. 1. Add a resource dictionary to the project and provide following styles in it.
<Style x:Key="TextBoxKey1" TargetType="TextBox"> <Setter Property="FontFamily" Value="Arial"/> <Setter Property="FontSize" Value="15"/> <Setter Property="Foreground" Value="Blue"/> </Style> <Style x:Key="TextBoxKey2" TargetType="TextBox"> <Setter Property="FontFamily" Value="Times New Roman"/> <Setter Property="FontSize" Value="20"/> <Setter Property="Foreground" Value="Red"/> </Style>

2. Within App.xaml file within Application.Resources specify the following code.


<ResourceDictionary>

<ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="E:\WPF7\StylesAndResources\StylesAndResources\MyResources.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary>

3. Add a window to the project place two text boxes on it with a canvas as follows.
<Canvas> <TextBox Width="194" Height="30" Style="{StaticResource TextBoxKey1}" Canvas.Left="39" Canvas.Top="23" Text="Windows Presentation Foundation"/> <TextBox Width="194" Height="30" Style="{StaticResource TextBoxKey2}" Canvas.Left="39" Canvas.Top="72" Text="Windows Presentation Foundation"/> </Canvas>

Data Binding in WPF Data binding is a means of connecting the elements of a user interface with the underlying data that application is interested in. Data binding is declarative rather than programmatic. Data binding is done with {Binding} markup extension and data binding has a Mode property that has following possible values. OneWay TwoWay OneTime Changes to the source will update the target Changes to the source will update the target and vice versa. The target is set only when the application starts or when the datacontext is changed. Changes to the target will update the source

OneWayToSource

Example: the following example takes a textbox and binds its fontsize property to value property of a slider. Another textbox is taken and its text property is binded to value property of the same slider in two way mode. Add a window to the project and write the following XAML markup by taking a canvas.
<Canvas> <TextBox Width="256" Height="35" Text="Microsoft Corporation" FontFamily="Arial" FontSize="{Binding ElementName=S1,Path=Value}" Foreground="Blue" Canvas.Left="119" Canvas.Top="32" /> <Slider Name="S1" Minimum="20" Maximum="100" TickFrequency="10" TickPlacement="BottomRight" Width="256" Canvas.Left="91" Canvas.Top="82" /> <TextBox Name="Size" Width="35" Height="35" Text="{Binding ElementName=S1,Path=Value,Mode=TwoWay}" Canvas.Left="362" Canvas.Top="82" FontFamily="Arial" FontWeight="Bold" Foreground="Blue"/> </Canvas>

Data Templates Data templates are used to specify how the data will be visualized in user interface. The following examples displays data from a table DEPT available in a database MYDB of SQL Server using data set in a list box by defining a data template for the list box and by using data binding concept. 1. Add a window to the project and design it as follows.
<Window.Resources>

2. Write using statements in the code for the namespaces System.Data System.Data.SqlClient and write the following code within the window loaded event.
SqlConnection Cn = new SqlConnection("server=.;database=mydb;uid=sa;pwd=123"); SqlDataAdapter Da = new SqlDataAdapter("select * from dept", Cn); DataSet Ds = new DataSet(); Da.Fill(Ds, "Dept"); L1.DataContext = Ds;

<DataTemplate x:Key="T1"> <StackPanel Margin="5"> <DockPanel> <TextBlock Text="DEPTNO" FontFamily="Arial Black" FontSize="15" Foreground="Red" DockPanel.Dock="Left"/> <TextBlock Text="{Binding DEPTNO}" FontFamily="Arial Black" FontSize="15" Foreground="Blue" DockPanel.Dock="Left"/> </DockPanel> <DockPanel> <TextBlock Text="DNAME" FontFamily="Arial Black" FontSize="15" Foreground="Red" DockPanel.Dock="Left"/> <TextBlock Text="{Binding DNAME}" FontFamily="Arial Black" FontSize="15" Foreground="Blue" DockPanel.Dock="Left"/> </DockPanel> <DockPanel> <TextBlock Text="LOC" FontFamily="Arial Black" FontSize="15" Foreground="Red" DockPanel.Dock="Left"/> <TextBlock Text="{Binding LOC}" FontFamily="Arial Black" FontSize="15" Foreground="Blue" DockPanel.Dock="Left"/> </DockPanel> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <ListBox Width="250" Height="250" ItemsSource="{Binding Tables[0]}" ItemTemplate="{StaticResource T1}" Name="L1"/> </Grid>

and

Triggers in WPF
Triggers are implemented as part of styles, and indicate a trigger condition and a new set of setters to apply when the trigger condition is met. Mouseover effects are a very common application of triggers. Triggers can fully be expressed using XAML, eliminating the need to write code for many simple effects. There are three types of triggers in WPF: 1. Property Triggers - run when the value of a dependency property changes 2. Data Triggers - run when the value of any .NET property changes, using data binding 3. Event Triggers - run when a routed event occurs

Triggers are implement as part of a style using the <Style.Triggers> property element, and a series of <Trigger>,<DataTrigger>, or <EventTrigger> elements.

Example : the following example applies an effect for the button whenever mouse is over it using property trigger. Add a window to the project and write following XAML markup in it.
<StackPanel VerticalAlignment="Center"> <StackPanel.Resources> <Style TargetType="Button"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="BitmapEffect"> <Setter.Value> <OuterGlowBitmapEffect GlowColor="Yellow" GlowSize="15"/> </Setter.Value> </Setter> </Trigger> </Style.Triggers> </Style> </StackPanel.Resources> <Button Width="100" Height="50" Content="Button" Margin="20"/> <Button Width="100" Height="50" Content="Button" Margin="20"/> </StackPanel>

Example : the following example plays audio video in media element control using event triggers without writing code. Add a window to the project and write the following XAML markup in it.
<Grid> <Grid.RowDefinitions> <RowDefinition Height="5*"/> <RowDefinition/> </Grid.RowDefinitions> <MediaElement Name="Me" LoadedBehavior="Manual" Grid.Row="0"/> <StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Grid.Row="1"> <Button Name="BtnOpen" Width="75" Height="35" Content="Open" Margin="7" Click="BtnOpen_Click" /> <Button Name="BtnPlay" Width="75" Height="35" Content="Play" Margin="7"/> <Button Name="BtnPause" Width="75" Height="35" Content="Pause" Margin="7"/> <Button Name="BtnResume" Width="75" Height="35" Content="Resume" Margin="7"/> <Button Name="BtnStop" Width="75"

Height="35" Content="Stop" Margin="7"/> <StackPanel.Triggers> <EventTrigger RoutedEvent="Button.Click" SourceName="BtnPlay"> <BeginStoryboard Name="BS"> <Storyboard> <MediaTimeline Name="MT" Storyboard.TargetName="Me"/> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="Button.Click" SourceName="BtnPause"> <PauseStoryboard BeginStoryboardName="BS"/> </EventTrigger> <EventTrigger RoutedEvent="Button.Click" SourceName="BtnResume"> <ResumeStoryboard BeginStoryboardName="BS"/> </EventTrigger> <EventTrigger RoutedEvent="Button.Click" SourceName="BtnStop"> <StopStoryboard BeginStoryboardName="BS"/> </EventTrigger> </StackPanel.Triggers> </StackPanel> </Grid>

Write the following code within the open button click event after adding reference to System.Windows.Forms and writing using statement for it.
OpenFileDialog Ofd = new OpenFileDialog(); Ofd.InitialDirectory = "E\\Videos"; if (Ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { MT.Source = new Uri(Ofd.FileName); }

2 D Drawings in WPF
WPF provides the following 2D Drawings. Line : To draw a line use <line> tag that has the following properties. X1 and Y1 X2 and Y2 Stroke to specify the starting point of the line to specify the ending point of the line color of the line thickness of the line Dash Style of the line

StrokeThickness StrokeDashArray

Rectangle

: To draw a rectangle use <rectangle> tag that has the following properties. width and height of the rectangle horizontal and vertical radius of the rectangle to make the corners rounded corners

Width and height

RadiusX and RadiusY

Fill Stroke StrokeThickness StrokeDashArray

color to fill in the rectangle

Ellipse : To draw an ellipse use <Ellipse> tag that has the properties same as <rectangle> tag. PolyLine Points Stroke StrokeThickness StrokeDashArray Fill The following example draws various 2D drawings in a window.
<StackPanel> <Line X1="20" Y1="20" X2="250" Y2="20" StrokeThickness="5" Stroke="Blue" Margin="10" StrokeDashArray="7,3"/> <Rectangle Width="200" Height="100" Stroke="Blue" StrokeThickness="5" Margin="10" Fill="LightGray"/> <Rectangle Width="200" Height="100" Stroke="Blue" StrokeThickness="5" Margin="10" Fill="LightGray" RadiusX="20" RadiusY="10"/> <Ellipse Width="200" Height="100" Stroke="Blue" StrokeThickness="5" Margin="10" Fill="LightGray"/> <Ellipse Width="150" Height="150" Stroke="Blue" StrokeThickness="5" Margin="10" Fill="LightGray"/> </StackPanel>

: To draw polyline use <polyline> tag that has the following attributes to specify the points to draw the poly line.

The following example draws a poly line and also sine curve using poly line.
1. Write the following XAML markup for the window.
<StackPanel> <Polyline Stroke="Blue" StrokeThickness="5" Points="10,60 60,5 110,60 160,5 210,60" Margin="15"/> <Polyline Stroke="Blue" StrokeThickness="5" Points="10,60 60,5 110,60 160,5 210,60 10,60" Fill="Gold" Margin="15"/> <Polyline Stroke="Blue" StrokeThickness="5" Name="P1" Margin="15"/> </StackPanel>

2. Write the following code within the constructor of the window in code.
public PolyLineExample() { InitializeComponent(); for (int i = 0; i <= 70; i++) { double X = Math.PI * i; double Y = 40 + 30 * Math.Sin(X / 10); P1.Points.Add(new Point(X, Y)); } }

Animations in WPF
Animation implementation is very easy in WPF when compared to Windows Forms as it provides a number of pre defined types for animations that are in the namespace System.Windows.media.Animation. Animations are classified into following three types. Linear Interpolation animation key frame animation path-based animation

Linear Interpolation Animation represents the animation that vary properties gradually between starting and ending values Example classes are DoubleAnimation and ColorAnimation classes are examples Key Frame animation change property values abruptly at specified times Example classes are StringAnimationUsingKeyFrames and ObjectAnimationUsingKeyFrames Path-based animations change value according to a shape described using pathgeometry object and they are used for moving an element along a path.

Example classes are DoubleAnimationUsingPath and PointAnimationUsingPath classes are examples. Example : the following example moves a rectangle using linear interpolation animation Add a window to the project, write the following markup in it and then write the following code within the constructor of the window after writing using statement for namespace of animations.
<Canvas> <Rectangle Stroke="Blue" StrokeThickness="5" Fill="LightGray" Width="100" Height="100" Name="R1"/> </Canvas>

public Window1() { InitializeComponent(); DoubleAnimation DA = new DoubleAnimation(); DA.From = 0; DA.To = 180; DA.RepeatBehavior = RepeatBehavior.Forever; DA.AutoReverse = true; DA.Duration = TimeSpan.FromSeconds(10); R1.BeginAnimation(Canvas.LeftProperty, DA); R1.BeginAnimation(Canvas.TopProperty, DA); }

Example : the following example changes the background color of the button from red to yellow using coloranimation Add a window to the project, write the following markup for the window and then write the next code within the constructor of the window after writing using statement for the Animation namespace.
<Canvas> <Button Width="120" Height="120" Content="Color Animation" Canvas.Left="79" Canvas.Top="63"> <Button.Background> <SolidColorBrush x:Name="Scb"/> </Button.Background> </Button> </Canvas>

public ColorAnimationExample() { InitializeComponent(); ColorAnimation CA = new ColorAnimation(Colors.Red,Colors.Yellow, new Duration(new TimeSpan(0, 0, 10))); CA.RepeatBehavior = RepeatBehavior.Forever; CA.AutoReverse = true; Scb.BeginAnimation(SolidColorBrush.ColorProperty, CA); }

Example : the following example draws a path using pathgeometry and makes an ellipse drawn using Ellipsegeometry using path based animation. Add a window to the project, write the following markup for the window and then write the next code within the constructor of the window after writing using statement for the Animation namespace.
<Canvas> <Path Stroke="Blue" StrokeThickness="3"> <Path.Data> <PathGeometry x:Name="P1" Figures="M50,120 C75,20 175,20 200,120 220,220 325,220 350,120 325,20 220,20 200,120 175,220 75,220 50,120"/> </Path.Data> </Path> <Path Stroke="Goldenrod" Fill="Gold"> <Path.Data> <EllipseGeometry RadiusX="10" RadiusY="10" Center="50,120" x:Name="C1"/> </Path.Data> </Path> </Canvas>

public PathAnimation() { InitializeComponent(); PointAnimationUsingPath PA = new PointAnimationUsingPath(); PA.PathGeometry = P1; PA.RepeatBehavior = RepeatBehavior.Forever; PA.Duration = TimeSpan.FromSeconds(10); C1.BeginAnimation(EllipseGeometry.CenterProperty, PA); }