You are on page 1of 27

What are dependency properties?

Show/Hide Answer

These dependency properties belong to one class but can be used in


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 d
property as it belongs the canvas class. It is used by the Rectangle to specify its position withi
 

Can explain the different elements involved in WPF application practically?


Show/Hide Answer

In order to understand the different elements of WPF, we will do a small ‘hello world’ sample and in th
we will understand the different elements of

Note :- For this sample we have VS 2008 express


 
So start VS 2008 express and from the templates select the WPF application as show in the below fig
 

Once we have created the WPF application project you will see two file types one the XAML file and the o
behind code i.e. XAML.cs. XAML files are nothing but XML files which has all the elements needed to
windows UI. Every of the XAML elements maps to come class. For instance the ‘Window’ elemen
‘WpfApplication1.Window1’ class , ‘Button’ elements in XAML file maps to ‘System.Windows.Control.Bu
and ‘Grid’ XAML element is mapped to ‘System.Windows.Control.Grid’.
The ‘App.XAML’ and ‘App.XAML.CS’ are the entry point files. If we see the code for ‘App.XAML.CS’ you
reference to XAML file which needs to be loaded. So the first code which runs in the application is ‘v
method from ‘App.XAML.CS’ which in turn loads the ‘Window1.XAML’ file for rendering.
We can now connect the behind code method and function to events in XAML file elements.
You can see from the above code snippet how the button element has the click event link
‘MyButton_Click’ function. ‘MyButton_Click’ is the method which is in the XAML.CS beh
So now if you run the code you can see the button and if you click on it you can see the message
same.
 

Which are the different namespaces and classes in WPF?


Show/Hide Answer
There are ten important namespaces / classes in

System.Threading.DispatcherObject

All WPF objects derive from the DispatcherObject. WPF works on STA model i.e. Single Threading
Model. The main duty of this object is to handle concurrency and threading. When any message like mo
button clicks etc are initiated they are sent to the DispatcherObject who verifies whether code is runn
correct thread. In the coming section we will look in to detail how WPF threadin
 
System.Windows.DependencyObject

When WPF was designed property based architecture was considered. In other words rather than usin
functions and events object behavior will interact using properties. For now we will only restrict ourse
definition. In the coming section we have dedicated question for the
 

System.Windows.Media.Visual

Visual class is a drawing object which abstracts drawing instructions, how drawing should be drawn lik
opacity and other functionalities. Visual class also acts like a bridge between unmanaged MilCore.d
managed classes. When any class derived from visual it can be displayed on windows. If you want to c
own customized user interface then you can program using visual
 

System.Windows.UIElement

UIElement handled three important aspects layout, input and


System.Windows.FrameworkElement
FrameWorkElement uses the foundation set by UIElement. It adds key properties like HorizontalA
VerticalAlignment , margins
System.Windows.Shapes.Shape

This class helps us to create basic shapes such as Rectangle, Polygon, Ellipse, Line,

System.Windows.Controls.Control

This class has controls like TextBox,Button,ListBox etc. It adds some extra properties like font,foreg
background

System.Windows.Controls.ContentControl

It holds a single piece of content. This can start from a simple label and go down to a unit level of
layout panel using
System.Windows.Controls.ItemsControl
This is the base class for all controls that show a collection of items, such as the ListBox and

System.Windows.Controls.Panel

This class is used for all layout containers—elements that can contain one or more children and arrang
per specific layout rules. These containers are the foundation of the WPF layout system, and using them
to arranging your content in the most attractive, flexible way
 

Can you explain the overall architecture of WPF?


Show/Hide Answer
Above figure shows the overall architecture of WPF. It has three major sections presentation core, p
framework and milcore. In the same diagram we have shown how other section like direct and operat
interact with the system. So let’s go section by section to understand how every secti

User32:- It decides which goes where on the

DirectX: - As said previously WPF uses directX internally. DirectX talks with drivers and renders th

