WPF – DOT NET Chapter Wise Interview Questions
Question 1:
What is WPF?
Answer:
WPF (Windows Presentation Foundation) is a graphical subsystem for displaying user interfaces, documents, images, movies, etc., in windows application.
Question 2:
What is the need of WPF when we had Windows forms?
Answer:
Remember: ABCDEFG
A – Anywhere execution (Windows or Web)
B – Bindings (less coding)
C – Common look and feel (resource and styles)
D – Declarative programming (XAML or Extensible Application Markup Language)
E – Expression blend animation (Animation ease)
F – Fast execution ( Hardware acceleration)
G – Graphic hardware independent (resolution independent)
Question 3:
What is XAML in WPF and why do we need it?
Answer:
XAML is a XML file which represents your WPF Ul. The whole point of creating the Ul representation in XML was write once and run it anywhere. So the same XAML Ul can be rendered as windows application with WPF and the same Ul can be displayed on the browser using WPF browser or Silverlight application.
Question 4:
What is xmlns in XAML file?
Answer:
“xmlns” stands for XML namespaces. It helps us to avoid name conflicts and confusion in XML documents. For example, consider the below two XML which have table elements, one table is a HTML table and the other represents a restaurant table. Now if both these elements come in a single XML document there would name conflicts and confusion.
<table> <trxtd>Rowl</tdx/tr> <tr>< td>Row2 </td></tr> </table> <table> <cloth>red</cloth> <serve>Tea</serve> </table>
So to avoid the same we can use XML namespaces. You can see in the below XML we have qualified the HTML table with “<h: table>” and the restaurant table element qualified with “<r: table>”.
<h: tablexmlns: h="HTTP: //www.w3.org/TR/html4/"> <trxtd>Rowl</td></tr> < tr>< td>Row2 </td></tr> </h: table> <r: tablexmlns: h="HTTP: //www.questpond.com/restaurant/table/def"> <cloth>red</cloth> <serve>Tea</serve> </r: table>
Question 5:
What is the difference between xmlns and xmlns: x in WPF?
Answer:
Bothe namespaces helps to define / resolved XAML Ul elements.
The first namespace is the default namespace and helps to resolve overall WPF elements.
xmlns=”HTTP: //schemas, microsoft.com/winfx/2006/xaml/presentation”
The second namespace is prefixed by “x: ” and helps to resolve XAML language definition.
xmlns: x=”HTTP: //schemas, microsoft.com/winfx/2006/xaml”
For instance for the below XAML snippet, we have two things one is the “StackPanel” and the other is “x: name”. “StackPanel” is resolved by the default namespace and the “x: name” is resolved by using “xmlns: x” namespace.
<StackPanetx: Name-’myStack” />
Question 6:
Provide some instances where you have “xmlns: x” namespace in XAML?
Answer:
There are two common scenarios where we use “xmlns : x” namespace:
To define behind code for the XAML file using “x: class” attribute.
<Page xmlns="HTTP: //schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x="HTTP: // schemas.microsoft.com/winfx/2006/xaml" x: Class="MyNamespace.MyCanvasCodelnline" >
Second to provide name to an element.
<StackPanel x: Name=”myStack” />
Question 7:
When should we use “x: name”and “name”?
Answer:
There is no difference between “x: name” and “name”, “name” is short hand of “x: name”.
But in classes where you do not find “name” property (this is a rare situations) we need to use “x: name” property.
Question 8:
What are the different kinds of controls in WPF?
Answer:
WPF controls can be categorized in to four categories:
- Control: This is the basic control with which you will work most of time. For example textbox, buttons etc. Now controls which are standalone control like button, text box, labels, etc., are termed as content control. Now there are other controls which can hold othercontrols, for instance itemscontrols. Itemscontrol can have multiple textbox controls, label controls, etc.
- Shape: These controls help us to create simple graphic controls like Ellipse, Line, rectangle, etc.
- Panel: These controls help to align and position the controls. For instance grid helps us to align in a table manner, stack panel helps for horizontal and vertical alignment.
- Content presenter: This control helps to place any XAML content inside it. Used when we want to add dynamic controls on a WPF screen.
All the above four types of WPF controlsfinally inherit from the framework element class of WPF as
shown in Figure 12.2.
Question 9:
Can you explain the complete WPF object hierarchy?
Answer:
Figure 12.3 shows the hierarchy of WPF objects as shown Figure 12.3.
- Object: As WPF is created using .NET so the first class from which WPF Ui classes inherits is the .NET object class.
- Dispatcher: This class ensures that all WPF UI objects can be accessed directly only by the thread who own him. Other threads who do not own him have to go via the dispatcher object.
- Dependency: WPF UI elements are represented by using XAML which is XML format. At any given moment of time a WPF element is surrounded by other WPF elements and the surrounded elements can influence this element and this is possible because of this dependency class. For example, if a textbox surrounded by a panel, its very much possible that the panel background color can be inherited by the textbox.
- Visual: This is the class which helps WPF UI to have their visual representation.
- UI Element: This class helps to implement features like events, input, layouting, etc.
- Framework element: This class supports for templating, styles, binding, resources, etc.
And finally all WPF controls textbox, button, grids and whatever you can think about from the WPF toolbox inherits from the framework element class.
Question 10:
Does that mean WPF has replaced DirectX?
Answer:
No, WPF does not replace DirectX. DirectX will still needed to make cutting edge games. The video performance of directX is still many times higher than WPF API (Application Programming Interface). So when it comes to game development the preference will be always DirectX and not WPF. WPF is not an optimum solution to make games, oh yes you can make a TIC-TAC-TOE game but not high action animation games.
One point to remember WPF is a replacement for Windows form and not directX.
Question 11:
So is XAML meant only for WPF?
Answer:
No, XAML is not meant only for WPF. XAML is a XML-based language and it had various variants.
- WPF XAML is used to describe WPF content, such as WPF objects, controls and documents. In WPF XAML we also have XPS XAML which defines an XML representation of electronic documents.
- Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a crossplatform browser plug-in which helps us to create rich Web content with 2-dimensional graphics, animation, and audio and video.
- WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this XAML and invokes workflow accordingly.
Question 12:
Can you explain the overall architecture of WPF?
Answer:
Figure 12.4 shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and miicore. In the same diagram we have shown how other section like direct and operating system interact with the system. So let’s go section by section to understand how every section works.
- User32: It decides which goes where on the screen.
- DirectX: As said previously WPF uses directX internally. DirectX talks with drivers and renders the content.
- MILcore: MIL stands for media Integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API.
- Presentation core: This is a low level API exposed by WPF providing features for 2D (two-dimensional), 3D (three-dimensional), geometry, etc.
- Presentation framework: This section has high level features like application controls, layouts. Content, etc., which helps you to build up your application.
Question 13:
What is App.xaml in WPF project?
Answer:
App.xaml is the start up file or a boot strapper file which triggers your first XAML page from your WPF project.
Question 14:
What are various ways of doing alignment in WPF?
Answer:
There are five ways of doing alignment in WPF as shown in Figure 12.5:
Grid: In Grid alignment we divide the screen in to static rows and columns like HTML tables and position elements in those rows and column area.
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Label Grid.Column="0" Grid.Row="0" Background="Red">1st column 1st row </Label> <Label Grid.Column="l" Grid.Row="0" Background="LightGreen">2nd Column 2nd row </Label> <Label Grid.Column="0" Grid.Row="l" Background="Red">lst column 2nd row </ Label> <Label Grid.Column="l" Grid.Row="l" Background="LightGreen">2nd Column 2nd row </Label> </Grid>
Stack panel: Arranges control in vertical or horizontal format as shown in Figure 12.6.
<StackPanel Orientation="Vertical"> <Label Background="Red">Red </Label> <Label Background="L.ightGreen">Green </Label> <Label Background="LightBlue">Blue </Label> <Label Background="Yellow">Yellow </Label> </stackPanel>
Wrap Panel: Aligns elements in a line until the border is hit, then wraps in to the next line as shown in Figure 12.7.
<WrapPanel Orientation="Horizontal"> <Label Width="125" Background="Red">Red 1</Label> <Label Width="100" Background="LightGreen">Green 1</Label> <Label Width="125" Background="LightBlue">Blue 1</Label> <Label Width="50" Background="Yellow">Yellow 1</Label> <Label Width="150" Background="Orange">Orange 1</Label> <Label Width="100" Background="Red">Red 2</Label> <Label Width="150" Background="LightenGreen">Green 2</Label> <Label Width="75" Background="LightenBlue">Blue 2</Label> </WrapPanel>
Dock Panel: Aligns controls in five different regions: top, bottom, left, right and center as shown in Figure 12.8.
<DockPanel> <Label DockPanel.Dock="Top" Height="100" Background="Red">Top 1</Label> <Label DockPanel.Dock="Left" Background="LightGreen">Left</Label> <Label DockPanel.Dock="Right" Backgrounds"LightCyan">Right</Label> <Label DockPanel.Dock="Bottom" Background="LightBlue">Bottom</Label> <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"> Demo of Dock panel</TextBlock> </DockPanel>
Canvas: Positions elements absolutely use co-ordinates as shown in Figure 12.9.
<Canvas Margin="273, 130, 144, 99"> <TextBlock> Canvas position </TextBlock> </Canvas>
Question 15:
What are resources in WPF?
Answer:
Resources are objects referred in WPF XAML. In C# code when we create an object, we do the following three steps as shown in Figure 12.10.
using CustomerNameSpace; // import the namespace. Customer obj = new Customer(); // Create object of the class Textboxl.text = obj.CustomerCode; // Bind the object with UI elements
So even in WPF XAML to define resources which are nothing but objects we need to the above 3 steps:
- Import namespace where the class resides: To define namespace we need to use the “xmlns” attribute as shown in the below XAML code.
<Window x: Class="LearnWpfResources.MainWindow" xmlns="HTTP: //schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x="HTTP: //schemas.microsoft.com/winfx/2006/xaml" xmlns: custns="clr-namespace: LearnWpfResources" Title="MainWindow" Height="350" Width="525">
- Create object of the class: To create an object of the class in XAML we need to create a resource by using the resource tag as the below code. You can the object name is ‘ custobj
<Window.Resources> <custns: Customer x: Key="custobj"/> </Window.Resources>
The above code you can map to something like this in C#.
Customer custobj = new Customer();
- Bind the object with Ul objects: Once the object is created we can then bind them using bindings like one way, two way as explained in “Explain one way, two way, one time and one way to source?” question explained above.
<TextBox Text=”{Binding CustomerCode, Mode=TwoWay Source={StaticResource custobj}}’’/>
Question 16:
Explain the difference between static and dynamic resource.
Answer:
Resources can be referred statically or dynamically. Static referred resources evaluate the resource only once and after that if the resources change those changes are not reflected in the binding. While dynamic referred resources are evaluated every time the resource is needed.
Consider the below “SolidColorBrush” resource which is set to “LightBlue” color.
<Window.Resources> <SolidColorBrush Color="LightBlue" x: Key="buttonBackground" /> </Window.Resources>
The above resource is binded with the below two textboxes statically and dynamically, respectively.
<TextBox Background= "{DynamicResource button Background}” /> <TextBox Background-’jStaticResource buttonBackground}”/>
Now if we modify the resource, you see the first text box changes the background and the other textbox color stays as it is.
private void Button_Click(object sender, RoutedEventArgs e) { Resources["buttonBackground"] Brushes.Black; }
Figure 12.11 shows the output of the same.
Question 17:
When should we use static resource over dynamic resource?
Answer:
Dynamic resources reduce application performance because they are evaluated every time the resource is needed. So the best practice is use Static resource until there is a specific reason to use dynamic resource. If you want resource to be evaluated again and again then only use dynamic resource.
Question 18:
Explain the need of binding and commands.
Answer:
WPF Binding’s helps to send / receive data between WPF objects while command helps to send and receive actions as shown in Figure 12.12. The object that emits data or action is termed as source and the object who wants to receive data or action is termed as target.
Question 19:
Explain one way, two way, one time and one way to source.
Answer:
All the above four things define how data will flow between target and source objects when WPF binding is applied as shown in 12.13.
- Two way: Data can flow from both source to target and from target to source.
- One way: Data flows only from source to target.
- One way to source: Data flows only from target to source.
- One time: Data flows only for the first time from source to target and after that no communication happens.
Table below shows is an easy tabular representation to memorize the same.
Bindings | Data flow | |
Target to Source | Source to target | |
Two way | Yes | Yes |
One way to source | Yes | No |
One way | No | Yes |
One time | No | For first Yes |
Figue 12.14 shows the binding direction (mode), like Default.
Question 20:
Can you explain WPF command with an example?
Answer:
When end users interact with application they send actions like button click, right click, Ctrl + C, Ctrl + V, etc. A command class in WPF wraps these end user actions in to a class so that they can be reused again and again.
WPF Command class idea is an implementation of command pattern from gang of four design pattern.
To create a command class we need to implement the “icommand” interface. For example below is a simple command class which increments a counter class by calling “increment” method.
public class IncrementCounter: System.Windows.Input.ICommand { private clsCounter obj; public IncrementCounter (clsCounter o) { Obj = 0; } Public event eventHandler CanExecutChanged; Public Void Execute(Object Parameter) { Obj.Increment(); }
The command class needs two implement methods as shown in the above code:
What to Execute (Execute) – Command class is all about wrapping actions of end users so that we can reuse them. At the end of the day Action invokes methods. Mean for instance a “btnmaths_click” action will invoke “Add” method of a class. The first thing we need to specify in the command class is which method you want to execute. In this case we want to call the “Increment” method of “clsCounter” class.
When to execute (CanExecute) – The second thing we need to specify is when the command can execute, means validations. This validation logic is specified in the “CanExecute” function. If the validation returns true then “Execute” fires or else the action has no effect.
You can see the code of “CanExecute” and “Execute” in the above code snippet.
Once you have created the “Command” class you can bind this with the button using-the “Command” property as shown in the below XAML code.”CounterObj ” is a resource object.
<Button Command=”{Binding IncrementClick, Source={StaticResource Counterobj}}”/>
So now that the action is wrapped in to command we do not need to write method invocation code again and again in behind code, we just need to bind the command object with the WPF Ul controls wherever necessary.
Question 21:
How does “UpdateSourceTrigger” affect bindings?
Answer:
“UpdateSourceTrigger” decides when the data should get updated between WPF objects that are binded. In other word should data get updated in lost focus event, in data change event, etc.
There are four modes by which “UpdateSourceTrigger” can be defined:
- Default: If it is a text property then data is updated during lost focus and for normal properties data updates in property change event.
- PropertyChanged: In this setting data is updated as soon as the value is changed.
- LostFocus: In this setting data is updated as soon as lost focus event occurs.
- Explicit: In this setting the data is updated manually. In other words to update data between two WPF object you need to call the below code.
BindingExpression binding =txt1.GetBindingExpression(TextBox. TextProperty); binding. UpdateSource();
To set “UpdateSourceTrigger” we need to use the “UpdateSourceTrigger” value which can be found in the bindings properties as shown in the Figure 12.15.
Question 22:
Explain the need of “INotifyPropertyChanged” interface.
Answer:
When we bind two WPF objects the target data is updated depending on the “UpdateSourceTrigger” events. Please refer the previous question for “UpdateSourceTrigger” basics.
The “UpdateSourceTrigger” has events like lostfocus, property change, etc. In other words when lostfocus or property change event happen on the target it makes a PULL to the source to get the latest data as shown in Figure 12.16.
So it’s very much possible that the WPF source data has changed and because the WPF target “UpdateSourceTrigger ” event did not fire if did not make a pull and the data of the source is not in synch with the target as shown in Figure 12.17. This is where “INotifyPropertyChanged” interface comes to use.
Below is a simple “clsCounter” class which has a “Counter” property and this property is incremented by “increment” method.
Now if we bind WPF label or textbox to the “Counter” property and call the “increment” method the new “Counter” value will not be propagated to the target. Because invoking a method does not trigger any “UpdateSourceTrigger” event.
So after calling the “increment” method the “Counter” value of the source and the target are out of synch.
So create a push event from the source you need to first implement “iNotifyPropertyChanged” interface as shown in the Figure 12.18. Now when someone calls the “increment” method you can raise an event saying that the “Counter” property has changed by calling “PropertyChanged” function as shown in the below code.
In simple words the source sends a notification to the target WPF object that data has changed in the source and if should refresh itself with the fresh data.
PropertyChanged(this, new PropertyChangedEventArgs(“Counter”));
Below is full “clsCounter” class code with “INotifyPropertyChanged” implemented.
public class clsCounter: INotifyPropertyChanged { private int _Counter=0; public int Counter { get { return _Counter; } } public void Increment() { _Counter++; PropertyChanged(this, new PropertyChangedEventArgs("Counter")); } public event PropertyChangedEventHandler PropertyChanged; }
Question 23:
How are WPF observable collections different from simple .NET collections?
Answer:
Simple .NET collections do not notify the Ul automatically when elements are added or removed from them. So when we update simple .NET collection’s we need to send refresh eventsback to the WPF Ul for rebinding the collection.
“ObservableCol lection “are specialized collection which updates the Ul automatically and immediatelywhen new elements are added and removed from the collection.
“ObservableCollection” implement’s “iNotifyCollectionChanged” interface. This interface exposes “CollectionChanged” event which gets raised when elements are added or removed to the collection.
Below is a simple code which creates “ObservableCollection” collection which is binded with a list.
ObservableColleciion<Person> person = new ObservableCollection<Person>(); IstNames. ltemsSource = person;
Question 24:
What are value converters in WPF?
Answer:
Binding is one of the big features in WPF which helps us to facilitate data flow between WPF Ul and Object (See Figure 12.18). But when data flows from source to Ul or vice-versa using these bindings we need to convert data from one format to other format. For instance let’s say we have a “Person” object with a married string property.
Let’s assume that this “Married” property is binded with a check box. So if the text is “Married” it should return true so that the option check box look’s checked. If the text is “UnMarried” it should return false so that the option check box looks unchecked.
In simple words we need to do data transformation. This is possible by using “Value Converters”. In order to implement value converters we need to inherit from “iValueConverter” interface and implement two methods “Convert” and “ConvertBack”.
public class MaritalConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.Culturelnfo culture) { string married = (string)value; if (married == "Married") { return true; } else { return false; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.Culturelnfo culture) { bool married = (bool)value; if (married) { return "Married"; } else { return "UnMarried"; } } }
You can see in the “Convert” function we have written logic to transform “Married” to true and from “UnMarried” to false. In the “ConvertBack” function we have implemented the reverse logic.
Question 25:
Explain multibinding and multivalue converters in WPF?
Answer:
“MultiBinding” helps you bind multiple sources to a target while multi-converters acts like bridge if the source and targets have different data formats or need some conversion as shown in Figure 12.19.
For example let’s say you have two textboxes which has “FirstName” and “LastName”. You want that as soon as users type on these two textboxes, the other text box should get updated with “FirstName LastName” as shown in the Figure 12.20.
Also vice-versa if we type in the third text box “FirstName LastName” it should display “FirstName” and “LastName’ in the other two textboxes, respectively.
So the first thing is to create a multivalue converter classwhich will join “FirstName” and “LastName” in to source and split “FirstName LastName” back to target. For the same we need to implement “IMultiValueConverter” and implement “Convert” and “ConvertBack” methods.
“Convert” helps to do conversion from “Target” to “Source” and “ConvertBack” helps to convert from “Source” to “Target”.
public class NameMultiConverter: IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.Culturelnfo culture) { // Conversion logic from Target to Source } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.Culturelnfo culture). { // Conversion logic from Source to Target. } }
Below is the “Convert” ( Target to Source) implementation where we get the “textbox” value in a array and we have concatenated the array values and returned the same in a single string. This single string will be displayed in the third textbox.
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.Culturelnfo culture) { string x = " "; foreach (object y in values) { x = x + " " + y.ToString(); } return x; }
“ConvertBack” helps to implement conversion logic from “Source” to “Target”. So when someone types “Shiv Koirala” in the third text box we would like to split “Shiv” in one string and “Koirala” in other string.
So you can see in the below code we have used the “Split” function to create a string array. So the first array index (array[0]) will go to the first textbox and the second array index (array[1]) will go to the second text box.
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.Culturelnfo culture) { string str = (string) value; string[] val = str.Split(' '); return val; }
Now once we are done with the converter next thing is to apply multi-binding. Below is the XAML code where we have the three text boxes ” txtFirs tName “, ” txtLas tName” and “txtFirstAndLast”.
You can see how the “txtFirstAndLast” textbox “Text” is binded using multibinding element which binds to “txtFirstName” and “txtLastName” textbox . So now if you make changes to multiple target the single source gets updated and if you update the source multiple target gets updates.
<TextBox x: Name="txtFirstName" HorizontalAlignment="Left" Height="26" Margin="42, 67, 0, 0” TextWrapping="Wrap" Text="" VerticaiAlignment="Top" Width="152" / > <TextBox x: Name="txtLastName" HorizontalAlignment="Left" Height="26" Margin="41, 135, 0, 0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width=" 153 " /> <TextBox x: Name="txtFirstAndLast" Height="28" HorizontalAlignment="Left" Margin="239, 103, 0, 0" Name="labell" VerticalAlignment="Top" Width="117”> <TextBox.Text> MultiBinding Converter="{StaticResource NameMultiConverter}"> <Binding ElementName="txtFirstName" Path="Text" /> <Binding ElementName="txtLastName" Path="Text" /> </MultiBinding> </TextBox.Text> </TextBox>
Question 26:
Explain WPF relative binding / relative resource.
Answer:
When we define bindings we need at least two elements target and source. But many times rather than defining binding between two elements we would like to define binding with reference to the current element, i.e., relatively.
For instance let’s say we have a WPF border and we would like height and width of the broder to be same. So for this scenario the target and source are the same, the WPF border itself. So we can define the binding using “RelativeSource” as shown in the below code. You can see it uses “Self” binding mode to bind the element to itself.
<Border BorderBrush="Black" BorderThickness="1" Height="139" Width="{Binding Height, RelativeSource={RelativeSource Self}}"/> What are the different ways of binding using relative source? .
There are four ways of binding relatively in WPF:
- Self
- Ancestor
- Previous data
- Tern plated parent
Question 27:
Can you explain self relative source binding in WPF?
Answer:
This relative binding helps to bind to one property of an element to the other property of the same element. For example, in the below XAML the border width is binded to height of the same border element.
< Border BorderBrush-’Black” BorderThickness=”1" Height=”139" Width-'{Binding Height, RelativeSource-{RelativeSource Self}}”/>
Question 28:
Explain Ancestor relative source binding in WPF.
Answer:
This relative binding helps to bind properties to the parent element properties. For example, in the below XAML code we have a textbox which has two border’s as a parent. One border is having dark green and the other border is having dark red color as the border color.
The dark green color border is the parent element followed by dark red and the textbox the child element at the end of the hierarchy.
<Border BorderBrush="DarkGreen"> <Border BorderBrush="DarkRed"> <TextBox /> </Border> </Border>
Below is how the WPF application looks like when it runs.
Now we want the background color of the text box to be binded to one of the parent border colors. To achieve the same we can use ancestor relative binding.
Table below shows some important properties in Ancestor type binding we need to know before we writing the binding code.
Property | Description |
AncestorType | Which type of parent element is it?. Is it a border element, grid element, etc. |
AncestorLevel | An element can have multiple parents. For example, in the above XAML we have two parents one with red color and the other with green. So this property specifies which level of parent element, we want to refer. Figure depicts the levels. The red color border is level 1 and the green color border is level 2.So the nearest element becomes the first level and so on. |
Binding | This specifies which property we want to bind to. For the current example we want to bind to border’s brush color. |
So the relative binding code with ancestor level 1, i.e., red looks as shown below. In case you are confused with any of the properties please refer to the previous table for more information.
<TextBox Background=" (Binding BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorLevel = l, AncestorType=(x: Type Border}}}"/>
So now the complete XAML with parent border element looks as shown in the below code.
<Border BorderBrush="DarkGreen"><!— Level 2 -> <Border BorderBrush="DarkRed"><!—Level 1 -> <TextBox Background="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorLevel=l, AncestorType={x: Type Border}}}"/> </Border> </Border>
Now if you run the above XAML code the textbox is binded with the background color of the first border. If you change the ancestor level to 2 textbox background color will change to green.
Question 29:
Explain the difference between visual and logical tree in WPF.
Answer:
WPF Ul is represented in XAML which is a XML format. In XML elements are arranged in a hierarchal fashion. For example, if you look at the below XAML (it has been downsized for simplicity) we have a Window element, the window element has a Grid control and the grid control has a button inside it.
<Window> <Grid> <Button..> </Grid> </Window>
So if you visualize the above XAML logically you can think that the button control is a child element of the Grid and the grid is the child element of the Window. This relationship between the elements which looks logical looking at the XAML is termed as “Logical Tree” as shown in Figure 12.24.
But now to display this Logical tree on to your screen you need lot of visual elements. Like border, text etc. So when you add these visual elements to the logical tree that complete structure is termed as “Visual Tree”.
Putting in simple words there is only tree in WPF but depending on how you view it these two trees are the outcome. If you use the WPF visualizer the above XAML tree looks something as shown in the below Figure 12.25 which is actually a complete visual tree.
In simple words whatever you see in your XAML is a logical tree and to make it display it uses the visual tree. Figure 12.26 shows the logical and visual tree of the above XAML. Logical tree is without the shades and with shades is the visual tree.
Question 30:
Why do we need to have these perspective of visual and logical tree in WPF?
Answer:
Visual tree and Logical tree are important when you work with WPF routed events.
Question 31:
Explain routed events in WPF.
Answer:
Routed events are those events which travel up or down the visual tree hierarchy. WPF events can be classified into three types:
- Direct events: In this case event is raised at the source and handled at the source itself like “MouseEnter” events.
- Bubbling events: They travel up the visual tree hierarchy. For example, “MousaDown” is a bubbling event.
- Tunneling events: These events travel down the visual tree hierarchy. “PreviewKeyDown” is a tunneling event.
Question 32:
Explain WPF styles.
Answer:
Let’s say you have WPF Ul which has a lot of buttons and you want to set the background to “Aqua’ color (See Figure 12.28).
So the quick way of doing is to set background of all the buttons to “Aqua” color as shown in the below XAML code. But now let’s say some days down the line customer wants to change the background color to “Red”. So you need to modify the background property for all buttons.
<Button Backgrounds"Aqua"/> <Button Background="Aqua"/> <Button Background="Aqua"/>
Won’t it be great if we can define the background color as a style from some common place and when we want to change the back ground color we just change from that central common place. That’s what WPF style helps us to achieve.
WPF style helps to define look and feel (color, fonts, alignments, etc.) from a central location so that we can have ease of maintenance.
To define a style we need to use the “Style” tag of XAML. It needs three things atleast:
- X: Key: Name of Key of the style.
- TargetType: WPF Ul object on which you want to apply style. For example, in the below code we are applying this style on the button.
- Setter: This element defines the property for which the value has to be set. For example, in our case we are setting the “Background” color property to “Aqua”.
<Style x: Key="myStyle" TargetType="Button"> <Setter Property="Background" Value="Aqua" /> </Style>
Once the style is defines we can attach the style resource to the style property of button element as shown in the below code.
<Button Style="(StaticResource myStyle}"/> <Button Style="(StaticResource myStyle}"/> <Button Style="{StaticResource myStyle}"/>
Question 33:
What are style triggers?
Answer:
Many times we would want astyle property to execute under certain conditions. Trigger’s help you to define condition under which the style values will be set.
For example, we want to create a dynamic style where we focus on the button it should change to red color or else should be set to Aqua color as shown in Figure 12.29.
To achieve the same we can use style trigger as shown in the below XAML code.
<Style x: Key="myStyle" TargetType="Button"> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="Background" Value="Red"/> </Trigger> </Style.Triggers> <Setter Property="Background" Value="Aqua" /> </Style>
Question 34:
Explain Multitrigger concept in WPF.
Answer:
Many times we want style triggers to be executed when multiple conditions are true. For example let’s say we have a button we want the button background to be set to “RED” when there is focus on the button and when somebody moves the mouse on the button.
In other situations the background color should be set to “Aqua”.
So to achieve such multiple AND conditions we can use “MultiTrigger” XAML element as shown in the below XAML code. Multiple AND conditions needs to be defined in “MultiTrigger .Conditions” tag and the property which needs to be modified in “MultiTrigger. Setters” tag.
<Style x: Key="myStyle" TargetType="Button"> <Style.Triggers> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsFocused" Value="True" /> <Condition Property="IsMouseOver" Value="True" /> </MultiTrigger.Conditions> <MultiTrigger.Setters> <Setter Property="Background" Value="Red" /> </MultiTrigger.Setters> </MultiTrigger> </Style.Triggers> <Setter Property="Background" Value="Aqua" /> </Style>
Question 35:
What is the difference between control templates and data templates?
Answer:
Control templates change the structure of a WPF element while data templates change the way data is displayed but maintain the structure of WPF element.
A visual example of control template where a rectangle shaped button is change into an ellipse shape.
For that we need to create style using the “<ControlTemplate>” element. In this “<ControlTemplate>” WPF element we can define the structure which we want to apply on the element. Below is the XAML code for the same.
<Style TargetType="Button"> <!-Override all default style —> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Ellipse Fill="{TemplateBinding Background}"/> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/ > </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
Later this style can be applied to the button using the style property as shown in below code.
<Button Style=”{StaticResource mystyle}”/>
Data templates have no effect on the structure but they affect data. For example, Figure 12.32 shows the is list box on which data templates have been applied. You can see the structure of the list box does not change but the number of fields and the way they are placed is changed.
To use data templates we need to use ‘ itemTemplate” tag and within the “itemTemplate” tag we can define the how we want the data to be structured.
<ListBox Margin="26, 27, 165, 51" x: Name="lstb"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="150"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="{Binding Name}" FontSize="12" Height="18" /> <TextBlock Grid.Column="l" Text="{Binding City}" FontSize="12" Height="18" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Question 36:
What is MWM?
Answer:
MVVM (Model-View-View Model) is an architecture pattern where we divide the project in to three logical layers and every layer has its own responsibility (See Figure 12.33).
Below are the three logical layers with explanation what they do:
- View: This layer handles responsibility of taking inputs from end user, positioning of controls, look and feel, design, visuals, colors etc.
- Model: This layer represents your middle layer objects like customer, supplier, etc. It handles business logic and interaction with data access layer.
- View Model: View model as it says View plus Model represents your user interface. You can also visualize this class as the behind code. This class is the bridge between model and view. It handles connection logic, data transformation logic and action mapping between mddel and view. For example it will have following types of logics as shown below.
- Replicating and propagating data between views and models. When someone enters data into Ul or the model gets updated this layer will ensure that the propagation of data happens between these entities.
- Handling data transformation from view to model and vice-versa. For example, you have a model which has gender property with data as “M” for male and “F” for female. But on the View or Ul you would like to display as a check box with true and false. This transformation logic is written in the view model class.
- View model also map Ul actions to methods. For example, you have “btn_Add” click event and when any one clicks on this button you would like to invoke “Customer .Add ()” method from the customer class. This connection code is again a part if view model.
Question 37:
What are the benefits of MWM?
Answer:
Below are the benefits of MWM pattern as shown in Figure 12.34:
- Separation of concern: As the project is divided into layers, every layer handles its own responsibility. This leads to better maintenance because when we change one layer the other layer does not get affected.
- increased Ul Reusability: The whole point of MWM is to remove behind, code, i.e., XAML.CS code. The problem with behind code is that it is tied up with a Ul technology, for example ASPX.CS code is tied up with the ASP page class, XAML.CS file is tied with WPF Ul technology and so on. So we cannot use ASPX.CS behind code with WPF XAML Ul.
By moving the behind code to the view model class we can now use this with any Ul technology.
Automated Ul Unit testing: View model class represents your Ul. The properties of the class represent Ul textboxes, combo boxes and the methods of the class represent action. Now as the Ul is represented by the view model class, we can do automated Ul testing using unit testing by creating the objects of view model class and doing the necessary asserts.
Question 38:
What is the importance of command and bindings in MWM pattern?
Answer:
MWM in the most used architecture because of command and bindings facility provided by WPF) (See Figure 12.35). WPF MWM is incomplete without command and bindings.
Command and bindings help you to connect view (WPF Ul) with view model class without writing lot of behind code. Binding connects the Ui input elements (textbox, combo box, etc.) with the view model class properties and the UI actions like button click, right click are connected to the methods of the class by commands.
Note: Please refer previous questions to understand command and bindings.
Question 39:
What is the difference between MWM and 3-layer architecture?
Answer:
MVVM has an extra layer as compared to 3 layer architecture. In 3 layer architecture we have UI (view), business logic (model) and Data Access Layer (DAL) as shown in Figure 12.36. In MVVM we have an extra layer in between view and model, i.e., the view model class.
3 layer architecture complements MWM architecture.
Question 40:
Explain delegate command.
Answer:
First let us answer in short: “Delegate command makes a MVVM command class independent of the view modef’. Now let’s understand the long way.
In MVVM architecture view talks with the view model and view model talks with the model. When actions are sent from the view they are sent to WPF commands for handling the events as shown in Figure 12.37. WPF commands invoked methods of view model internally.
In other words command needs reference of ‘hew model class.
If you see a typical WPF MVVM command it looks as shown below. You can see the “CustomerViewModel” class referenced inside the ‘btnCommand” class. If you think with your eyes closed this reference of “CustomerViewModel” class inside the command is a problem. This will lead to tight coupling between command classes and view model.
If you visualize command it is nothing but click, double click, left mouse click, drag and drop etc. It is an ACTION created by the user. Now wouldn’t be great if we can just attach this command with any view model. So like click event gets connected with “Cus tomervi ewModel” or “SupplierViewModel”.
This is achieved by using delegate command.
public class btnCommand: ICorranand { Private CustomerViewModel Viewobj = new CustomerViewModel () ; public btnCommand(CustomerViewModel obj) { Viewobj = obj; } public bool CanExecute(object parameter) // When he should execute { return Viewobj.IsValid(); } public void Execute(object parameter) ViewObj.Add(); }
To decouple the view model class from command we can use delegates, i.e., “Action” and “Func”.lf you see the command class we need only two things “WhattoExecute” and “WhentoExecute”. So how about passing these methods as generic delegates. You can see the constructor of “btnCommand” takes two delegates one what to execute and when to execute.
You can see in the below code the “btnCommand” class has no reference of the view model class but has references to delegates which are just abstract pointer to functions/methods. So this command class can now be attached with any view model class. This approach is termed as “Delegate command”.
public class btnCommand: ICommand // Step 1: Create command { private Action WhattoExecute; private Func<bool> WhentoExecute; public btnCommand(Action What, Func<bool> When) { WhattoExecute = What; WhentoExecute = When; } public bool CanExecute(object parameter) // When he should execute { return WhentoExecute(); } public void Execute(object parameter) // What to execute { WhattoExecute(); } }
Question 41:
What is PRISM?
Answer:
PRISM (Personal Record Information System Methodology) is a framework to develop composite application in WPF and Silverlight as shown in Figure 12.38. Composite applications are built using composition. In other words rather than building application from scratch we take prebuilt components, assemble them together and create the application.
Take the example of simple WPF Ul (See Figure 12.39). You can see it has lots of sections. Now rather than building the whole Ul as one big unit, we can develop all these section as independent unit. Later by using PRISM we can compose WPF Ul by taking all these independent units (See Figure 12.39).
Question 42:
What are benefits of PRISM?
Answer:
- Modular development: As we are developing components as independent units we can assign these units to different developers and do modular parallel development. With parallel development project will be delivered faster.
- High reusability: As the components are developed in individual units we can plug them using PRISM and create composed Ul in an easy way.
Question 43:
How are individual units combined into a single unit?
Answer:
PRISM uses dependency injection for the same. Please see design pattern section to read about Dl (Dependency Injection). We can do Dl by two way’s by using unity application block or MEF (Managed Extensibility Framework).
Question 44:
Does PRISM do MWM?
Answer:
The prime focus of PRISM (Personal Record Information System Methodology) is modular development and not MWM. But it does have readymade classes like delegate command which can help us reduce MWM code. But please note the main goal of PRISM was not MWM.
Question 45:
Is PRISM a part of WPF?
Answer:
No, PRISM a acronym for (Personal Record Information System Methodology) is a separate installation.
Question 46:
What is expression blend?
Answer:
Expression blend is a designing tool for WPF and Silverlight application.
Question 47:
What is Silverlight?
Answer:
Silverlight is 16. Windows Presentation Framework (Vista Series)a Web browser plug-in by which we can enable animations, graphics and audio/video. You can compare Silverlight with Flash. We can view animations with Flash and it’s installed as a plug-in in the browser.
Question 48:
Can Silverlight run in other platforms other than window?
Answer:
Yes, animations made in Silverlight can run in other platforms other than window. In whatever platform you want run you just need the Silverlight plug-in.
Question 49:
Come on, even WPF runs under browser why Silverlight?
Answer:
Yes there is something called as WPF browser application which can run WPF in browser. For WPF browser application you need .NET framework to be installed in the client location while for Silverlight you need only the plug-in. So in other words WPF browser applications are OS (Operating System) dependent while Silverlight is not. Silverlight plug-in can run in other OS other than windows while we all know .NET framework only runs in windows.
Question 50:
What is the relationship between Silverlight, WPF and XAML?
Answer:
As explained previously XAML is a XML file which defines the Ul elements. This XML file can be read by WPF framework or Silverlight framework for rendering.
XAML files to describe the Ul elements to the WPF framework. Microsoft then extended WPF and made WPF/e (Windows Presentation Foundation/Everywhere) which helped to render the Ul in the browser. WPF/e was the code name for Silverlight. Later Microsoft launched Silverlight officially.
So the XAML just defines the XML structure to represent the Ul elements. Both the frameworks, i.e., WPF and Silverlight then reads the Ul elements and renders the Ul elements in the respective platform as shown in Figure 12.40.
Question 51:
What is XAP file in Silverlight?
Answer:
XAP (Cross-Platform Audio Creation Tool Audio Projects) the necessary DLLs (Dynamic Link Library), code at the browser client so that Silverlight application can run inside the browser.
Question 52:
Can you explain Sliverlight architecture?
Answer:
Before we talk about Silverlight architecture let’s discuss what is Silverlight is really made of technically. Silverlight has borrowed lot of things from existing Microsoft technologies. We can think Silverlight plug-in as a combination of some technologies from core .NET framework, vector animations, media and JavaScript as shown in Figure 12.41.
So we can visualize the Silverlight architecture as combination of some functionalities from core .NET framework, Ajax and some functionalities like animation, media, etc., provided by core Silverlight framework.
We can think Silverlight architecture as a combination of four important blocks:
- Some .NET framework components: Silverlight uses some components from .NET framework. One of the main components is WPF. Many of the Ul components (check box, buttons, text boxes, etc.), XAML parsing, etc., are taken from the core WPF system. It also has taken components like WCF to simplify data access. It also have CLR (Common Language Runtime) for memory management, safety checking and garbage collection. The base class libraries of NET are used for string manipulations, algorithms, expressions, collections and globalization.
- Presentation core: The core presentation framework has functionalities to display vector 2d animations, images, media, DRM (Digital Rights Management) and handle inputs like mouse and keyboard.
- Other technologies: Silverlight interacts with other technologies like Ajax and JavaScript. So it also borrows some functionalities from there technologies.
- Hosting: Silverlight animations finally run under the browser environment. So it has a the hosting functionality which helps to host the application the browser, expose a DOM (Document Object Model) by which JavaScript can manipulate the Silverlight components and it also has a installer functionality which helps to install Silverlight application and plug-in in the browser environment.
One of the things which you can notice from the architecture diagram is that the presentation core reads from the XAML file for rendering. The XAML is a component which is a part of the .NET framework and the rendering part is done by the presentation core (See Figure 12.42).
The application is a typical HTML which runs under the browser. There are markups which instantiates the Silverlight plug-in. Now when user interacts with the Silverlight application it sends event to JavaScript system or the .NET system. This depends on which programming language you are using. The program code which is either in JavaScript of .NET can make calls to the Silverlight run-time and achieve the necessary functionalities (See Figure 12.43). XAML will be read and parsed by the Silverlight runtime and then rendered accordingly to the browser.
Question 53:
What are the various basic steps to make a simple Silverlight application?
Answer:
This sample we are making using VS 2008 Web express edition and .NET 3.5. It’s a six step procedure to run our first Silverlight application. So let’s go through it step by step.
Step1: The first thing we need to do is install Silverlight SDK (Software Development Kit) from HTTP: //www. mi crosoft.com/down loads/d eta i Is. asox?f ami I vid = FB7900D B-4380-4 BO F-BB95- 0BAEC714EE17&displavlanq=en
Step 2: Once you install the Silverlight SDK you should be able to use the Silverlight template. So when you go to create a new project you will see a ‘Silverlight application’ template.
Step 3: Once you click ok you will see a dialog box as shown below with three options.
Add a ASP.NET Web project to the solution to host Silverlight: This option is the default option, and it will create a new Web application project that is configured to host and run your Silverlight application. If you are creating a new Silverlight application then this is the option to go.
Automatically generate Test Page To Host Silverlight at build time: This option will create a new page at runtime every time you try to debug and test your application. If you want to only concentrate on your Silverlight application then this option is worth looking at.
Link This Silverlight Control Into An Existing Website: If you have a existing Silverlight application then this option helps to link the Silverlight application with the existing Web application project. You will not see this option enabled to new projects, you need to have an existing Web application.
For this example we have selected the first option. Once you click ok you should see the full IDE (Integrated Development Environment) environment for Silverlight.
So let’s run through some basic points regarding the IDE view what we see. You will see there are two projects one is your Web application and the other is the Silverlight application. In the Silverlight application we two XAML files one is App.XAML and the other is Page.XAML.
App.XAML has the global level information.
Step 4: Now for simplicity sake we just use the TextBlock tag to display a text. You can see as we type in the Page.XAML its displayed in the viewer.
Step 5: Now we need to consume the Silverlight application in a ASPX page. So in the HTML / ASPX page we need to first refer the Silverlight name space using the ‘ Register’ attribute.
<%@RegisterAssembly=”System.Web. Silverlight” Namespace-’System. Web. Ul.SilverlightControls” TagPrefix-’asp” %>
We also need to refer the script manager from the Silverlight name space. The script manager control is functionality from AJAX. The main purpose of this control is to manage the download and referencing of JavaScript libraries.
<asp: ScriptManager ID=”ScriptManager1" runat=”server”></asp: ScriptManager>
Finally we need to refer the Silverlight application. You can see that in the source we have referred to the XAP file. XAP file is nothing but a compiled Silverlight application which is compressed and ZIP. It basically has all the files that’s needed for the application in a compressed format. If you rename the file to ZIP extension you can open the same using WINZIP.
<asp: Silverlight ID="Xamll" runat="server" Source="~/ClientBin/ MyFirstSilverLightApplication.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
So your final ASPX / HTML code consuming the Silverlight application looks something as shown below.
<%@ Page Language="C#" AutoEventWireup=''true" %> <%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %> <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN'' "HTTP: // www.w3.org/TR/xhtmll /DTD/xhtml1-transitional.dtd"> <html xmlns = "HTTP: //www.w3.org/1999/xhtml" style="height100%; "> <head runat="server"> <title>MyFirstSilverLightApplication</title> </head> <body style="height: 100%;margin: 0;"> <form id="forml" runat="server" style="height: 100%;"> <asp: ScriptManager ID="ScriptManagerl" runat="server"></asp: ScriptManager> <div style="height: 100%;"> <asp: Silverlight ID="Xamll" runat="server" Source-"~/ClientBin/MyFirstSilverLightApplication.xap" Minimuro.Version="2.0.31005.0" Width="100%" Height = " 100%" /> </div> </form> </body> </html>
Step 6: So finally set the Web application as start up and also set this page as start up and run it. You should be pleased to see your first Silverlight application running as shown in Figure 12.44.
Question 54:
What are the different kinds of bindings in Silverlight?
Answer:
There are three kind of bindings one-way, two-way and one time binding.
- One-way binding: data flows from object to Ul and not vice-versa.
- Two-way bindings: data flows from object to Ul and also vice-versa.
- In one time binding data flows from object to the Ul only once. There is no tracking mechanism to update data on either side. One time binding has marked performance improvement as compared to the previous two bindings discussed. This binding is a good choice for reports where the data is loaded only once and viewed.
In order to specify bindings we need to use the binding path attribute on the Ul elements as shown in the below code snippet.
<TextBox x: Name="txtEnterAge" Text="(Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>
Question 55:
How does Silverlight connect with databases?
Answer:
If you remember the Silverlight architecture, it does not contain ADO.NET. In order to make insert, update and deletes via Silverlight, we need to call WCF services and WCF services in turn will do insert updates and deletes on SQL Server.
Question 56:
What are the two important points we noted when we call WCF service from Silverlight?
Answer:
- We can only WCF services asynchronously from Silverlight.
- We need to create crossdomain and client access policy XML (extensible Markup Language) file where the WCF service is hosted.
Question 57:
What are the different ways of doing alignment in Silverlight and WPF?
Answer:
There are three ways provided by Silverlight for layout management Canvas, Grid and Stack panel.
Canvas is the simplest methodology for layout management. It supports absolute positioning using ‘X’- and ‘Y’-coordinates. ‘ Canvas. Left’ helps to specify the X-coordinate while ‘ Canvas . Top’ helps to provide the ‘Y’-coordinates.
Below is a simple code snippet which shows how Rectangle objects are positioned using ‘ Canvas’ on coordinates (50, 150).
<Canvas x: Name="MyCanvas"> <Rectangle Fill="Blue" Width="100" Height="100" Canvas . Lef t=" 50 " Canvas.Top="15 0 " /> </Canvas>
Grid layout helps you position your controls using rows and columns as shown in Figure 12.45. It’s very similar to table defined in HTML.
As the name so the behavior. Stack allows you to arrange your Ul elements vertically or horizontally.
Question 58:
What is expression blend?
Answer:
Expression blend is a graphic designer tool which can design the look-and-feel using expression blend and give the XAML file to the developers who can write the behind code for the same.
Question 1: How can we do multi-threading in WPF / Silverlight?
In order to implement proper multi-threading we need to use the dispatcher object.
Question 2: Can’t we just use threads, why do we need the dispatcher object?
In WPF / Silverlight objects have thread affinity. In other words the objects can be modified only by the thread that has created the object. Now when any WPF/Silverlight applications run they run on a main thread as shown in Figure 12.47. So that main thread only has the permission to modify the same.
Question 3: But what if try to modify it?
If other threads who have not created the Ul object tries to modify the same it will throw an exception “invalid cross-thread access”.
For example in the below code we have a simple function called as “SetValue”, this function modifies a textbox. This function is called directly by creating a “Thread” object in a button click event.
private void buttonl_Click(object sender, RoutedEveritArgs e) { Thread obj = new Thread(new ThreadStart(SetValue)); obj.Start(); } public void SetValue() { for (int i = 0; i < 10; i++) { textBoxl.Text = "test"; } }
Now the Ul object “textBoxl” is not created by thread “obj”. It’s created by the main thread which runs the WPF/Silver!ight Ul. So when you run the application you should get an exception as shown in the below “invalid cross-thread access” as shown in Figure 12.48.
Question 4: So how do we make the code working?
To make threading working in WPF and Silverlight we need to use the “Dispatcher” object. So rather than making calls directly to the Ul object we need to route the calls via dispatcher object. The dispatcher object then prioritizes and executes the calls on the threads behalf to the Ui control (See Figure 12.49).
So to make the above code working we need to call the code from within the dispatcher object. We need to pass a delegate to the “Beginlnvoke” function (which is done by using a lambda expression ” ()=>”) of the “Dispatcher” object.
public void SetValue( ) { for (int i = 0; i < 10; i++) { this.Dispatcher.Beginlnvoke(() => {textBoxl.Text = "Test";}); } }
Question 5: What is a background worker thread?
Background worker is a simple thread which runs at the background and helps us execute process in the background. In order to use background worker class we need to provide two things:
- The first thing we need to provide is the heavy processing method which we want invoke in a multi-threading fashion. For instance the below method “_bWorker_DoWork” has the heavy processing logic. This method is provided to the “DoWork” property of the “BackGroundWorker” class.
readonly BackgroundWorker _bWorker = new BackgroundWorker(); _bWorker.DoWork += new DoWorkEventHandler(_bWorker_DoWork); void _bWorker_DoWork (object sender, DoWorkEventArgs e) { //Heavy processing logic }
- The second thing is you need to invoke method ” RunWorkerAsync” so that the “_bWorker_DoWork” method will be executed in the background.
_bWorker. Run WorkerAsync();
Question 6: What is the difference between background worker and dispatcher?
Dispatcher only queues and executes the multi-threaded request. Dispatcher does not create threads. While background worker actually spawns and executes methods in a muiti-threaded manner.