Milcore: - Mil stands for media integration library. This section is a unmanaged code because it acts li
between WPF managed and DirectX / User32 unmanaged

Presentation core ;- This is a low level API exposed by WPF providing features for 2D , 3D , geo

Presentation framework:- This section has high level features like application controls , layouts . C
which helps you to build up your application.

So is XAML meant only for WPF?


Show/Hide Answer

No,XAML is not meant only for WPF.XAML is a XML-based language and it had various

WPF XAML is used to describe WPF content, such as WPF objects, controls and documents. In WPF XA
have XPS XAML which defines an XML representation of electronic d

Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cro
browser plug-in which helps us to create rich web content with 2-dimensional graphics, animation, and
video.

WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this
invokes workflow a
 

What is XAML?
Show/Hide Answer

XAML (pronounced as Zammel) is a declarative XML-based language by which you can define
properties in XML. XAML document is loaded by a XAML parser. XAML parser instantiates objects an
properties. XAML describes objects, properties and there relation in between them. Using XAML, you
any kind of objects that means graphical or non-graphical. WPF parses the XAML document and insta
objects and creates the relation as defined by
So XAML is a XML document which defines objects and properties and WPF loads this document in actu
 

So can we define WPF in a precise way?


Show/Hide Answer

Windows Presentation Framework is the new presentation API. WPF is a two and three dimension
engine. It has the following ca
• Has all equivalent common user controls like buttons, check boxes slid
• Fixed and flow format
• Has all of the capabilities of HTML and
• 2D and 3D vector


• Data
 

Does that mean WPF has replaced DirectX?


Show/Hide Answer

No, WPF does not replace DirectX. DirectX will still be still needed to make cutting edge games.
performance of directX is still many times higher than WPF API. So when it comes to game develo
preference will be always DirectX and not WPF. WPF is not a optimum solution to make games, oh y
make a TIC TAC TOE game but not high action animation

One point to remember WPF is a replacement for windows form and not
 

How does hardware acceleration work with WPF?


Show/Hide Answer

Hardware acceleration is a process in which we use hardware to perform some functions rather than
those functions using the software which is running in the

WPF exploits hardware acceleration in a two tier manner.


WPF API first detects the level of hardware acceleration using parameters like RAM of video card , per
etc. Depending on that it either uses Tier 0, Tier 1 or Tier 2 renderin

Tier 0:- If the video card does not support hardware acceleration then WPF uses Tier 0 rendering mod
words it uses software acceleration. This corresponds to working of DirectX version less

Tier 1:- If the video card supports partial hardware acceleration then WPF uses Tier 1 rendering m
corresponds to working of DirectX version between 7.0 and

Tier 2:- If the video card supports hardware acceleration then WPF uses Tier 2 rendering mode. This c
to working of DirectX version equal or greater than
 

What is the need of WPF when we had GDI, GDI+ and DirectX?
Show/Hide Answer

 
First let’s try to understand how display technology has evolved in Microsoft t

User32:- This provides the windows look and feel for buttons and textboxes and other UI elements. Use
drawing c

GDI (Graphics device interface):- Microsoft introduced GDI to provide drawing capabilities. GD


provided drawing capabilities but also provided a high level of abstraction on the hardware display. In o
it encapsulates all complexities of hardware in the GDI

GDI+:- GDI+ was introduced which basically extends GDI and provides extra functionalities like jp
support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use
acceleration and did not have animation and 3D support.

Note: - Hardware acceleration is a process in which we use hardware to perform some


rather than performing those functions using the software which is running in
 

DirectX :- One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and
support. This came as a biggest disadvantage for game developers. To answer and server game
Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color
media streaming facility and lot more. This API no matured when it comes to gaming

WPF :- Microsoft almost had 3 to 4 API's for display technologies , so why a need for one mo
technology. DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to
elements like textboxes,button,grids etc using the DirectX technology by which they can exploit the
acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements b
one step further and develop special UI elements like Grid, FlowDocument, and Ellipse. Oh yes you
more step further and build animations.WPF is not meant for game development. DirectX still will le
scenario. In case you are looking for light animation ( not game programming ) WPF will be a choice. Y
express WPF using XML which is also called as XAML.In other words WPF is a wrapper which is built ov
So let’s define
 

WPF is a collection of classes that simplify building dynamic user interfaces. Those classes include a
controls, some of which mimic old UI elements (such as Label, TextBox, Button), and some that are ne
Grid, FlowDocument and
 

What kind of documents are supported in WPF?


Show/Hide Answer
There are two kind of major document supported in WPF Fixed format documents and Flow format
Fixed format documents look like PDF format. They display content regardless of screen size and reso
flow format document adjust depending on screen size and
Below is the code snippet for fixed format. You can see the document has a look of PDF reader. Step 1
tag to define a document and Step 2 shows how the documen
  
Figure .3:- Document viewer in action

How can we access XAML objects in behind code?


Show/Hide Answer
To access XAML objects in behind code you just need to define them with the same name as given in
document. For instance in the below code snippet we named the object as objtext and the object is d
the same name in the behind
  
Figure .2 Accessing XAML object

Can you explain how we can separate code and XAML?


Show/Hide Answer
This is one of the most important features of WPF, separating the XAML from the code to be handled
can independently work on the presentation of the application and developers can actually write t
independent of how the presentation
  
Figure .1:- XAML and behind code in action

Above is the code snippet, which shows a XAML file and the code completely detached from the XAML pr
order to associate a class with XAML file you need to specify the x: Class attribute. Any event specified o
object can be connected by defining a method with sender and event values. You can see from the abov
snippet we have linked the MyClickEvent to an event in the behind code.

Are XAML file compiled or built on runtime?


Show/Hide Answer
XAML files are usually compiled rather than parsing on runtime. But it also supports parsing during runt
build a XAML based project, you will see it creates g.cs extension in obi\Debug folder. Therefore, for e
you will find a g.cs file. For instance, a Shiv.XAML will have Shiv.g.cs file in obi\Debug folder. In short,
actually do not see the XAML file. But if you want to do runtime, parsing of XAML file it also allows that t

What are dependency properties?


Show/Hide Answer
These dependency properties belong to one class but can be used i
Consider the below code
  

<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="


 

Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is depend
as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas.

What is XAML?
Show/Hide Answer
XAML (pronounced as Zammel) is a declarative XML-based language by which you can define object an
XML. XAML document is loaded by a XAML parser. XAML parser instantiates objects and set there pro
describes objects, properties and there relation in between them. Using XAML, you can create any kind
means graphical or non-graphical. WPF parses the XAML document and instantiates the objects an
relation as defined by
So XAML is a XML document which defines objects and properties and WPF loads this document in actua

What is WPF?
Show/Hide Answer
Windows Presentation Foundation (Avalon was the code name for WPF) is the new presentation API in
a two and three dimensional graphics engine. It has the following
• Has all equivalent common user controls like buttons, check boxes
• Fixed and flow format
• Has all of the capabilities of HTML and
• 2D and 3D vector


• Data binding
What is WPF?

Windows Presentation Foundation (Avalon was the code name for WPF) is the new presentation API in WinFX. WPF is a two and
three dimensional graphics engine. It has the following capabilities:-
• Has all equivalent common user controls like buttons, check boxes sliders etc.
• Fixed and flow format documents 
• Has all of the capabilities of HTML and Flash 
• 2D and 3D vector graphics 
• Animation 
• Multimedia 
• Data binding 

What is XAML?

XAML (pronounced as Zammel) is a declarative XML-based language by which you can define object and properties in XML.
XAML document is loaded by a XAML parser. XAML parser instantiates objects and set there properties. XAML describes
objects, properties and there relation in between them. Using XAML, you can create any kind of objects that means graphical
or non-graphical. WPF parses the XAML document and instantiates the objects and creates the relation as defined by XAML.
So XAML is a XML document which defines objects and properties and WPF loads this document in actual memory.
What are dependency properties?

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. 

Are XAML file compiled or built on runtime?

XAML files are usually compiled rather than parsing on runtime. But it also supports parsing during runtime. When we build a
XAML based project, you will see it creates g.cs extension in obi\Debug folder. Therefore, for every XAMl file you will find a g.cs
file. For instance, a Shiv.XAML will have Shiv.g.cs file in obi\Debug folder. In short, in runtime you actually do not see the
XAML file. But if you want to do runtime, parsing of XAML file it also allows that to be done.

Can you explain how we can separate code and XAML?

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.

Figure .1:- XAML and behind code in action

Above is the code snippet, which shows a XAML file and the code completely detached from the XAML presentation. In order to
associate a class with XAML file you need to specify the x: Class attribute. Any event specified on the XAML object can be
connected by defining a method with sender and event values. You can see from the above code snippet we have linked the
MyClickEvent to an event in the behind code.

How can we access XAML objects in behind code?


To access XAML objects in behind code you just need to define them with the same name as given in the XAML document. For
instance in the below code snippet we named the object as objtext and the object is defined with the same name in the behind
code.

Figure .2 Accessing XAML object

What kind of documents are supported in WPF?

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.
Below is the code snippet for fixed format. You can see the document has a look of PDF reader. Step 1 defines the tag to define
a document and Step 2 shows how the document looks.

Figure .3:- Document viewer in action

Which namespace is used to work with 3D in WPF.


Posted by: Abhisek | Show/Hide Answer
The System.Windows.Media.Medi3D namespace is used to work with 3D.

What is 'One-way-to-Source ' binding property?


Posted by: Abhisek | Show/Hide Answer
In One-way-to-Source binding when the target property changes, the source object gets
updated.

What is the use of System.Windows.Navigation namespace in WPF?


Posted by: Abhisek | Show/Hide Answer
System.Windows.Navigation namespace contains different classes for navigation between
windows.
Which namespace provide classes to work with images, sound, video, etc?
Posted by: Abhisek | Show/Hide Answer
The System.Windows.Media namespace provide classes to work with images, sound, video, etc
in WPF.

The core classes for User Interface is located in which namespace?


Posted by: Abhisek | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct
answer.

Control class of WPF is derived from which class?


Posted by: Abhisek | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct
answer.

Which class is the base class of all the visual elements of WPF?
Posted by: Abhisek | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct
answer.

Which class of the WPF is the base class of all the user-interactive elements?
Posted by: Abhisek | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct
answer.

Which namespace provide classes for integration with WPF and Win32?
Posted by: Abhisek | Show/Hide Answer
The "System.Windows.Interop" namespace provides classes for integration of WPF with Win32.

What is the use of "System.Windows.Markup" namespace in WPF?


Posted by: Abhisek | Show/Hide Answer
The System.Windows.Markup namespace provides some helper classes for XAML code.

How to define a button USING XAML?


Posted by: Abhisek | Show/Hide Answer
To define a button in WPD using XAML use the following syntax, 

<Button Name="btnName">btnCaption</Button>

Example:- 

<Button Name="btnClick">Click Me</Button>

Here the <Button> element specifies the use of the Button class.

What is WPF?
Posted by: Abhisek | Show/Hide Answer
Microsoft has introduced WPF(Windows Presentation Foundation) API in .NET3.0 framework for
the first time. 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 functionalities you need to develop richer GUI applications. 

Using WPF we can develop GUI for both windows application and web application.

What is the use of System.Windows.Media namespace?


Posted by: Abhisek | Show/Hide Answer
It is the root namespace to several other media related namespaces. It provides
different types to work with animations, 3D rendering, text rendering and other
multimedia services.

What are the core WPF assemblies?


Posted by: Abhisek | Show/Hide Answer
The core WPF assemblies are, 

WindowsBase.dll:- It defines the core types constituting the infrastructure of WPF


API. 

PresentationCore.dll:- 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.

What is a Routed event?


Posted by: Blessybaby | Show/Hide Answer
In a typical 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.

what are dependency properties?


Posted by: Blessybaby | Show/Hide Answer
These are dependency properties that 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" /> 
4 7 9 
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’s used by the Rectangle to 
specify its position within Canvas.

What is XAML?
Posted by: Blessybaby | Show/Hide Answer
XAML (pronounced as Zammel) is a declarative XML-based language by which you
can 
define object and properties in XML. XAML document is loaded by a XAML parser. 
XAML parser instantiates objects and set there properties. XAML describes objects, 
properties and there relation in between them. Using XAML you can create any kind
of 
objects that means graphical or non-graphical. WPF parses the XAML document and 
instantiates the objects and creates the relation as defined by XAML.

What is WPF?
Posted by: Blessybaby | Show/Hide Answer
Windows Presentation Framework is the new 
presentation API in WinFX. WPF is a two and three dimensional graphics engine. It
has 
the following capabilities:- 
v Has all equivalent common user controls like buttons, check boxes sliders etc. 
v Fixed and flow format documents 
v Has all of the capabilities of HTML and Flash 
v 2D and 3D vector graphics 
v Animation 
v Multimedia 
v Data binding
Q: When should I use WPF instead of DirectX? (Is DirectX dead?)

DirectX is definitely not dead and is still more appropriate than WPF for advanced developers
writing hard-core “twitch games” or applications with complex 3D models where you need
maximum performance. That said, it’s easy to write a naive DirectX application that performs far
worse than a similar WPF application.
DirectX is a low-level interface to the graphics hardware that exposes all of the quirks of
whatever GPU a particular computer has. DirectX can be thought of as assembly language in
the world of graphics: You can do anything the GPU supports.
WPF provides a high-level abstraction that takes a description of your scene and
figures out the best way to render it, given the hardware resources available. Internally, this
might involve using Shader Model 3.0, or the fixed-function pipeline, or software. (Don’t worry if
you’re not familiar with these terms, but take it as a sign that you should be using WPF!).
The downside of choosing DirectX over WPF is a potentially astronomical increase in development
cost. A large part of this cost is the requirement to test your application on each
driver/GPU combination you intend to support. One of the major benefits of building on top of WPF
is that Microsoft has already done this testing for you! You can instead focus your
testing on low-end hardware for measuring performance. The fact that WPF applications can
even leverage the client GPU over Remote Desktop or in a partial-trust environment is also a
compelling differentiator.
Q: When should I use WPF instead of Windows Forms?(Is Windows Forms dead?)

WPF is clearly more suitable for applications with rich media, but some people have said that
Windows Forms is the best choice for business applications with traditional user interfaces. I think
this belief is based on first versions of WPF in which many standard controls didn’t exist (such as
TreeView, ListView, and OpenFileDialog) and a visual designer didn’t exist, making traditional
Windows application development in WPF harder than in Windows Forms. Although Windows
Forms still has useful controls that WPF lacks (such as DataGridView and PropertyGrid) and at the
time of writing has a larger set of third-party controls in the marketplace, WPF has compelling
features even for traditional user interfaces (such as the support for resolution independence or
advanced layout).

Q: When should I use WPF instead of Adobe Flash?

For creating rich web content, Flash is currently the most popular option because of its ubiquity.
You can put Flash-based content on a website with confidence that the overwhelming
majority of visitors already have the necessary player installed. (And if they don’t, it’s a very
quick download.)
WPF applications can also run within a web browser. WPF has the advantage of better development
tools and programming model, a richer feature set, robust control reuse, broad
programming language support, and full access to the underlying platform (when security
permits). But viewing such content requires Windows and the .NET Framework 3.0 (installed
by default on Windows Vista or later).

Q: How do I get a ToolTip to appear when hovering over a disabled element?

use the ShowOnDisabled attached property of the ToolTipService class! From


XAML, this would look like the following on a Button:
<Button ToolTipService.ShowOnDisabled=”True”>
</Button>
Or from C# code, you can call the static method corresponding to the attached property:
ToolTipService.SetShowOnDisabled(myButton, true);

Q: How can I forcibly close a ToolTip that is currently showing?

Set its IsOpen property to false.

Q: What’s the difference between ComboBox’s IsEditable and IsReadOnly properties?

Setting IsEditable to true turns ComboBox’s selection box into a text box. IsReadOnly controls whether that
text box can be edited, just like TextBox’s IsReadOnly property. This means that IsReadOnly is meaningless
unless IsEditable is true, and IsEditable being true doesn’t necessarily mean that the selection text can be
edited. Below in the table sums up thebehavior of ComboBox based on the values of these two properties.
The Behavior for All Combinations of IsEditable and IsReadOnly
IsEditabl IsReadOnl
Meaning
e y
The selection box displays a visual copy of the selected item and it doesn’t allow the typing o
false false
(The default behavior.)
false true Same as above.
true false The selection box displays a textual representation of the selected item and it allows the typi
text.
The selection box displays a textual representation of the selected item but it doesn’t allow t
true true
arbitrary text.
Q: When the SelectionChanged event gets raised, how do I get the new selection?

The SelectionChanged event is designed to handle controls that allow multiple selections,
so it can be a little confusing for a single-selection selector such as ComboBox. The
SelectionChangedEventArgs type passed to event handlers has two properties of type
IList: AddedItems and RemovedItems. AddedItems contains the new selection and
RemovedItems contains the previous selection.
e.g.
void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
object newSelection = e.AddedItems[0];
}
Like this code, never assume that there’s a selected item! Besides the fact that ComboBox’s
selection can be cleared programmatically, it can get cleared by the user when IsEditable is
true and IsReadOnly is false. In this case, if the user changes the selection box text to
something that doesn’t match any item, the SelectionChanged event is raised with an
empty AddedItems collection.

Q: Why should I bother wrapping items in a ComboBoxItem?

ComboBoxItem exposes some useful properties—IsSelected and IsHighlighted—and


useful events—Selected and Unselected. Using ComboBoxItem also avoids a quirky behavior with
showing content controls in the selection box (when IsEditable is false): If an item in a ComboBox
is a content control, the entire control doesn’t get displayed in the selection box. Instead, the inner
content is extracted and shown. By using ComboBoxItem as the outermost content control, the inner
content is now the entire control that you probably wanted to be displayed in the first place.
Because ComboBoxItem is a content control, it is also handy for adding simple strings to a
ComboBox (rather than using something like TextBlock or Label).

Q: How can I make ListBox arrange its items horizontally instead of vertically?

One way is to define a new control template, but all ItemsControls provide a shortcut with its ItemsPanel
property. ItemsPanel enables you to swap out the panel used to arrange items while leaving everything else
about the control intact. ListBox uses a panel called VirtualizingStackPanel to arrange its items vertically, but
the following code replaces it with a newVirtualizingStackPanel that explicitly sets its Orientation to
Horizontal:
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation=”Horizontal”/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
The translation of this XAML to procedural code is not straightforward, but here’s how you
can accomplish the same task in C#:
FrameworkElementFactory panelFactory =
new FrameworkElementFactory(typeof(VirtualizingStackPanel));
panelFactory.SetValue(VirtualizingStackPanel.OrientationProperty,
Orientation.Horizontal);
myListBox.ItemsPanel = new ItemsPanelTemplate(panelFactory);

Q: How can I get ListBox to scroll smoothly?

By default, ListBox scrolls on an item-by-item basis. Because the scrolling is based on each
item’s height, it can look quite choppy if you have large items. If you want smooth scrolling,
such that each scrolling action shifts the items by a small number of pixels regardless of
their heights, the easiest solution is to set the ScrollViewer.CanContentScroll attached
property to false on the ListBox.
Be aware, however, that by making this change you lose ListBox’s virtualization functionality.
Virtualization refers to the optimization of creating child elements only when they become
visible on the screen. Virtualization is only possible when using data binding to fill the
control’s items, so setting CanContentScroll to false can negatively impact the performance
of data-bound scenarios only.

Q: How can I sort items in a ListBox (or any other ItemsControl)?

Sorting can be done via a mechanism on the ItemsCollection object, so it applies equally to all ItemsControls.


ItemsCollection has a SortDescriptions property that can hold any number
of System.ComponentModel.SortDescription instances. Each SortDescription describes which property of the
items should be used for sorting and whether the sort is ascending or descending. For example, the
following code sorts a bunch of ContentControl items based on their Content property:
// Clear any existing sorting first
myItemsControl.Items.SortDescriptions.Clear();
// Sort by the Content property
myItemsControl.Items.SortDescriptions.Add(
new SortDescription(“Content”, ListSortDirection.Ascending));

Q: How do I get the items in my ItemsControl to have Automation IDs, as seen in tools like UISpy?

The easiest way to give any FrameworkElement an Automation ID is to set its Name property, as
that gets used by default for automation purposes. However, if you want to give an element an ID
that is different from its name, simply set the AutomationProperties.AutomationID attached
property (from the System.Windows.Automation namespace) to the desired string.

Q: How can I get items in a StatusBar to grow proportionally?

It’s common to want StatusBar panes that remain proportionately sized. For example,
perhaps you want a left pane that occupies 25% of the StatusBar’s width and a right pane
that occupies 75% of the width. This can be done by overriding StatusBar’s ItemsPanel with
a Grid and configuring the Grid’s columns appropriately.

Q: How can I make TextBox support multiple lines of text?

Setting AcceptsReturn to true allows users to press the Enter key to create a new line of
text. Note that TextBox always supports multiple lines of text programmatically. If its Text is
set to a string containing NewLine characters, it displays the multiple lines regardless of the
value of AcceptsReturn. Also, the multiline support is completely independent from text
wrapping. Text wrapping only applies to individual lines of text that are wider than the
TextBox.
Q: What unit of measurement is used by WPF?

All absolute measurements, such as the numbers used in this section’s size-related properties,
are specified in device-independent pixels. These “logical pixels” are meant to represent
1/96th of an inch, regardless of the screen’s DPI setting. Note that device-independent
pixels are always specified as double values, so they can be fractional.
The exact measurement of 1/96th of an inch isn’t important, although it was chosen
because on a typical 96 DPI display, one device-independent pixel is identical to one physical
pixel. Of course, the notion of a true “inch” depends on the physical display device. If an
application draws a one-inch line on my laptop screen, that line will certainly be longer than
one inch if I hook up my laptop to a projector!

Q: Where’s the entry point in WPF application?

When you create a WPF Windows Application in Visual Studio, the generated project has no Main
method, yet it still runs as expected! In fact, even attempting to add a Main method
gives a compilation error telling you that it is already defined.
Application is special-cased when it is compiled from XAML, because Visual Studio assigns
the XAML file a Build Action of ApplicationDefinition. This causes a Main method to be
autogenerated.

Q: How do I retrieve command-line arguments in my WPF application?

Command-line arguments are typically retrieved via a string array parameter passed to Main,
but the common way to define WPF applications doesn’t allow you to implement the Main
method. You can get around this in two different ways. One way is to forego defining an
Application-derived class in XAML, so you can manually define the Main method with a
string array parameter. The easier way, however, is to simply call
System.Environment.GetCommandLineArgs at any point in your application, which returns
the same string array you’d get inside Main.

Q: What is BAML?

BAML, which stands for Binary Application Markup Language, is simply XAML that has been
parsed, tokenized, and converted into binary form. Although any chunk of XAML can be
represented by procedural code, the XAML-to-BAML compilation process does not generate
procedural source code. So, BAML is not like Microsoft intermediate language (MSIL); it is a
compressed declarative format that is faster to load and parse (and smaller in size) than plain
XAML. BAML is just an implementation detail of the XAML compilation process without any
direct public exposure, so it could be replaced with something  different in the future. Nevertheless,
it’s interesting to be aware of its existence.

Q: Can BAML be decompiled back into XAML?

Sure, because an instance of any public .NET class can be serialized as XAML, regardless of
how it was originally declared. The first step is to retrieve an instance that you want to be the
root. If you don’t already have this object, you can call the static
System.Windows.Application.LoadComponent method as follows:
System.Uri uri = new System.Uri(“MyWindow.xaml”, System.UriKind.Relative);
Window window = (Window)Application.LoadComponent(uri);
This differs from previous code that uses FileStream to load a .xaml file because with
LoadComponent, the name specified as the Uniform Resource Identifier (URI) does not have
to physically exist as a standalone .xaml file. LoadComponent can automatically retrieve
BAML embedded as a resource when given the appropriate URI (which, by MSBuild convention,
is the name of the original XAML source file). In fact, Visual Studio’s autogenerated
InitializeComponent method calls Application.LoadComponent to load embedded BAML,
although it uses a different overload.
After you’ve gotten a hold of the root element instance, you can use the
System.Windows.Markup.XamlWriter class to get a XAML representation of the root
element (and, therefore, any of its children). XamlWriter contains five overloads of a static
Save method, the simplest of which accepts an object instance and returns appropriate
XAML as a string. For example:
string xaml = XamlWriter.Save(window);
It might sound a little troubling that BAML can be so easily “cracked open,” but it’s really no
different from any other software running locally or displaying UI locally. (For example, you can
easily dig into a website’s HTML, JavaScript, and Cascading Style Sheets [CSS] files.)

Q: What are possible ways to implement distributed applications in .NET?

.NET Remoting and ASP.NET Web Services.

Q: Can you create Windows Service Using WPF?

No, you can not build the windows Services using WPF. WPF is presentation technolgy, where as
Windows service requires certain permission to perform the certain GUI retalted operations.
If the Windows service does not have the appropriate permissions, there may be unexpected results.

Q: What is WPF?

Windows Presentation Foundation (WPF) is a next-generation presentation system for building


Windows client applications with visually stunning user experiences. With WPF, you can create a
wide range of both standalone and browser-hosted applications.

Q: What is XAML?

XAML is used extensively in .NET Framework 3.0 technologies, particularly in Windows


Presentation Foundation (WPF) . In WPF, XAML is used as a user interface markup language to
define UI elements, data binding, eventing, and other features. In WF, workflows can be defined
using XAML.
XAML elements map directly to common language runtime object instances, while XAML
attributes map to Common Language Runtime properties and events on those objects. XAML files
can be created and edited with visual design tools such as Microsoft Expression Blend, Microsoft
Visual Studio, and the hostable Windows Workflow Foundation visual designer.

Q: What is XBAP?

XBAP stands for XAML Browser Application. XBAP allows for WPF applications to be used
inside a browser. The .NET framework is required to be installed on the client system. Hosted
applications run in a partial trust sandbox environment. They are not given full access to the
computer's resources and not all of WPF functionality is available.
WPF supports the creation of applications that run directly in a web browser. (So will WPF/E, when it is
released.) They are called XAML Browser Applications (XBAPs), and have a.xbap file extension.
The power of this WPF support is that the exact same programming model is used for a XAML Browser
Application as for a standard Windows application. Therefore, creating an XBAP isn’t much different than
creating a standard Windows application. The main differences are as follows:
. Not all features in WPF or the .NET Framework are accessible (by default).
. Navigation is integrated into the browser (for Internet Explorer 7 or later).
. Deployment is handled differently.

Q: What is a Routed event?

In a typical 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. 

You might also like