You are on page 1of 557

List of available projects - HTTrack Website Copier

HTTrack Website Copier - Open Source offline browser

Index of locally available projects:



WPF TUTORIALS 2

· wpftutorial.net

Mirror and index made by HTTrack Website Copier [XR&CO'2008]

© 2008 Xavier Roche & other contributors - Web Design: Leto Kauler.

index.html[2/16/2014 2:22:30 PM]


WPF Tutorial

Home Share... Feed About Christian Moser


   
     

Home

WPF Inspector Welcome to the WPF Tutorial Tip of the Day

Getting started
Setting a local value on a
Fundamentals dependency property clears an
eventually set binding. Use
User Experience
SetCurrentValue() in .NET 4.0
Patterns to work around this issue.

Controls

Custom Controls Popular Articles


Layout
Learn WPF in two Weeks
Input
Introduction to WPF
Data Binding
DataGrid
Styling
Create a simple WPF
Localization application
Interaction XAML
Resources Grid Panel
2D Graphics Dependency Properties
Welcome to my website about the Windows Presentation Foundation. The tutorials will
3D Graphics Development Tools
show you how to create the next generation user experience. I hope you will get amazed
Animation by the possibilities of this fascinating technology.

Multimedia
Latest Articles
Documents
(2013/11/01)
XAML
Windows 7
WPF Inspector
Interoperability
List of 3rd-Party Controls
Performance
Query Screen Resolutions
Expression Blend
Books
Tools
XAML Inspector is the successor of WPF Inspector. It makes all the features you love from
Undo/Redo
UI Automation this tool available on all XAML platforms.

To learn more visit: www.xamlinspector.com Grid Panel

Introduction to WPF

index.html[2/16/2014 2:23:07 PM]


WPF Tutorial

Copyright (c) by Christian Moser, 2011.

index.html[2/16/2014 2:23:07 PM]


WPF Tutorial

Home Share... Feed About Christian Moser


   
     

Home

WPF Inspector Welcome to the WPF Tutorial Tip of the Day

Getting started
A shared Freezable inherits its
Fundamentals DataContext from the
resource dictionary its defined
User Experience
in, whereas a non-shared
Patterns Freezable inherits it from the
place in the VisualTree its
Controls inserted.
Custom Controls

Layout
Popular Articles
Input

Data Binding
Learn WPF in two Weeks

Styling
Introduction to WPF

Localization
DataGrid

Interaction
Create a simple WPF
application
Resources
XAML
2D Graphics
Grid Panel
Welcome to my website about the Windows Presentation Foundation. The tutorials will
3D Graphics
show you how to create the next generation user experience. I hope you will get amazed Dependency Properties
Animation by the possibilities of this fascinating technology.
Development Tools
Multimedia

Documents
(2013/11/01)
Latest Articles
Windows 7

Interoperability XAML

Performance WPF Inspector

Expression Blend List of 3rd-Party Controls

Tools Query Screen Resolutions


XAML Inspector is the successor of WPF Inspector. It makes all the features you love from
UI Automation this tool available on all XAML platforms. Books

To learn more visit: www.xamlinspector.com Undo/Redo

Grid Panel

Home.html[2/16/2014 2:23:26 PM]


WPF Tutorial
Introduction to WPF

Copyright (c) by Christian Moser, 2011.

Home.html[2/16/2014 2:23:26 PM]


Christian Moser's WPF Tutorial.net


News and tutorials around the Windows Presentation Foundation
en
http://www.wpftutorial.net
Sun, 16 Feb 2014
08:23:05 +0100
moc@zuehlke.com (Christian Moser)
<h1>Introduction to XAML</h1>
<p>XAML stands for
Extensible Application Markup Language. Its a simple language based on XML to create and initialize .NET objects
with hierarchical relations. Altough it was originally invented for WPF it can by used to create any kind of object trees.
</p>
<p>Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF and for electronic
paper in the XPS standard.</p>
<p>All classes in WPF have parameterless constructors and make excessive usage of
properties. That is done to make it perfectly fit for XML languages like XAML.</p>
<h2>Advantages of XAML</h2>

<p>All you can do in XAML can also be done in code. XAML ist just another way to create and initialize objects. You
can use WPF without using XAML. It's up to you if you want to declare it in XAML or write it in code. Declare your
UI in XAML has some advantages:</p>
<ul>
<li>XAML code is short and clear to read</li>
<li>Separation of
designer code and logic</li>
<li>Graphical design tools like Expression Blend require XAML as source.</li>
<li>The
separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.</li>
</ul>

<h2>XAML vs. Code</h2>
<p>As an example we build a simple StackPanel with a textblock and a button in XAML
and compare it to the same code in C#.</p>
<div class="codeblock"><pre class="xaml xaml" style="font-family:
courier new,courier,monospace;"> <span style="color: #800000;"><span style="color:
#800000;">&lt;StackPanel<span style="color: #800000;">&gt;</span></span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;TextBlock</span> <span style="color: #ff0000;">Margin</span>=
<span style="color: #0000ff;">&quot;20&quot;</span><span style="color: #800000;">&gt;</span></span>Welcome
to the World of XAML<span style="color: #800000;"><span style="color: #800000;">&lt;/TextBlock<span
style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;Button</span> <span style="color: #ff0000;">Margin</span>=<span style="color:
#0000ff;">&quot;10&quot;</span> <span style="color: #ff0000;">HorizontalAlignment</span>=<span style="color:
#0000ff;">&quot;Right&quot;</span><span style="color: #800000;">&gt;</span></span>OK<span style="color:
#800000;"><span style="color: #800000;">&lt;/Button<span style="color: #800000;">&gt;</span></span></span>

<span style="color: #800000;"><span style="color: #800000;">&lt;/StackPanel<span style="color: #800000;">&gt;
</span></span></span>
</pre></div><p>The same expressed in C# will look like this:</p>
<div class="codeblock">
<pre class="csharp csharp" style="font-family: courier new,courier,monospace;"> <span style="color: #008000;">//
Create the StackPanel</span>
StackPanel stackPanel <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> StackPanel<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
<span style="color: #0600FF; font-weight: bold;">this</span>.<span style="color:
#0000FF;">Content</span> <span style="color: #008000;">=</span> stackPanel;
<span style="color: #008000;">//
Create the TextBlock</span>
TextBlock textBlock <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> TextBlock<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
textBlock.<span style="color: #0000FF;">Margin</span> <span style="color: #008000;">=
</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-
weight: bold;">new</span></a> Thickness<span style="color: #000000;">&#40;</span><span style="color:
#FF0000;">10</span><span style="color: #000000;">&#41;</span>;
textBlock.<span style="color:
#0000FF;">Text</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Welcome to
the World of XAML&quot;</span>;
stackPanel.<span style="color: #0000FF;">Children</span>.<span style="color:
#0000FF;">Add</span><span style="color: #000000;">&#40;</span>textBlock<span style="color: #000000;">&#41;
</span>;
<span style="color: #008000;">// Create the Button</span>
Button button <span style="color: #008000;">=
</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-
weight: bold;">new</span></a> Button<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
button.<span style="color: #0000FF;">Margin</span><span style="color: #008000;">=
</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-
weight: bold;">new</span></a> Thickness<span style="color: #000000;">&#40;</span><span style="color:
#FF0000;">20</span><span style="color: #000000;">&#41;</span>;
button.<span style="color:
#0000FF;">Content</span> <span style="color: #008000;">=</span> <span style="color:
#666666;">&quot;OK&quot;</span>;
stackPanel.<span style="color: #0000FF;">Children</span>.<span style="color:
#0000FF;">Add</span><span style="color: #000000;">&#40;</span>button<span style="color: #000000;">&#41;
</span>;
</pre></div><p>As you can see is the XAML version much shorter and clearer to read. And that's the power

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

of XAMLs expressiveness.</p>
<h2>Properties as Elements</h2>
<p>Properties are normally written inline as known
from XML <code>&lt;Button Content="OK" /&gt;</code>. But what if we want to put a more complex object as
content like an image that has properties itself or maybe a whole grid panel? To do that we can use the property element
syntax. This allows us to extract the property as an own child element.</p>
<div class="codeblock"><pre class="xaml
xaml" style="font-family: courier new,courier,monospace;"> <span style="color: #800000;"><span style="color:
#800000;">&lt;Button<span style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;">
<span style="color: #800000;">&lt;Button</span>.Content<span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;Image</span> <span style="color:
#ff0000;">Source</span>=<span style="color: #0000ff;">&quot;Images/OK.png&quot;</span> <span style="color:
#ff0000;">Width</span>=<span style="color: #0000ff;">&quot;50&quot;</span> <span style="color:
#ff0000;">Height</span>=<span style="color: #0000ff;">&quot;50&quot;</span> <span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/Button</span>.Content<span style="color: #800000;">&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/Button<span style="color: #800000;">&gt;</span></span></span>
</pre></div>
<h2>Implicit Type conversion</h2>
<p>A very powerful construct of WPF are implicit type converters.
They do their work silently in the background. When you declare a
BorderBrush, the word "Blue" is only a string. The
implicit <code>BrushConverter</code> makes a <code>System.Windows.Media.Brushes.Blue</code> out of it. The
same regards to the border thickness that is beeing converted implicit into a <code>Thickness</code> object. WPF
includes a lot of type converters for built-in classes, but you can also write type converters for your own classses.</p>

<div class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span
style="color: #800000;"><span style="color: #800000;">&lt;Border</span> <span style="color:
#ff0000;">BorderBrush</span>=<span style="color: #0000ff;">&quot;Blue&quot;</span> <span style="color:
#ff0000;">BorderThickness</span>=<span style="color: #0000ff;">&quot;0,10&quot;</span><span style="color:
#800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/Border<span
style="color: #800000;">&gt;</span></span></span>
</pre></div>
<h2>Markup Extensions</h2>
<p>Markup
extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime.
Markup extensions are surrouded by curly braces (Example: <code>Background="{StaticResource
NormalBackgroundBrush}"</code>). WPF has some built-in markup extensions, but you can write your own, by
deriving from <code>MarkupExtension</code>. These are the built-in markup extensions: <ul>
<li><b>Binding</b>
<br/>To bind the values of two properties together.</li>
<li><b>StaticResource</b><br/>One time lookup of a resource
entry</li>
<li><b>DynamicResource</b><br/>Auto updating lookup of a resource entry</li>
<li>
<b>TemplateBinding</b><br/>To bind a property of a control template to a dependency property of the control</li>
<li><b>x:Static</b><br/>Resolve the value of a static property.</li>
<li><b>x:Null</b><br/>Return
<code>null</code></li>
</ul>
The first identifier within a pair of curly braces is the name of the extension. All
preciding identifiers are named parameters in the form of Property=Value.
The following example shows a label whose
<code>Content</code> is bound to the <code>Text</code> of the textbox. When you type a text into the text box, the
text property changes and the binding markup extension automatically updates the content of the label.
</p>
<div
class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color:
#800000;"><span style="color: #800000;">&lt;TextBox</span> <span style="color: #ff0000;">x:Name</span>=<span
style="color: #0000ff;">&quot;textBox&quot;</span><span style="color: #800000;">/&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;Label</span> <span style="color:
#ff0000;">Content</span>=<span style="color: #0000ff;">&quot;{Binding Text, ElementName=textBox}&quot;
</span><span style="color: #800000;">/&gt;</span></span>
</pre></div>
<h2>Namespaces</h2>
<p>At the
beginning of every XAML file you need to include two namespaces. <br/>The first is
<code>http://schemas.microsoft.com/winfx/2006/xaml/presentation</code>. It is mapped to all wpf controls in
<code>System.Windows.Controls</code>. <br/>The second is
<code>http://schemas.microsoft.com/winfx/2006/xaml</code> it is mapped to
<code>System.Windows.Markup</code> that defines the XAML keywords.<br/>
The mapping between an XML
namespace and a CLR namespace is done by the <code>XmlnsDefinition</code> attribute at assembly level. You can
also directly include a CLR namespace in XAML by using the <code>clr-namespace:</code> prefix.</p>
<div
class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color:
#800000;"><span style="color: #800000;">&lt;Window</span> <span style="color: #ff0000;">xmlns</span>=<span
style="color: #0000ff;">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span></span>

<span style="color: #800000;"><span style="color: #ff0000;">xmlns:x</span>=<span style="color:

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

#0000ff;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span><span style="color: #800000;">&gt;


</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/Window<span style="color:
#800000;">&gt;</span></span></span>
</pre></div>
http://www.wpftutorial.net/XAML.html
Sun, 16 Feb 2014
08:23:05 +01002013-12-13 09:08:46
moc@zuehlke.com (Christian Moser)
<table cellpadding="0" cellspacing="0">
<tr>
<td style="width: 511px; padding-bottom: 20px; vertical-align: top;">
<h1>Welcome to the WPF Tutorial</h1>

<img src="images/title.jpg" style="width: 400px; height: 349px; padding-left: 30px;" />
<p style="padding-top: 20px;
padding-right: 10px; padding-left: 0px;">Welcome to my website about the Windows Presentation Foundation. The
tutorials will show you how to create the next generation user experience. I hope you will get amazed by the
possibilities of this fascinating technology.</p>
<br/>
[news]
</td>
<td rowspan="2" style="padding-left: 30px;
margin-top: 10px; vertical-align: top; border-left: #eeeeee 1px solid;" >
[tipofday]
[popular]
</td>
</tr>
</table>
http://www.wpftutorial.net/Home.html
Sun, 16 Feb 2014 08:23:05 +01002013-11-01 12:06:36
moc@zuehlke.com
(Christian Moser)
<h1>WPF Inspector</h1>
<h2>NEW: XAML Inspector - cross platform visual Debugging</h2>

<p>Have a look at XAML inspector. The successor of WPF Inspector. It brings all the features of WPF Inspector to all
XAML platofrms (WPF, Silveright, WinRT and Windows Phone).</p>
<p>Visit project page: <a
href="http://www.xamlinspector.com" target="_blank">www.xamlinspector.com</a></p>
<img
src="images/inspector_ad.jpg" />
<p>WPF Inspector is a utility that attaches to a running WPF application to
troubleshoot common problems with layouting, databinding or styling. WPF Inspector allows you to explore a live
view of the logical- and visual tree, read and edit property values of elements, watch the data context, debug triggers,
trace styles and much more. Since March 2011, WPF Inspector is open source and available on CodePlex.</p>
<a
href="http://wpfinspector.codeplex.com/">Download WPF Inspector from CodePlex</a>
<br/><br/>

http://www.wpftutorial.net/Inspector.html
Sun, 16 Feb 2014 08:23:05 +01002013-10-17 13:47:17
moc@zuehlke.com
(Christian Moser)
<h1>WPF - Third Party Controls</h1> <h2>WPF Component Vendors</h2> <ul> <li><a
href="http://www.mindscapehq.com/products/wpfelements">Mindscape</a></li> <li><a
href="http://www.componentart.com/products/wpf/navigation/">Component Art</a></li> <li><a
href="http://www.devexpress.com/Products/NET/Controls/WPF/">DevExpress</a></li> <li><a
href="http://www.syncfusion.com/products/user-interface-edition/wpf">SyncFusion</a></li> <li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf.aspx#Overview">Infragistics</a></li> <li><a
href="http://xceed.com/pages/TopMenu/Products/ProductSearch.aspx?Lang=EN-CA&Category=0617b4dd-af9a-4e34-
a1a1-d1129237d614">Xceed</a></li> <li><a href="http://www.telerik.com/products/wpf.aspx">Telerik</a></li> <li>
<a href="http://www.actiprosoftware.com/Products/DotNet/WPF/WPFStudio/Default.aspx">Actipro</a></li> <li><a
href="http://www.divil.co.uk/net/controls/wpf.aspx">divelements</a></li> <li><a
href="http://www.binarymission.co.uk/">Binary Mission</a></li> <li><a href="http://www.e-iceblue.com/">Ice
Blue</a></li> </ul> <hr> <table> <tr> <td style="vertical-align: top; width: 300px;"> <h2>Bar Code</h2> <ul> <li>
<a href="http://www.neodynamic.com/Products/Barcode-WPF/Barcode_wpf_Feature_Details.aspx">Neodynamics
BarCode</a></li> <li><a
href="http://www.actiprosoftware.com/Products/DotNet/WPF/BarCode/Default.aspx">Actipro BarCode</a></li>
</ul> <h2>Data Grids</h2> <ul> <li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamdatagrid.aspx#Overview">Infragistics Data Grid</a>
</li> <li><a href="http://xceed.com/Grid_WPF_New.html">Xceed Data Grid</a></li> <li><a
href="http://www.componentone.com/SuperProducts/GridWPF/ ">Component One Data Grid</a></li> <li><a
href="http://www.syncfusion.com/products/user-interface-edition/wpf/grid">Syncfusion Essential Grid</a></li> <li>
<a href="http://www.telerik.com/products/wpf/gridview.aspx">Telerik RadGridView for WPF</a></li> <li><a
href="http://www.componentart.com/products/wpf/datagrid/">ComponentArt DataGrid</a></li> <li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/data-grid">Mindscape Datagrid</a></li> </ul>
<h2>CAD</h2> <ul> <li><a href="http://code.google.com/p/tf-net/">Topology Framework .NET</a></li> <li><a
href="http://www.devdept.com/products/eyeshot/">Eyeshot</a></li> <li><a href="http://www.mono-
project.com/GtkSharp">Mono GtkSharp</a></li> <li><a href="http://www.woutware.com/cadlib3.5.html">CadLib 3.5
DWG DXF .NET Library</a></li> <li><a href="http://www.geometros.com/sgcore/review.htm">sgCode</a></li>
<li><a href="http://www.seedrawex.com/">SeeDraw</a></li> </ul> <h2>Charts</h2> <ul> <li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamchart.aspx#Overview ">Infragistics xamChart</a>
</li> <li><a href="http://sourceforge.net/projects/swordfishcharts">Swordfish Charts</a></li> <li><a
href="http://www.componentone.com/SuperProducts/ChartWPF/ ">Component One Chart</a></li> <li><a
href="http://www.visifire.com/">Visifire Chart for WPF and Silverlight</a></li> <li><a
href="http://www.codeproject.com/KB/WPF/wpfgraph.aspx">WPF Graph on Code Project</a></li> <li><a

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

href="http://www.codeproject.com/KB/WPF/WPF_3D_Bar_chart_control.aspx">Free 3D Chart</a></li> <li><a


href="http://www.codeproject.com/KB/WPF/WPFChart3D.aspx">Free High Performance 3D Chart</a></li> <li><a
href="http://dynamicdatadisplay.codeplex.com/">D3 Dynamic Data Display</a></li> <li><a
href="http://www.syncfusion.com/products/user-interface-edition/wpf/chart">Syncfusion Essential Chart</a></li> <li>
<a href="http://www.syncfusion.com/products/user-interface-edition/wpf/gauge">Syncfusion Gauge</a></li> <li><a
href="http://www.telerik.com/products/wpf/gauge.aspx">Telerik RadGauge for WPF</a></li> <li><a
href="http://www.telerik.com/products/wpf/chart.aspx">Telerik RadChart for WPF</a></li> <li><a
href="http://www.componentart.com/products/wpf/charting/">ComponentArt Chart</a></li> <li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-bar-chart">Mindscape Chart</a></li> <li><a
href="http://www.softwarefx.com/sfxNetProducts/ChartFX/wpf/">ChartFX for WPF</a></li> <li><a
href="http://www.nextwavesoft.com/products/nextwave-chart-for-wpf">NextWave Chart for WPF</a></li> <li><a
href="http://www.nextwavesoft.com/products/nextwave-gauge-for-wpf">NextWave Gauge for WPF</a></li> </ul>
<h2>Color Picker</h2> <ul> <li><a href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-color-
picker">Mindscape Color Picker</a></li> <li><a
href="http://www.telerik.com/products/wpf/colorpicker.aspx">Telerik Color Picker</a></li> <li><a
href="http://wpfcolorpicker.codeplex.com/">Free Color Picker (CodePlex)</a></li> <li><a
href="http://www.componentone.com/SuperProducts/ColorPickerWPF/">Component One Color Picker</a></li> </ul>
<h2>Diagram Editors</h2> <ul> <li><a href="http://visualizationtools.net/default/productsoverview/">Orbifold
Visualizers</a></li> <li><a href="http://www.syncfusion.com/products/user-interface-
edition/wpf/diagram">Syncfusion Essential Diagram Editor</a></li> </ul> <h2>Dialogs and Windows</h2> <ul> <li>
<a href="http://wpfdialogs.codeplex.com/">Pure WPF FileOpen, FileSave and FolderBrowser Dialogs</a></li> <li><a
href="http://www.divil.co.uk/net/controls/sandshellwpf/">divelements Shell</a></li> </ul> <h2>Dock</h2> <ul> <li>
<a <li><a href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamdockmanager.aspx#Overview ">Infragistics
Dock Manager</a></li> <li><a
href="http://www.actiprosoftware.com/Products/DotNet/WPF/Docking/Default.aspx">Actipro Dock Panel</a></li>
<li><a href="http://www.devcomponents.com/dotnetbar-wpf/">DevComponents Dock Panel</a></li> <li><a
href="http://sourceforge.net/projects/wpfdockinglib/">WPF Docking Library (Open Source)</a></li> <li><a
href="http://avalondock.codeplex.com">Avalon Dock (Open Source)</a></li> <li><a
href="http://www.telerik.com/products/wpf/docking.aspx">Telerik RadDocking for WPF</a></li> <li><a
href="http://www.divil.co.uk/net/controls/sanddockwpf/screenshots.aspx">divelements Dock</a></li> </ul>
<h2>Editors</h2> <ul> <li><a href="http://www.infragistics.com/dotnet/netadvantage/wpf/xameditors.aspx#Overview
">Infragistics xamEditors</a></li> <li><a href="http://xceed.com/Editors_WPF_Intro.html">Xceed Editors</a></li>
<li><a href="http://www.devcomponents.com/dotnetbar-wpf/WPFNumericDoubleInput.aspx ">DevComponents
Numeric Editor</a></li> <li><a href="http://www.telerik.com/products/wpf/numericupdown.aspx">Telerik
RadNumericUpDown for WPF</a></li> <li><a href="http://www.syncfusion.com/products/user-interface-
edition/wpf/edit">Syncfusion Essential Edit (with Syntax Highlighting)</a></li> <li><a
href="http://wpfcalendarcontrol.codeplex.com/">WPF Calendar Control</a></li> <li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-rich-text-toolbar">Mindscape Rich Text
Editor</a></li> <li><a href="http://www.telerik.com/products/wpf/image-editor.aspx">Telerik Image Editor</a></li>
</ul> <h2>Effects</h2> <ul> <li><a href="http://www.codeplex.com/transitionals">Transitionals - Framework to
transition between screens.</li> <li><a href="http://www.codeplex.com/fx">WPF Shader and Transition FX</a></li>
<li><a href="http://www.codeplex.com/wpffx">Windows Presentation Foundation Pixel Shader Effects Library</a>
</li> <li><a href="http://www.codeplex.com/dotwaywpf">DotWay WPF - Color Picker, Panels and several Shader
Effects</a></li> <li><a href="http://www.telerik.com/products/wpf/drag-drop.aspx">Telerik Drag&amp;Drop for
WPF</a></li> </ul> <h2>GIS and Maps</h2> <ul> <li><a href="http://resources.arcgis.com/content/arcgis-api-
silverlightwpf/1.2/about">ESRI ArcGIS Controls for WPF</a></li> <li><a
href="http://vewpf.codeplex.com/">Microsoft Virual Earth Control</a></li> <li><a
href="http://wpfsharpmapcontrols.codeplex.com/">Sharp Map Control</a></li> </ul> <h2>Multimedia</h2> <ul>
<li><a href="http://directshownet.sourceforge.net/">DirectShowLib - .NET Wrapper for DirectShow</a></li> <li><a
href="http://videorendererelement.codeplex.com/">VideoRenderElement</a></li> <li><a
href="http://wpfcap.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=13380#ReleaseFiles">Webcam
Control</a></li> <li><a href="http://www.codeplex.com/WPFMediaKit">WPF Media Kit - DVD Player, DirectShow,
WebCam</li> </ul> </td> <td style="padding-left: 40px; vertical-align: top;"> <h2>Misc</h2> <ul> <li><a
href="http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=15598">WPF Toolkit</a></li> <li><a

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamTabControl.aspx#Overview ">Infragistics Tab


Control</a></li> <li><a href="http://www.mindscape.co.nz/products/wpfflowdiagrams/">Mindscape Flow
Diagrams</a></li> </ul> <h2>Office Components</h2> <ul> <li><a href="http://www.e-iceblue.com/Introduce/word-
for-wpf-introduce.html">Spire.DOC for WPF</a></li> <li><a href="http://www.e-iceblue.com/Introduce/excel-for-
wpf-introduce.html">Spire.XLS for WPF</a></li> </ul> <h2>Outlook Bar</h2> <ul> <li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamOutlookBar.aspx#Overview ">Infragistics Outlook
Bar</a></li> <li><a href="http://www.actiprosoftware.com/Products/DotNet/WPF/Navigation/Default.aspx">Actipro
Outlook Bar</a></li> <li><a href="http://www.devcomponents.com/dotnetbar-
wpf/NavigationPane.aspx">DevComponents Outlook Bar</a></li> <li><a
href="http://www.codeproject.com/KB/WPF/WPFOutlookBar.aspx">Odyssey Outlook Bar</a></li> <li><a
href="http://www.codeproject.com/KB/WPF/WPFExplorerBar.aspx">Odyssey Explorer Bar</a></li> <li><a
href="http://www.telerik.com/products/wpf/outlookbar.aspx">Telerik RadOutlookBar for WPF</a></li> <li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-outlook-bar">Mindscape Outlook Bar</a>
</li> <li><a href="http://www.componentone.com/SuperProducts/OutlookBarWPF/">Component One Outlook
Bar</a></li> </ul> <h2>Panels</h2> <ul> <li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamcarouselpanel.aspx#Overview">Infragistics Carousel
Panel</a></li>
<li><a href="http://www.telerik.com/products/wpf/carousel.aspx">Telerik WPF Carousel Control</a>
</li>
<li><a href="http://www.telerik.com/products/wpf/tileview.aspx">Telerik RadTileView for WPF</a></li>
<li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-coverflow-control">Mindscape Coverflow
Control</a></li>
<li><a href="http://www.telerik.com/products/wpf/virtualizingwrappanel.aspx">Telerik Virtualizing
Wrap Panel</a></li>
<li><a href="http://www.componentone.com/SuperProducts/HyperPanelWPF/">Component One
HyperPanel</a></li>
</ul>
<h2>Progress Bars</h2>
<ul>
<li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-progress-bar">Mindscape Progress Bar</a>
</li>
</ul>
<h2>Property Grids</h2>
<ul>
<li><a
href="http://www.actiprosoftware.com/Products/DotNet/WPF/PropertyGrid/Default.aspx">Actipro Property Grid</a>
</li>
<li><a href="http://www.mindscape.co.nz/products/WpfPropertyGrid/default.aspx">Mindscape Property
Grid</a></li>
<li><a href="http://www.componentone.com/SuperProducts/PropertyGridWPF/">Component One
Property Grid</a></li>
</ul>
<h2>PDF &amp; Reporting</h2>
<ul>
<li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf/reporting.aspx#Overview
">Infragistics Reporting for
WPF</a></li>
<li><a href="http://www.componentone.com/SuperProducts/ReportsWPF/">Component One
Reports</a></li>
<li><a href="http://www.componentone.com/SuperProducts/PdfViewerWPF/">Component One PDF
Viewer</a></li>
<li><a href="http://www.e-iceblue.com/Introduce/pdf-viewer-wpf.html">IceBlue PDF Viewer</a>
</li>
<li><a href="http://www.e-iceblue.com/Introduce/pdf-for-wpf-introduce.html">IceBlue PDF for WPF</a></li>
<li><a href="http://www.o2sol.com/pdfview4net/overview.htm">o2sol PDFView4NET</a></li>
</ul>

<h2>Ribbon</h2>
<ul>
<li><a href="http://fluent.codeplex.com">Fluent Ribbon Control Suite</a></li> <li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamRibbon.aspx#Overview">Infragistics Ribbon</a></li>

<li><a href="http://www.actiprosoftware.com/Products/DotNet/WPF/Ribbon/Default.aspx">Actipro Ribbon</a></li>
<li><a href="http://www.devcomponents.com/dotnetbar-wpf/wpfribbon/
">DevComponents Ribbon</a></li>
<li><a
href="http://www.codeproject.com/KB/WPF/OdysseyRibbonBar.aspx">Odyssey Ribbon</a></li>
<li><a
href="http://www.telerik.com/products/wpf/ribbonbar.aspx">Telerik WPF UI RibbonBar</a></li>
<li><a
href="http://windowsclient.net/wpf/wpf35/wpf-35sp1-ribbon-walkthrough.aspx">Free Microsoft WPF Ribbon
Control</a></li>
<li><a href="http://www.divil.co.uk/net/controls/sandribbonwpf/">divelements Ribbon</li></a>
<li>
<a href="http://www.binarymission.co.uk/Products/wpf/ribbon-wpf.html">BinaryMisson Ribbon</a></li>
</ul>

<h2>Schedule</h2>
<ul>
<li><a href="http://www.devcomponents.com/dotnetbar-wpf/WPFScheduleControl.aspx

">DevComponents Schedule Control</a></li>
<li><a href="http://www.devcomponents.com/dotnetbar-
wpf/WPFDateTimePicker.aspx
">DevComponents DateTime Picker</a></li>
<li><a
href="http://www.componentone.com/SuperProducts/SchedulerWPF/">Component One Schedule</a></li>
<li><a
href="http://timeline.codeplex.com/">Timeline Control</a></li>
<li><a
href="http://www.telerik.com/products/wpf/scheduler.aspx">Telerik RadScheduler for WPF</a></li>
<li><a
href="http://wpfschedule.codeplex.com/">Free WPF Schedule Control</a></li>
<li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-scheduler">Mindscape Schedule Control</a>
</li>
<li><w href="http://www.mindscapehq.com/products/wpfelements/controls/time-explorer">Mindscape Time
Explorer</a></li>
<li><a
href="http://www.infragistics.com/dotnet/netadvantage/wpf/xamMonthCalendar.aspx#Overview">Infragistics

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

MonthCalendar</a></li>
</ul>
<h2>Slider</h2>
<ul>
<li><a
href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-dual-slider">Mindscape Dual-Slider</a></li>
<li><a href="http://www.componentone.com/SuperProducts/RangeSliderWPF/">Component One Dual-Slider</a>
</li>
</ul>
<h2>Toolbar</h2>
<ul>
<li><a
href="http://www.devexpress.com/Products/NET/Controls/WPF/Bar_Menu/">DevExpress ToolBar</a></li>
<li><a
href="http://www.codeproject.com/KB/tree/WPFBreadcrumbBar.aspx">Odyssey Breadcrumb Bar</a></li>
<li><a
href="http://www.componentart.com/products/wpf/navigation/">ComponentArt Toolbar</a></li>
</ul>

<h2>Theming</h2>
<ul>
<li><a href="http://wpfthemeselector.codeplex.com/">WPF Theme Selector</a></li>
</ul>

<h2>Tree</h2>
<ul>
<li><a href="http://www.telerik.com/products/wpf/treeview.aspx">Telerik RadTree View for
WPF</a></li>
<li><a href="http://www.mindscapehq.com/products/wpfelements/controls/wpf-multicolumn-tree-
view">Mindscape Multicolumn Tree</a></li>
</ul>
<h2>Web Browser</h2>
<ul>
<li><a
href="http://wpfchromium.codeplex.com/SourceControl/changeset/view/28084#413984">Chromium Web
Browser</a></li>
</ul>
<h2>Wizard</h2>
<ul>
<li><a
href="http://www.divil.co.uk/net/controls/wizardframeworkwpf/">divelements Wizard</a></li>
<li><a
href="http://www.actiprosoftware.com/Products/DotNet/WPF/Wizard/Default.aspx">Actipro Wizard</a></li>
</ul>

<h2>3D</h2>
<ul>
<li><a href="http://xceed.com/3DViews_WPF_Intro.html">Xceed 3D Views</a></li>
</ul>
</td>

</tr>
</table>
http://www.wpftutorial.net/3rdPartyLibs.html
Sun, 16 Feb 2014 08:23:05 +01002013-03-08 21:43:42
moc@zuehlke.com (Christian Moser)
<h1>WPF replacemenet for <code>Screen.AllScreens()</code></h1> <p>Many
WPF applications want to check the available screen resolution to adjust window placements of sizes. In WinForms
was a nice helper called <code>Screen.AllScreens</code> that returned a list of screens with their corresponding
resolution. To use it from WPF you have to reference <code>System.Windows.Forms</code> and
<code>System.Windows.Drawing</code> which is not always what you want (because of application load time,
dependencies, ambigue class names, etc.).</p> <p>To get around this limitation I created a helper called
<code>Monitor</code> which is a simple port of the <code>Screen</code> functionality from WinForms.</p> <div
class="codeblock"><pre class="csharp csharp" style="font-family: courier new,courier,monospace;"> <span
style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #2b91af; font-weight:
bold;">class</span> Monitor <span style="color: #000000;">&#123;</span> <span style="color: #008000;">#region
Dll imports</span> <span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;
</span><span style="color: #666666;">&quot;user32.dll&quot;</span>, CharSet <span style="color: #008000;">=
</span> CharSet.<span style="color: #0600FF; font-weight: bold;">Auto</span><span style="color: #000000;">&#41;
</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#91;
</span>ResourceExposure<span style="color: #000000;">&#40;</span>ResourceScope.<span style="color:
#0000FF;">None</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight:
bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> <span style="color: #2b91af;
font-weight: bold;">bool</span> GetMonitorInfo <span style="color: #000000;">&#40;</span>HandleRef hmonitor,
<span style="color: #000000;">&#91;</span><span style="color: #0600FF; font-weight: bold;">In</span>, <span
style="color: #0600FF; font-weight: bold;">Out</span><span style="color: #000000;">&#93;</span>MonitorInfoEx
info<span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#91;</span>DllImport<span
style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;user32.dll&quot;</span>, ExactSpelling
<span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span
style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span> <span style="color:
#000000;">&#91;</span>ResourceExposure<span style="color: #000000;">&#40;</span>ResourceScope.<span
style="color: #0000FF;">None</span><span style="color: #000000;">&#41;</span><span style="color:
#000000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color:
#0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">extern</span> <span
style="color: #2b91af; font-weight: bold;">bool</span> EnumDisplayMonitors <span style="color: #000000;">&#40;
</span>HandleRef hdc, IntPtr rcClip, MonitorEnumProc lpfnEnum, IntPtr dwData<span style="color:
#000000;">&#41;</span>; <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color:
#2b91af; font-weight: bold;">delegate</span> <span style="color: #2b91af; font-weight: bold;">bool</span>
MonitorEnumProc <span style="color: #000000;">&#40;</span>IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr
lParam<span style="color: #000000;">&#41;</span>; <span style="color: #000000;">&#91;
</span>StructLayout<span style="color: #000000;">&#40;</span>LayoutKind.<span style="color:
#0000FF;">Sequential</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

</span> <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #2b91af; font-weight:
bold;">struct</span> Rect <span style="color: #000000;">&#123;</span> <span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #2b91af; font-weight: bold;">int</span> left; <span style="color: #0600FF;
font-weight: bold;">public</span> <span style="color: #2b91af; font-weight: bold;">int</span> top; <span
style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #2b91af; font-weight:
bold;">int</span> right; <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color:
#2b91af; font-weight: bold;">int</span> bottom; <span style="color: #000000;">&#125;</span> <span style="color:
#000000;">&#91;</span>StructLayout<span style="color: #000000;">&#40;</span>LayoutKind.<span style="color:
#0000FF;">Sequential</span>, CharSet <span style="color: #008000;">=</span> CharSet.<span style="color:
#0600FF; font-weight: bold;">Auto</span>, Pack <span style="color: #008000;">=</span> <span style="color:
#FF0000;">4</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #2b91af; font-weight:
bold;">class</span> MonitorInfoEx <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;
font-weight: bold;">internal</span> <span style="color: #2b91af; font-weight: bold;">int</span> cbSize <span
style="color: #008000;">=</span> Marshal.<a href="http://www.google.com/search?q=sizeof+msdn.microsoft.com">
<span style="color: #0000ff; font-weight: bold;">SizeOf</span></a><span style="color: #000000;">&#40;</span><a
href="http://www.google.com/search?q=typeof+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">typeof</span></a><span style="color: #000000;">&#40;</span>MonitorInfoEx<span style="color:
#000000;">&#41;</span><span style="color: #000000;">&#41;</span>; <span style="color: #0600FF; font-weight:
bold;">internal</span> Rect rcMonitor <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> Rect<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;
</span>;
<span style="color: #0600FF; font-weight: bold;">internal</span> Rect rcWork <span style="color:
#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> Rect<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
<span style="color: #0600FF; font-weight: bold;">internal</span> <span style="color:
#2b91af; font-weight: bold;">int</span> dwFlags <span style="color: #008000;">=</span> 0;
<span style="color:
#000000;">&#91;</span>MarshalAs<span style="color: #000000;">&#40;</span>UnmanagedType.<span
style="color: #0000FF;">ByValArray</span>, SizeConst <span style="color: #008000;">=</span> <span style="color:
#FF0000;">32</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">internal</span> <span style="color: #2b91af; font-weight:
bold;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span>
szDevice <span style="color: #008000;">=</span> <a href="http://www.google.com/search?
q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight: bold;">new</span></a> <span style="color:
#2b91af; font-weight: bold;">char</span><span style="color: #000000;">&#91;</span><span style="color:
#FF0000;">32</span><span style="color: #000000;">&#93;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight:
bold;">const</span> <span style="color: #2b91af; font-weight: bold;">int</span> MonitorinfofPrimary <span
style="color: #008000;">=</span> 0x00000001;
<span style="color: #008000;">#endregion</span>
<span
style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight:
bold;">static</span> HandleRef NullHandleRef <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> HandleRef<span style="color: #000000;">&#40;</span><span style="color: #0600FF; font-
weight: bold;">null</span>, IntPtr.<span style="color: #0000FF;">Zero</span><span style="color: #000000;">&#41;
</span>;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color:
#000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color:
#0000FF;">Rect</span> Bounds <span style="color: #000000;">&#123;</span> get; <span style="color: #0600FF;
font-weight: bold;">private</span> set; <span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;
font-weight: bold;">public</span> <span style="color: #000000;">System</span>.<span style="color:
#0000FF;">Windows</span>.<span style="color: #0000FF;">Rect</span> WorkingArea <span style="color:
#000000;">&#123;</span> get; <span style="color: #0600FF; font-weight: bold;">private</span> set; <span
style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span
style="color: #2b91af; font-weight: bold;">string</span> Name <span style="color: #000000;">&#123;</span> get;
<span style="color: #0600FF; font-weight: bold;">private</span> set; <span style="color: #000000;">&#125;</span>

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #2b91af; font-weight:


bold;">bool</span> IsPrimary <span style="color: #000000;">&#123;</span> get; <span style="color: #0600FF; font-
weight: bold;">private</span> set; <span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-
weight: bold;">private</span> Monitor<span style="color: #000000;">&#40;</span>IntPtr monitor, IntPtr hdc<span
style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
var info <span style="color:
#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> MonitorInfoEx<span style="color: #000000;">&#40;</span><span
style="color: #000000;">&#41;</span>;
GetMonitorInfo<span style="color: #000000;">&#40;</span><a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> HandleRef<span style="color: #000000;">&#40;</span><span style="color: #0600FF; font-
weight: bold;">null</span>, monitor<span style="color: #000000;">&#41;</span>, info<span style="color:
#000000;">&#41;</span>;
Bounds <span style="color: #008000;">=</span> <a href="http://www.google.com/search?
q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight: bold;">new</span></a> <span style="color:
#000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color:
#0000FF;">Rect</span><span style="color: #000000;">&#40;</span>
info.<span style="color:
#0000FF;">rcMonitor</span>.<span style="color: #0000FF;">left</span>, info.<span style="color:
#0000FF;">rcMonitor</span>.<span style="color: #0000FF;">top</span>, info.<span style="color:
#0000FF;">rcMonitor</span>.<span style="color: #0000FF;">right</span> <span style="color: #008000;">-</span>
info.<span style="color: #0000FF;">rcMonitor</span>.<span style="color: #0000FF;">left</span>, info.<span
style="color: #0000FF;">rcMonitor</span>.<span style="color: #0000FF;">bottom</span> <span style="color:
#008000;">-</span> info.<span style="color: #0000FF;">rcMonitor</span>.<span style="color:
#0000FF;">top</span><span style="color: #000000;">&#41;</span>;
WorkingArea <span style="color: #008000;">=
</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-
weight: bold;">new</span></a> <span style="color: #000000;">System</span>.<span style="color:
#0000FF;">Windows</span>.<span style="color: #0000FF;">Rect</span><span style="color: #000000;">&#40;
</span>
info.<span style="color: #0000FF;">rcWork</span>.<span style="color: #0000FF;">left</span>, info.<span
style="color: #0000FF;">rcWork</span>.<span style="color: #0000FF;">top</span>, info.<span style="color:
#0000FF;">rcWork</span>.<span style="color: #0000FF;">right</span> <span style="color: #008000;">-</span>
info.<span style="color: #0000FF;">rcWork</span>.<span style="color: #0000FF;">left</span>, info.<span
style="color: #0000FF;">rcWork</span>.<span style="color: #0000FF;">bottom</span> <span style="color:
#008000;">-</span> info.<span style="color: #0000FF;">rcWork</span>.<span style="color: #0000FF;">top</span>
<span style="color: #000000;">&#41;</span>;
IsPrimary <span style="color: #008000;">=</span> <span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#40;</span>info.<span style="color:
#0000FF;">dwFlags</span> <span style="color: #008000;">&amp;</span> MonitorinfofPrimary<span style="color:
#000000;">&#41;</span> <span style="color: #008000;">!=</span> 0<span style="color: #000000;">&#41;</span>;
Name <span style="color: #008000;">=</span> <a href="http://www.google.com/search?
q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight: bold;">new</span></a> <span style="color:
#2b91af; font-weight: bold;">string</span><span style="color: #000000;">&#40;</span>info.<span style="color:
#0000FF;">szDevice</span><span style="color: #000000;">&#41;</span>.<span style="color:
#0000FF;">TrimEnd</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;
</span><span style="color: #2b91af; font-weight: bold;">char</span><span style="color: #000000;">&#41;
</span>0<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span
style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight:
bold;">static</span> IEnumerable<span style="color: #008000;">&lt;</span>Monitor<span style="color:
#008000;">&gt;</span> AllMonitors
<span style="color: #000000;">&#123;</span>
get
<span style="color:
#000000;">&#123;</span>
var closure <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> MonitorEnumCallback<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
var proc <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> MonitorEnumProc<span style="color: #000000;">&#40;</span>closure.<span style="color:
#0000FF;">Callback</span><span style="color: #000000;">&#41;</span>;
EnumDisplayMonitors<span style="color:
#000000;">&#40;</span>NullHandleRef, IntPtr.<span style="color: #0000FF;">Zero</span>, proc, IntPtr.<span
style="color: #0000FF;">Zero</span><span style="color: #000000;">&#41;</span>;
<span style="color: #0600FF;

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

font-weight: bold;">return</span> closure.<span style="color: #0000FF;">Monitors</span>.<span style="color:


#0000FF;">Cast</span><span style="color: #008000;">&lt;</span>Monitor<span style="color: #008000;">&gt;
</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span
style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
<span style="color:
#0600FF; font-weight: bold;">private</span> <span style="color: #2b91af; font-weight: bold;">class</span>
MonitorEnumCallback
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> ArrayList Monitors <span style="color: #000000;">&#123;</span> get; <span style="color:
#0600FF; font-weight: bold;">private</span> set; <span style="color: #000000;">&#125;</span>
<span style="color:
#0600FF; font-weight: bold;">public</span> MonitorEnumCallback<span style="color: #000000;">&#40;</span>
<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
Monitors <span
style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span
style="color: #0000ff; font-weight: bold;">new</span></a> ArrayList<span style="color: #000000;">&#40;</span>
<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color:
#0600FF; font-weight: bold;">public</span> <span style="color: #2b91af; font-weight: bold;">bool</span>
Callback<span style="color: #000000;">&#40;</span>IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr
lparam<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
Monitors.<span
style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> Monitor<span style="color: #000000;">&#40;</span>monitor, hdc<span style="color:
#000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #0600FF; font-weight:
bold;">return</span> true;
<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;
</span>
<span style="color: #000000;">&#125;</span>
</pre></div>
http://www.wpftutorial.net/ScreenResolutions.html
Sun, 16 Feb 2014 08:23:05 +01002012-12-06 16:52:36
moc@zuehlke.com (Christian Moser)
<h1>Books about WPF</h1>
<table width="700">
<tr style="height: 200px;">
<td><a href="http://www.packtpub.com/windows-presentation-foundation-4-5-cookbook/book"><img
src="images/book_cookbook45.jpg" style="width: 150px;"></a></td>
<td style="vertical-align: top;">
<h3><a
href="http://www.packtpub.com/windows-presentation-foundation-4-5-cookbook/book">Windows Presentation
Foundation 4.5 Cookbook</a></h3> <p>The book contains over 80 recipes to effectively and efficiently develop rich
Windows client applications on the Windows platform. It is full of illustrations, diagrams, and tips with clear step-by-
step instructions and real world examples to gain a strong foundation of WPF features and patterns. It shows how to
leverage the MVVM pattern to build decoupled, maintainable apps.</p>
<p><table>
<tr>
<td style="width: 100px;">
<b>Autor:</b></td>
<td>Pavel Yosifovich</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b></td>
<td>978-
1849686228</td>
</tr>
<tr>
<td style="width: 100px;"><b>Published:</b></td>
<td>Sept 2012</td>
</tr>
<tr>
<td>
</td>
<td><a href="http://www.packtpub.com/windows-presentation-foundation-4-5-cookbook/book"
target="_blank">Find it at Packt publishing</td>
</tr>
</table>
</p>
</td>
</tr>
</table>
<table width="700">
<tr
style="height: 200px;">
<td><img src="images/book_wpf4unleashed.png" style="width: 150px;"></td>
<td
style="vertical-align: top;">
<h3>WPF 4 - Unleashed</h3> <p>In my opinion one of the best books about WPF - now
updated to version 4.0. It's printed fully in color, so all code samples have syntax highlighting. It includes all the good
explanations and samples of version 3 including new chapters about multitouch, XAML 2009, VSM, improved text
rendering, windows 7 shell integration and more. </p>
<p><table>
<tr>
<td style="width: 100px;"><b>Autor:</b>
</td>
<td>Adam Nathan</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b></td>
<td>978-0672331190</td>
</tr>
<tr>
<td style="width: 100px;"><b>Published:</b></td>
<td>June 2010</td>
</tr>
<tr>
<td></td>
<td><a
href="http://www.amazon.de/WPF-4-Unleashed-Adam-Nathan/dp/0672331195/ref=sr_1_1?ie=UTF8&s=books-intl-
de&qid=1279693891&sr=8-1" target="_blank">Find it at Amazon</td>
</tr>
</table>
</p>
</td>
</tr>
</table>
<table
width="700">
<tr style="height: 200px;">
<td><img src="images/book_wpfcontroldev.png" style="width: 150px;">
</td>
<td style="vertical-align: top;">
<h3>WPF Control Development Unleashed</h3> <p>In this book, two leading
Windows Presentation Foundation experts give developers everything they need to build next-generation WPF
applications--software that is more robust, usable, and compelling. Drawing on their close ties with Microsoft's WPF
development team, Pavan Podila and Kevin Hoffman give you a clear, robust, and practical understanding of WPF, its
underpinnings, its overall architecture, and its design philosophy.</p>
<p><table>
<tr>
<td style="width: 100px;">
<b>Autor:</b></td>
<td>Pavan Podila, Kevin Hoffman</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b>
</td>
<td>978-0672330339</td>
</tr>
<tr>
<td style="width: 100px;"><b>Published:</b></td>
<td>September
2009</td>
</tr>
<tr>
<td></td>
<td><a href="http://www.amazon.de/gp/product/0672330334/ref=sib_rdr_dp"
target="_blank">Find it at Amazon</td>
</tr>
</table>
</p>
</td>
</tr>
<tr style="height: 200px;">
<td><img

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

src="images/book_wpfunleashed.jpg" style="width: 150px;"></td>


<td style="vertical-align: top;">
<h3>Windows
Presentation Foundation - Unleashed (My favorite!)</h3> <p>In my opinion one of the best book about WPF. It covers
all important themes including 3D programming. All code samples have syntax highlighting. Digging deeper sections
with additional informations for advanced programmers.</p>
<p><table>
<tr>
<td style="width: 100px;"><b>Autor:
</b></td>
<td>Adam Nathan</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b></td>
<td>978-
0672328916</td>
</tr>
<tr>
<td style="width: 100px;"><b>Published:</b></td>
<td>January 2007</td>
</tr>
<tr>
<td></td>
<td><a href="http://www.amazon.de/Windows-Presentation-Foundation-Unleashed-
Nathan/dp/0672328917/ref=pd_sim_eb_1" target="_blank">Find it at Amazon</td>
</tr>
</table>
</p>
</td>
</tr>
<tr
style="height: 200px;">
<td><img src="images/book_appcodemarkup.jpg" style="width: 130px;"></td>
<td
style="vertical-align: top;">
<h3>Application = Code + Markup</h3> <p>"Get the definitive guide to the Windows
Presentation Foundation (WPF), the new client programming interface for the Microsoft .NET Framework 3.0 and
Windows Vista. Award-winning author Charles Petzold teaches you how to combine C# code and the Extensible
Application Markup Language (XAML) to develop applications for the WPF.". I cannot unterstand how anyone can
write a book about a UI technology without a single illustration. If you prefer gray text to colorful images, it might be
the book for you. </p>
<p><table>
<tr>
<td style="width: 100px;"><b>Autor:</b></td>
<td>Charles Petzold</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b></td>
<td>978-0735619579</td>
</tr>
<tr>
<td style="width:
100px;"><b>Published:</b></td>
<td>August 2006</td>
</tr>
</table>
</p>
</td>
</tr>
<tr style="height: 200px;">
<td><img src="images/book_essentialwpf.jpg" style="width: 130px;"></td>
<td style="vertical-align: top;">

<h3>Essential Windows Presentation Foundation</h3> <p>Chris Anderson was one of the chief architects of the next-
generation GUI stack, the Windows Presentation Framework (WPF), which is the subject of this book. Chris's insights
shine a light from the internals of WPF to those standing at the entrance, guiding you through the concepts that form the
foundation of his creation.</p>
<p><table>
<tr>
<td style="width: 100px;"><b>Autor:</b></td>
<td>Chris
Anderson</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b></td>
<td>978-0321374479</td>
</tr>
<tr>
<td
style="width: 100px;"><b>Published:</b></td>
<td>April 2007</td>
</tr>
</table>
</p>
</td>
</tr>
<tr
style="height: 200px;">
<td><img src="images/book_foundations.jpg" style="width: 130px;"></td>
<td
style="vertical-align: top;">
<h3>Foundations of WPF: An Introduction to Windows Presentation Foundation </h3>
<p>Foundations of WPF: An Introduction to Windows Presentation Foundation teaches you everything you need to get
started with the technology, and is broken into three parts. The first introduces and contextualizes the WPF technology;
the second part dives deeper into the facets of the technology that are of immediate and valuable use in developing
applications; the last part offers you the real-world perspective you need to be productive in the community and
customer base.</p>
<p><table>
<tr>
<td style="width: 100px;"><b>Autor:</b></td>
<td>Laurence Moroney</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b></td>
<td>978-1590597606</td>
</tr>
<tr>
<td style="width:
100px;"><b>Published:</b></td>
<td>November 2006</td>
</tr>
</table>
</p>
</td>
</tr>
<tr style="height:
200px;">
<td><img src="images/book_prowpf.jpg" style="width: 130px;"></td>
<td style="vertical-align: top;">

<h3>Pro WPF in C# 2008</h3> <p>This book explains how WPF works from the ground up. It follows on from the
author s previous and highly successful books, covering Windows Forms (WPF's predecessor technology) and earlier
versions of WPF. It is a one-stop shop in Apress proven Pro style that leaves readers with a deep understanding of the
technology and able to take the concepts away and apply them for themselves.</p>
<p><table>
<tr>
<td style="width:
100px;"><b>Autor:</b></td>
<td>Matthew McDonald</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b>
</td>
<td>978-1590599556</td>
</tr>
<tr>
<td style="width: 100px;"><b>Published:</b></td>
<td>Februar
2008</td>
</tr>
</table>
</p>
</td>
</tr>
<tr style="height: 200px;">
<td><img
src="images/book_programming_wpf.jpg" style="width: 130px;"></td>
<td style="vertical-align: top;">

<h3>Foundations of WPF: An Introduction to Windows Presentation Foundation </h3> <p>If you want to build
applications that take full advantage of Windows Vista's new user interface capabilities, you need to learn Microsoft's
Windows Presentation Foundation (WPF). This new edition, fully updated for the official release of .NET 3.0, is
designed to get you up to speed on this technology quickly.</p>
<p><table>
<tr>
<td style="width: 100px;">
<b>Autor:</b></td>
<td>Chris Sells and Ian Griffiths</td>
</tr>
<tr>
<td style="width: 100px;"><b>ISBN:</b></td>
<td>978-0596510374</td>
</tr>
<tr>
<td style="width: 100px;"><b>Published:</b></td>
<td>September 2007</td>
</tr>
</table>
</p>
</td>
</tr>
</table>
http://www.wpftutorial.net/WPFBools.html
Sun, 16 Feb 2014 08:23:05
+01002012-10-24 09:40:51
moc@zuehlke.com (Christian Moser)
<h1>Architecture of WPF</h1>
<p>This article is
still in constuction...</p>
http://www.wpftutorial.net/WPFArchitecture.html
Sun, 16 Feb 2014 08:23:05 +01002012-10-
23 16:32:19
moc@zuehlke.com (Christian Moser)
<h1>How to implement undo/redo using MVVM</h1>
<h3>Introduction</h3> <p>One feature that many users demand is a neatless undo/redo integration. This means that
the application allows the user to revert any modification he made - one by one - back to the start of the application and

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

than eventually reapply them again. This improves the usability a lot, because it allows the user to carelessly use an
unclear command, because he is certain, that he can undo it if he was wrong. Today undo/redo has gotten almost
standard for any modern data editing application.</p> <img style="padding-left: 150px;" src="images/undoredo.png"
/> <h3>The MVVM-Pattern</h3> <p>Because of the strong databinding functionality in WPF, most applications are
using the popular MVVM (Model-View-ViewModel) pattern. The idea of this pattern is basically to define a class that
aggregates all data and commands for a certain view and provides them to the view as properties where it can bind to.
Changes on properties are notified by an event on the <code>INotifyPropertyChanged</code> interface.</p> <h3>A
concept of implementing undo/redo</h3> <p>A classical approach to implement undo/redo is to allow changes on the
model only through commands. And every command should be invertible. The user than executes an action, the
application creates a command, executes it and puts an inverted command on the undo-stack. When the user clicks on
undo, the application executes the top-most (inverse) command on the undo-stack, inverts it again (to get the original
command again) and puts it on the redo-stack. That's it.</p> <p><b>Scenario 1: Executing an action</b></p> <img
style="padding-left: 50px;" src="images/undoredo1.png" /> <p><b>Scenario 2: Undoing an action</b></p> <img
style="padding-left: 50px;" src="images/undoredo2.png" /> <h3>Adoption for WPF</h3> <p>We start with a base
class that implements the <code>INotifyPropertyChanged</code> interface and provides a private method
<code>Notify(string propertyName)</code>. <div class="codeblock"><pre class="csharp csharp" style="font-family:
courier new,courier,monospace;"> <span style="color: #0600FF; font-weight: bold;">public</span> <span
style="color: #2b91af; font-weight: bold;">class</span> NotifyableObject <span style="color: #008000;">:</span>
INotifyPropertyChanged
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> PropertyChangedEventHandler
PropertyChanged;
<span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF;
font-weight: bold;">void</span> Notify<span style="color: #000000;">&#40;</span><span style="color: #2b91af;
font-weight: bold;">string</span> propertyName<span style="color: #000000;">&#41;</span>
<span style="color:
#000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color:
#000000;">&#40;</span>PropertyChanged <span style="color: #008000;">!=</span> <span style="color: #0600FF;
font-weight: bold;">null</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span>
PropertyChanged<span style="color: #000000;">&#40;</span><span style="color: #0600FF; font-weight:
bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> PropertyChangedEventArgs<span style="color: #000000;">&#40;
</span>propertyName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
<span style="color:
#000000;">&#125;</span>
</pre></div>
<p>Then we build the base class <code>TrackableObject</code> where all
model objects or view models that are directly bound to the view should inherit from. <div class="codeblock"><pre
class="csharp csharp" style="font-family: courier new,courier,monospace;"> <span style="color: #0600FF; font-
weight: bold;">public</span> <span style="color: #2b91af; font-weight: bold;">class</span> TrackableObject <span
style="color: #008000;">:</span> NotifyableObject
<span style="color: #000000;">&#123;</span>
<span
style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight:
bold;">readonly</span> List<span style="color: #008000;">&lt;</span>ITrackable<span style="color:
#008000;">&gt;</span> _trackableItems <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> List<span style="color: #008000;">&lt;</span>ITrackable<span style="color:
#008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #2b91af; font-weight:
bold;">bool</span> HasChanges
<span style="color: #000000;">&#123;</span>
get <span style="color:
#000000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _trackableItems.<span
style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span>i <span style="color:
#008000;">=&gt;</span> i.<span style="color: #0000FF;">HasChanges</span><span style="color: #000000;">&#41;
</span>; <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
<span
style="color: #0600FF; font-weight: bold;">public</span> IModificationTracker ModificationTracker <span
style="color: #000000;">&#123;</span> get; set; <span style="color: #000000;">&#125;</span>
<span style="color:
#0600FF; font-weight: bold;">protected</span> TrackableValue<span style="color: #008000;">&lt;</span>T<span
style="color: #008000;">&gt;</span> RegisterTrackableValue<span style="color: #008000;">&lt;</span>T<span
style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #2b91af; font-
weight: bold;">string</span> propertyName, T defaultValue <span style="color: #008000;">=</span> <span

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

style="color: #0600FF; font-weight: bold;">default</span><span style="color: #000000;">&#40;</span>T<span


style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color:
#000000;">&#123;</span>
var property <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> TrackableValue<span style="color: #008000;">&lt;</span>T<span style="color:
#008000;">&gt;</span><span style="color: #000000;">&#40;</span>propertyName, Modify, Notify,
defaultValue<span style="color: #000000;">&#41;</span>;
_trackableItems.<span style="color:
#0000FF;">Add</span><span style="color: #000000;">&#40;</span>property<span style="color: #000000;">&#41;
</span>;
<span style="color: #0600FF; font-weight: bold;">return</span> property;
<span style="color:
#000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">protected</span>
TrackableCollection<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
RegisterTrackableCollection<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color:
#000000;">&#123;</span>
var collection <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> TrackableCollection<span style="color: #008000;">&lt;</span>T<span style="color:
#008000;">&gt;</span><span style="color: #000000;">&#40;</span>Modify<span style="color: #000000;">&#41;
</span>;
_trackableItems.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;
</span>collection<span style="color: #000000;">&#41;</span>;
<span style="color: #0600FF; font-weight:
bold;">return</span> collection;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-
weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">void</span> Modify<span
style="color: #000000;">&#40;</span>Action doAction, Action undoAction, Action notification<span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
var modification <span style="color:
#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> Modification<span style="color: #000000;">&#40;</span>doAction,
undoAction, notification<span style="color: #000000;">&#41;</span>;
modification.<span style="color:
#0000FF;">Execute</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;
</span>;
ModificationTracker.<span style="color: #0000FF;">TrackModification</span><span style="color:
#000000;">&#40;</span>modification<span style="color: #000000;">&#41;</span>;
<span style="color:
#000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
</pre></div>
<p>To simplify the
generation of modifactions when changing a property value, we build a generic wrapper for each property called
<code>TrackableValue</code>. <div class="codeblock"><pre class="csharp csharp" style="font-family: courier
new,courier,monospace;"> <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color:
#2b91af; font-weight: bold;">class</span> TrackableValue<span style="color: #008000;">&lt;</span>T<span
style="color: #008000;">&gt;</span> <span style="color: #008000;">:</span> ITrackable
<span style="color:
#000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color:
#0600FF; font-weight: bold;">readonly</span> <span style="color: #2b91af; font-weight: bold;">string</span>
_propertyName;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-
weight: bold;">readonly</span> Action<span style="color: #008000;">&lt;</span>Action, Action, Action<span
style="color: #008000;">&gt;</span> _modifyCallback;
<span style="color: #0600FF; font-weight:
bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> Action<span style="color:
#008000;">&lt;</span><span style="color: #2b91af; font-weight: bold;">string</span><span style="color:
#008000;">&gt;</span> _notifyAction;
<span style="color: #0600FF; font-weight: bold;">private</span> T _value;
<span style="color: #0600FF; font-weight: bold;">public</span> TrackableValue<span style="color:
#000000;">&#40;</span><span style="color: #2b91af; font-weight: bold;">string</span> propertyName, Action<span
style="color: #008000;">&lt;</span>Action, Action, Action<span style="color: #008000;">&gt;</span>
modifyCallback,
Action<span style="color: #008000;">&lt;</span><span style="color: #2b91af; font-weight:
bold;">string</span><span style="color: #008000;">&gt;</span> notifyAction, T defaultValue<span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
_propertyName <span style="color:
#008000;">=</span> propertyName;
_modifyCallback <span style="color: #008000;">=</span> modifyCallback;
_notifyAction <span style="color: #008000;">=</span> notifyAction;
_value <span style="color: #008000;">=</span>
defaultValue;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #2b91af; font-weight: bold;">bool</span> HasChanges
<span style="color:
#000000;">&#123;</span>
get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF; font-

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

weight: bold;">return</span> _originalValue.<span style="color: #0000FF;">Equals</span><span style="color:


#000000;">&#40;</span>_value<span style="color: #000000;">&#41;</span>; <span style="color:
#000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> T Value
<span style="color: #000000;">&#123;</span>
get <span style="color:
#000000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _value; <span
style="color: #000000;">&#125;</span>
set
<span style="color: #000000;">&#123;</span>
var oldValue <span
style="color: #008000;">=</span> _value;
_modifyCallback<span style="color: #000000;">&#40;</span><span
style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color:
#008000;">=&gt;</span> _value <span style="color: #008000;">=</span> value, <span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
_value <span style="color: #008000;">=</span> oldValue,
<span style="color: #000000;">&#40;</span><span
style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> _notifyAction<span
style="color: #000000;">&#40;</span>_propertyName<span style="color: #000000;">&#41;</span><span
style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color:
#000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
</pre></div>
<p>To same thing we need
to do for collections to track add/remove of items from a collection</p>
<div class="codeblock"><pre class="csharp
csharp" style="font-family: courier new,courier,monospace;"> <span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #2b91af; font-weight: bold;">class</span> TrackableCollection<span
style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> <span style="color: #008000;">:
</span> IList<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>, ITrackable

<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">private</span>
<span style="color: #0600FF; font-weight: bold;">readonly</span> Action<span style="color: #008000;">&lt;
</span>Action, Action, Action<span style="color: #008000;">&gt;</span> _modifyCallback;
<span style="color:
#0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">readonly</span>
List<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> _list <span style="color:
#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> List<span style="color: #008000;">&lt;</span>T<span style="color:
#008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight:
bold;">readonly</span> List<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>
_originalList <span style="color: #008000;">=</span> <a href="http://www.google.com/search?
q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight: bold;">new</span></a> List<span
style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #0600FF; font-weight:
bold;">public</span> TrackableCollection<span style="color: #000000;">&#40;</span>Action<span style="color:
#008000;">&lt;</span>Action, Action, Action<span style="color: #008000;">&gt;</span> modifyCallback<span
style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
_modifyCallback <span
style="color: #008000;">=</span> modifyCallback;
<span style="color: #000000;">&#125;</span>
<span
style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight:
bold;">event</span> EventHandler<span style="color: #008000;">&lt;</span>EventArgs<span style="color:
#008000;">&lt;</span>T<span style="color: #008000;">&gt;&gt;</span> ItemAdded;
<span style="color: #0600FF;
font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span>
EventHandler<span style="color: #008000;">&lt;</span>EventArgs<span style="color: #008000;">&lt;
</span>T<span style="color: #008000;">&gt;&gt;</span> ItemRemoved;
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #0600FF; font-weight: bold;">event</span> EventHandler
CollectionChanged;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #2b91af;
font-weight: bold;">bool</span> HasChanges
<span style="color: #000000;">&#123;</span>
get
<span style="color:
#000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">if</span><span style="color:
#000000;">&#40;</span> _list.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">==
</span> _originalList.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">return</span> _list.
<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#40;</span>item, index<span style="color: #000000;">&#41;</span> <span style="color:
#008000;">=&gt;</span> <span style="color: #008000;">!</span>item.<span style="color: #0000FF;">Equals</span>

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

<span style="color: #000000;">&#40;</span>_originalList<span style="color: #000000;">&#91;</span>index<span


style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color:
#000000;">&#41;</span>.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span>
<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color:
#0600FF; font-weight: bold;">return</span> true;
<span style="color: #000000;">&#125;</span>
<span style="color:
#000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color:
#0600FF; font-weight: bold;">void</span> AcceptChanges<span style="color: #000000;">&#40;</span><span
style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
_originalList.<span
style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
_originalList.<span style="color: #0000FF;">AddRange</span><span style="color:
#000000;">&#40;</span>_list<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;
</span>
<span style="color: #0600FF; font-weight: bold;">public</span> IEnumerator<span style="color:
#008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> GetEnumerator<span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span> <span style="color: #0600FF; font-weight: bold;">return</span> _list.<span style="color:
#0000FF;">GetEnumerator</span><span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>; <span style="color: #000000;">&#125;</span>
IEnumerator IEnumerable.<span
style="color: #0000FF;">GetEnumerator</span><span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight:
bold;">return</span> GetEnumerator<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #0600FF; font-weight: bold;">void</span> Add<span style="color:
#000000;">&#40;</span>T item<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span>
_modifyCallback<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>
<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
<span style="color:
#000000;">&#123;</span>
_list.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;
</span>item<span style="color: #000000;">&#41;</span>; ItemAdded.<span style="color: #0000FF;">Notify</span>
<span style="color: #000000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;
</span><span style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;</span><span
style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>, <span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>

<span style="color: #000000;">&#123;</span>
_list.<span style="color: #0000FF;">Remove</span><span
style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;</span>;
ItemRemoved.<span
style="color: #0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;
font-weight: bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span
style="color: #0000ff; font-weight: bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;
</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>item<span
style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color:
#000000;">&#125;</span>, OnCollectionModified<span style="color: #000000;">&#41;</span>;
<span style="color:
#000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color:
#0600FF; font-weight: bold;">void</span> Clear<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
var items <span style="color: #008000;">=
</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-
weight: bold;">new</span></a> T<span style="color: #000000;">&#91;</span>_list.<span style="color:
#0000FF;">Count</span><span style="color: #000000;">&#93;</span>;
_list.<span style="color:
#0000FF;">CopyTo</span><span style="color: #000000;">&#40;</span>items<span style="color: #000000;">&#41;
</span>;
_modifyCallback<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>
<span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
<span style="color:
#000000;">&#123;</span>
_list.<span style="color: #0600FF; font-weight: bold;">ForEach</span><span
style="color: #000000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> ItemRemoved.<span
style="color: #0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;
font-weight: bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

style="color: #0000ff; font-weight: bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;


</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>i<span
style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color:
#000000;">&#41;</span>;
_list.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;
</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>, <span
style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color:
#008000;">=&gt;</span>
<span style="color: #000000;">&#123;</span>
_list.<span style="color:
#0000FF;">AddRange</span><span style="color: #000000;">&#40;</span>items<span style="color:
#000000;">&#41;</span>;
_list.<span style="color: #0600FF; font-weight: bold;">ForEach</span><span style="color:
#000000;">&#40;</span>i <span style="color: #008000;">=&gt;</span> ItemAdded.<span style="color:
#0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF; font-weight:
bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;</span>T<span
style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>i<span style="color:
#000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;
</span>;
<span style="color: #000000;">&#125;</span>, OnCollectionModified<span style="color: #000000;">&#41;
</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #2b91af; font-weight: bold;">bool</span> Contains<span style="color:
#000000;">&#40;</span>T item<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span>
<span style="color: #0600FF; font-weight: bold;">return</span> _list.<span style="color:
#0000FF;">Contains</span><span style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;
</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #0600FF; font-weight: bold;">void</span> CopyTo<span style="color:
#000000;">&#40;</span>T<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;
</span> array, <span style="color: #2b91af; font-weight: bold;">int</span> arrayIndex<span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
_list.<span style="color:
#0000FF;">CopyTo</span><span style="color: #000000;">&#40;</span>array, arrayIndex<span style="color:
#000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #2b91af; font-weight: bold;">bool</span> Remove<span style="color:
#000000;">&#40;</span>T item<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span>
var result <span style="color: #008000;">=</span> _list.<span style="color: #0000FF;">Contains</span>
<span style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;</span>;
_modifyCallback<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span
style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
<span style="color:
#000000;">&#123;</span>
_list.<span style="color: #0000FF;">Remove</span><span style="color:
#000000;">&#40;</span>item<span style="color: #000000;">&#41;</span>;
ItemRemoved.<span style="color:
#0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF; font-weight:
bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;</span>T<span
style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>item<span style="color:
#000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;
</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span
style="color: #008000;">=&gt;</span>
<span style="color: #000000;">&#123;</span>
_list.<span style="color:
#0000FF;">Add</span><span style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;
</span>;
ItemAdded.<span style="color: #0000FF;">Notify</span><span style="color: #000000;">&#40;</span>
<span style="color: #0600FF; font-weight: bold;">this</span>, <a href="http://www.google.com/search?
q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight: bold;">new</span></a> EventArgs<span
style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color:
#000000;">&#40;</span>item<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;
</span>;
<span style="color: #000000;">&#125;</span>, OnCollectionModified<span style="color: #000000;">&#41;
</span>;
<span style="color: #0600FF; font-weight: bold;">return</span> result;
<span style="color:
#000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color:
#2b91af; font-weight: bold;">int</span> Count
<span style="color: #000000;">&#123;</span>
get <span style="color:
#000000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _list.<span style="color:

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

#0000FF;">Count</span>; <span style="color: #000000;">&#125;</span>


<span style="color: #000000;">&#125;
</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #2b91af; font-weight:
bold;">bool</span> IsReadOnly
<span style="color: #000000;">&#123;</span>
get <span style="color:
#000000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> false; <span style="color:
#000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #2b91af; font-weight: bold;">int</span> IndexOf<span style="color:
#000000;">&#40;</span>T item<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span>
<span style="color: #0600FF; font-weight: bold;">return</span> _list.<span style="color:
#0000FF;">IndexOf</span><span style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;
</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">public</span> <span style="color: #0600FF; font-weight: bold;">void</span> Insert<span style="color:
#000000;">&#40;</span><span style="color: #2b91af; font-weight: bold;">int</span> index, T item<span
style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
_modifyCallback<span
style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
<span style="color: #000000;">&#123;
</span>
_list.<span style="color: #0000FF;">Insert</span><span style="color: #000000;">&#40;</span>index,
item<span style="color: #000000;">&#41;</span>;
ItemAdded.<span style="color: #0000FF;">Notify</span><span
style="color: #000000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;
</span><span style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;</span><span
style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>, <span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>

<span style="color: #000000;">&#123;</span>
_list.<span style="color: #0000FF;">Remove</span><span
style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;</span>;
ItemRemoved.<span
style="color: #0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;
font-weight: bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span
style="color: #0000ff; font-weight: bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;
</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>item<span
style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color:
#000000;">&#125;</span>, OnCollectionModified<span style="color: #000000;">&#41;</span>;
<span style="color:
#000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color:
#0600FF; font-weight: bold;">void</span> RemoveAt<span style="color: #000000;">&#40;</span><span
style="color: #2b91af; font-weight: bold;">int</span> index<span style="color: #000000;">&#41;</span>
<span
style="color: #000000;">&#123;</span>
var item <span style="color: #008000;">=</span> _list<span style="color:
#000000;">&#91;</span>index<span style="color: #000000;">&#93;</span>;
_modifyCallback<span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #008000;">=&gt;</span>
<span style="color: #000000;">&#123;</span>
_list.<span style="color:
#0000FF;">Remove</span><span style="color: #000000;">&#40;</span>item<span style="color: #000000;">&#41;
</span>;
ItemRemoved.<span style="color: #0000FF;">Notify</span><span style="color: #000000;">&#40;</span>
<span style="color: #0600FF; font-weight: bold;">this</span>, <a href="http://www.google.com/search?
q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight: bold;">new</span></a> EventArgs<span
style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color:
#000000;">&#40;</span>item<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;
</span>;
<span style="color: #000000;">&#125;</span>, <span style="color: #000000;">&#40;</span><span
style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>
<span style="color:
#000000;">&#123;</span>
_list.<span style="color: #0000FF;">Insert</span><span style="color: #000000;">&#40;
</span>index, item<span style="color: #000000;">&#41;</span>;
ItemAdded.<span style="color:
#0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF; font-weight:
bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;</span>T<span
style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>item<span style="color:
#000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;
</span>, OnCollectionModified<span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

</span>
<span style="color: #0600FF; font-weight: bold;">public</span> T <span style="color: #0600FF; font-weight:
bold;">this</span><span style="color: #000000;">&#91;</span><span style="color: #2b91af; font-weight:
bold;">int</span> index<span style="color: #000000;">&#93;</span>
<span style="color: #000000;">&#123;</span>

get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span>
_list<span style="color: #000000;">&#91;</span>index<span style="color: #000000;">&#93;</span>; <span
style="color: #000000;">&#125;</span>
set
<span style="color: #000000;">&#123;</span>
var oldItem <span
style="color: #008000;">=</span> _list<span style="color: #000000;">&#91;</span>index<span style="color:
#000000;">&#93;</span>;
_modifyCallback<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span>

<span style="color: #000000;">&#123;</span>
_list<span style="color: #000000;">&#91;</span>index<span
style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> value;
ItemAdded.<span
style="color: #0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;
font-weight: bold;">this</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span
style="color: #0000ff; font-weight: bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;
</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>value<span
style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color:
#000000;">&#125;</span>, <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;
</span> <span style="color: #008000;">=&gt;</span>
<span style="color: #000000;">&#123;</span>
_list<span
style="color: #000000;">&#91;</span>index<span style="color: #000000;">&#93;</span> <span style="color:
#008000;">=</span> oldItem;
ItemRemoved.<span style="color: #0000FF;">Notify</span><span style="color:
#000000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span>, <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> EventArgs<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;
</span><span style="color: #000000;">&#40;</span>oldItem<span style="color: #000000;">&#41;</span><span
style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>, OnCollectionModified<span
style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color:
#000000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color:
#0600FF; font-weight: bold;">void</span> OnCollectionModified<span style="color: #000000;">&#40;</span><span
style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
CollectionChanged.<span
style="color: #0000FF;">Notify</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;
font-weight: bold;">this</span>, EventArgs.<span style="color: #0000FF;">Empty</span><span style="color:
#000000;">&#41;</span>; <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;
</span>
</pre></div>
http://www.wpftutorial.net/UndoRedo.html
Sun, 16 Feb 2014 08:23:05 +01002011-12-23
09:14:09
moc@zuehlke.com (Christian Moser)
<h1>Grid Panel</h1> <p><a href="#Intro">Introduction</a></p> <p>
<a href="#add">How to define rows and columns</a></p> <p><a href="#add">How to add controls to the grid</a>
</p> <p><a href="#resize">Resize columns or rows</a></p> <p><a href="#sharedsize">How to share the width of a
column over multiple grids</a></p> <p><a href="#gridlength">Using GridLenghts from code</a></p> <a
name="Intro"><h2>Introduction</h2></a> <img src="images/v2_gridlayout.png" style="margin-left: 200px;" />
<p>The grid is a layout panel that arranges its child controls in a tabular structure of rows and columns. Its
functionality is similar to the HTML table but more flexible. A cell can contain multiple controls, they can span over
multiple cells and even overlap themselves.</p> <p>The resize behaviour of the controls is defined by the
<code>HorizontalAlignment</code> and <code>VerticalAlignment</code> properties who define the anchors. The
distance between the anchor and the grid line is specified by the margin of the control</p> <a name="rowscols">
<h2>Define Rows and Columns</h2></a> <p>The grid has one row and column by default. To create additional rows
and columns, you have to add <code>RowDefinition</code> items to the <code>RowDefinitions</code> collection
and <code>ColumnDefinition</code> items to the <code>ColumnDefinitions</code> collection. The following
example shows a grid with three rows and two columns.</p> <p>The size can be specified as an absolute amount of
logical units, as a percentage value or automatically.</p> <table style="margin-left: 40px; width: 600px;"> <tr> <td
style="width: 50px;"><b>Fixed</b></td> <td> Fixed size of logical units (1/96 inch)</td> </tr> <tr> <td>
<b>Auto</b></td> <td> Takes as much space as needed by the contained control</td> </tr> <tr> <td style="vertical-
align: top"><b>Star (*)</b></td> <td>Takes as much space as available (after filling all auto and fixed sized columns),
proportionally divided over all star-sized columns. So 3*/5* means the same as 30*/50*. Remember that star-sizing
does not work if the grid size is calculated based on its content. </td> </tr> </table> <div class="codeblock"><pre
class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color: #800000;"><span

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

style="color: #800000;">&lt;Grid<span style="color: #800000;">&gt;</span></span></span> <span style="color:


#800000;"><span style="color: #800000;">&lt;Grid</span>.RowDefinitions<span style="color: #800000;">&gt;
</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;RowDefinition</span> <span
style="color: #ff0000;">Height</span>=<span style="color: #0000ff;">&quot;Auto&quot;</span> <span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;RowDefinition</span> <span style="color: #ff0000;">Height</span>=<span style="color:
#0000ff;">&quot;Auto&quot;</span> <span style="color: #800000;">/&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;RowDefinition</span> <span style="color: #ff0000;">Height</span>=
<span style="color: #0000ff;">&quot;*&quot;</span> <span style="color: #800000;">/&gt;</span></span> <span
style="color: #800000;"><span style="color: #800000;">&lt;RowDefinition</span> <span style="color:
#ff0000;">Height</span>=<span style="color: #0000ff;">&quot;28&quot;</span> <span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;/Grid</span>.RowDefinitions<span style="color: #800000;">&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;Grid</span>.ColumnDefinitions<span style="color: #800000;">&gt;
</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;ColumnDefinition</span> <span
style="color: #ff0000;">Width</span>=<span style="color: #0000ff;">&quot;Auto&quot;</span> <span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;ColumnDefinition</span> <span style="color: #ff0000;">Width</span>=<span style="color:
#0000ff;">&quot;200&quot;</span> <span style="color: #800000;">/&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;/Grid</span>.ColumnDefinitions<span style="color: #800000;">&gt;
</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;/Grid<span style="color:
#800000;">&gt;</span></span></span> </pre></div><a name="add"><h2>How to add controls to the grid</h2></a>
<p>To add controls to the grid layout panel just put the declaration between the opening and closing tags of the
<code>Grid</code>. Keep in mind that the row- and columndefinitions must precced any definition of child controls.
</p> <p>The grid layout panel provides the two attached properties <code>Grid.Column</code> and
<code>Grid.Row</code> to define the location of the control.</p> <div class="codeblock"><pre class="xaml xaml"
style="font-family: courier new,courier,monospace;"><span style="color: #800000;"><span style="color:
#800000;">&lt;Grid<span style="color: #800000;">&gt;</span></span></span> <span style="color: #800000;">
<span style="color: #800000;">&lt;Grid</span>.RowDefinitions<span style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;RowDefinition</span> <span style="color:
#ff0000;">Height</span>=<span style="color: #0000ff;">&quot;Auto&quot;</span> <span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;RowDefinition</span> <span style="color: #ff0000;">Height</span>=<span style="color:
#0000ff;">&quot;Auto&quot;</span> <span style="color: #800000;">/&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;RowDefinition</span> <span style="color: #ff0000;">Height</span>=
<span style="color: #0000ff;">&quot;*&quot;</span> <span style="color: #800000;">/&gt;</span></span> <span
style="color: #800000;"><span style="color: #800000;">&lt;RowDefinition</span> <span style="color:
#ff0000;">Height</span>=<span style="color: #0000ff;">&quot;28&quot;</span> <span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;/Grid</span>.RowDefinitions<span style="color: #800000;">&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;Grid</span>.ColumnDefinitions<span style="color: #800000;">&gt;
</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;ColumnDefinition</span> <span
style="color: #ff0000;">Width</span>=<span style="color: #0000ff;">&quot;Auto&quot;</span> <span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;ColumnDefinition</span> <span style="color: #ff0000;">Width</span>=<span style="color:
#0000ff;">&quot;200&quot;</span> <span style="color: #800000;">/&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;/Grid</span>.ColumnDefinitions<span style="color: #800000;">&gt;
</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;Label</span> Grid.<span
style="color: #ff0000;">Row</span>=<span style="color: #0000ff;">&quot;0&quot;</span> Grid.<span style="color:
#ff0000;">Column</span>=<span style="color: #0000ff;">&quot;0&quot;</span> <span style="color:
#ff0000;">Content</span>=<span style="color: #0000ff;">&quot;Name:&quot;</span><span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;Label</span>
Grid.<span style="color: #ff0000;">Row</span>=<span style="color: #0000ff;">&quot;1&quot;</span> Grid.<span
style="color: #ff0000;">Column</span>=<span style="color: #0000ff;">&quot;0&quot;</span> <span style="color:

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

#ff0000;">Content</span>=<span style="color: #0000ff;">&quot;E-Mail:&quot;</span><span style="color:


#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Label</span>
Grid.<span style="color: #ff0000;">Row</span>=<span style="color: #0000ff;">&quot;2&quot;</span> Grid.<span
style="color: #ff0000;">Column</span>=<span style="color: #0000ff;">&quot;0&quot;</span> <span style="color:
#ff0000;">Content</span>=<span style="color: #0000ff;">&quot;Comment:&quot;</span><span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;TextBox</span>
Grid.<span style="color: #ff0000;">Column</span>=<span style="color: #0000ff;">&quot;1&quot;</span> Grid.
<span style="color: #ff0000;">Row</span>=<span style="color: #0000ff;">&quot;0&quot;</span> <span style="color:
#ff0000;">Margin</span>=<span style="color: #0000ff;">&quot;3&quot;</span> <span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;TextBox</span>
Grid.<span style="color: #ff0000;">Column</span>=<span style="color: #0000ff;">&quot;1&quot;</span> Grid.
<span style="color: #ff0000;">Row</span>=<span style="color: #0000ff;">&quot;1&quot;</span> <span style="color:
#ff0000;">Margin</span>=<span style="color: #0000ff;">&quot;3&quot;</span> <span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;TextBox</span>
Grid.<span style="color: #ff0000;">Column</span>=<span style="color: #0000ff;">&quot;1&quot;</span> Grid.
<span style="color: #ff0000;">Row</span>=<span style="color: #0000ff;">&quot;2&quot;</span> <span style="color:
#ff0000;">Margin</span>=<span style="color: #0000ff;">&quot;3&quot;</span> <span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Button</span>
Grid.<span style="color: #ff0000;">Column</span>=<span style="color: #0000ff;">&quot;1&quot;</span> Grid.
<span style="color: #ff0000;">Row</span>=<span style="color: #0000ff;">&quot;3&quot;</span> <span style="color:
#ff0000;">HorizontalAlignment</span>=<span style="color: #0000ff;">&quot;Right&quot;</span> </span>
<span
style="color: #800000;"> <span style="color: #ff0000;">MinWidth</span>=<span style="color:
#0000ff;">&quot;80&quot;</span> <span style="color: #ff0000;">Margin</span>=<span style="color:
#0000ff;">&quot;3&quot;</span> <span style="color: #ff0000;">Content</span>=<span style="color:
#0000ff;">&quot;Send&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/Grid<span style="color: #800000;">&gt;</span></span></span>
</pre></div>
<a name="resize"><h2>Resizable columns or rows</h2></a>
<img src="images/v2_gridsplitter.png"
style="padding-left: 180px;">
<p>WPF provides a control called the <code>GridSplitter</code>. This control is added
like any other control to a cell of the grid. The special thing is that is grabs itself the nearest gridline to change its width
or height when you drag this control around.</p>
<div class="codeblock"><pre class="xaml xaml" style="font-family:
courier new,courier,monospace;"><span style="color: #800000;"><span style="color: #800000;">&lt;Grid<span
style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;Grid</span>.ColumnDefinitions<span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;ColumnDefinition</span> <span style="color:
#ff0000;">Width</span>=<span style="color: #0000ff;">&quot;*&quot;</span><span style="color: #800000;">/&gt;
</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;ColumnDefinition</span> <span
style="color: #ff0000;">Width</span>=<span style="color: #0000ff;">&quot;Auto&quot;</span><span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;ColumnDefinition</span> <span style="color: #ff0000;">Width</span>=<span style="color:
#0000ff;">&quot;*&quot;</span><span style="color: #800000;">/&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/Grid</span>.ColumnDefinitions<span style="color: #800000;">&gt;
</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Label</span> <span style="color:
#ff0000;">Content</span>=<span style="color: #0000ff;">&quot;Left&quot;</span> Grid.<span style="color:
#ff0000;">Column</span>=<span style="color: #0000ff;">&quot;0&quot;</span> <span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;GridSplitter</span> <span style="color: #ff0000;">HorizontalAlignment</span>=<span style="color:
#0000ff;">&quot;Right&quot;</span> </span>
<span style="color: #800000;"> <span style="color:
#ff0000;">VerticalAlignment</span>=<span style="color: #0000ff;">&quot;Stretch&quot;</span> </span>
<span
style="color: #800000;"> Grid.<span style="color: #ff0000;">Column</span>=<span style="color:
#0000ff;">&quot;1&quot;</span> <span style="color: #ff0000;">ResizeBehavior</span>=<span style="color:
#0000ff;">&quot;PreviousAndNext&quot;</span></span>
<span style="color: #800000;"> <span style="color:
#ff0000;">Width</span>=<span style="color: #0000ff;">&quot;5&quot;</span> <span style="color:
#ff0000;">Background</span>=<span style="color: #0000ff;">&quot;#FFBCBCBC&quot;</span><span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Label</span>

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

<span style="color: #ff0000;">Content</span>=<span style="color: #0000ff;">&quot;Right&quot;</span> Grid.<span


style="color: #ff0000;">Column</span>=<span style="color: #0000ff;">&quot;2&quot;</span> <span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/Grid<span
style="color: #800000;">&gt;</span></span></span>
</pre></div>
<p>The best way to align a grid splitter is to place
it in its own auto-sized column. Doing it this way prevents overlapping to adjacent cells. To ensure that the grid splitter
changes the size of the previous and next cell you have to set the <code>ResizeBehavior</code> to
<code>PreviousAndNext</code>.</p>
<p>The splitter normally recognizes the resize direction according to the ratio
between its height and width. But if you like you can also manually set the <code> ResizeDirection</code> to
<code>Columns</code> or <code>Rows</code>.
<div class="codeblock"><pre class="xaml xaml" style="font-family:
courier new,courier,monospace;"><span style="color: #800000;"><span style="color:
#800000;">&lt;GridSplitter</span> <span style="color: #ff0000;">ResizeDirection</span>=<span style="color:
#0000ff;">&quot;Columns&quot;</span><span style="color: #800000;">/&gt;</span></span>
</pre></div>
<a
name="sharedsize"><h2>How to share the width of a column over multiple grids</h2></a>
<p>The shared size feature
of the grid layout allows it to synchronize the width of columns over multiple grids. The feature is very useful if you
want to realize a multi-column listview by using a grid as layout panel within the data template. Because each item
contains its own grid, the columns will not have the same width.</p>
<p>By setting the attached property
<code>Grid.IsSharedSizeScope</code> to <code>true</code> on a parent element you define a scope within the
column-widths are shared.</p>
<p>To synchronize the width of two columndefinitions, set the
<code>SharedSizeGroup</code> to the same name.</p>
<div class="codeblock"><pre class="xaml xaml" style="font-
family: courier new,courier,monospace;"> <span style="color: #800000;"><span style="color:
#800000;">&lt;ItemsControl</span> Grid.<span style="color: #ff0000;">IsSharedSizeScope</span>=<span
style="color: #0000ff;">&quot;True&quot;</span> <span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;ItemsControl</span>.ItemTemplate<span style="color:
#800000;">&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;DataTemplate<span style="color: #800000;">&gt;</span></span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;Grid<span style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Grid</span>.ColumnDefinitions<span
style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;ColumnDefinition</span> <span style="color: #ff0000;">SharedSizeGroup</span>=<span
style="color: #0000ff;">&quot;FirstColumn&quot;</span> <span style="color: #ff0000;">Width</span>=<span
style="color: #0000ff;">&quot;Auto&quot;</span><span style="color: #800000;">/&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;ColumnDefinition</span> <span style="color:
#ff0000;">Width</span>=<span style="color: #0000ff;">&quot;*&quot;</span><span style="color: #800000;">/&gt;
</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/Grid</span>.ColumnDefinitions<span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;TextBlock</span> <span style="color:
#ff0000;">Text</span>=<span style="color: #0000ff;">&quot;{Binding Path=Key}&quot;</span> <span style="color:
#ff0000;">TextWrapping</span>=<span style="color: #0000ff;">&quot;Wrap&quot;</span><span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;TextBlock</span> <span style="color: #ff0000;">Text</span>=<span style="color: #0000ff;">&quot;
{Binding Path=Value}&quot;</span> Grid.<span style="color: #ff0000;">Column</span>=<span style="color:
#0000ff;">&quot;1&quot;</span> <span style="color: #ff0000;">TextWrapping</span>=<span style="color:
#0000ff;">&quot;Wrap&quot;</span><span style="color: #800000;">/&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/Grid<span style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/DataTemplate<span style="color: #800000;">&gt;
</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/ItemsControl</span>.ItemTemplate<span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;/ItemsControl<span style="color: #800000;">&gt;
</span></span></span>
</pre></div><h3>Useful Hints</h3>
<p>Columns and rows that participate in size-sharing do
not respect Star sizing. In the size-sharing scenario, Star sizing is treated as Auto. Since TextWrapping on TextBlocks
within an SharedSize column does not work you can exclude your last column from the shared size. This often helps to
resolve the problem.</p>
<a name="gridlength"><h2>Using GridLenghts from code</h2></a>
<p>If you want to add
columns or rows by code, you can use the <code>GridLength</code> class to define the differenz types of sizes.</p>

<br/>
<table style="margin-left: 30px;">
<tr>
<td style="width: 100px;"><b>Auto sized</b></td> <td>

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

<code>GridLength.Auto</code>
</td>
</tr>
<tr>
<td><b>Star sized</b></td>
<td><code>new
GridLength(1,GridUnitType.Star)</td> </tr>
<tr>
<td><b>Fixed size</b></td>
<td><code>new
GridLength(100,GridUnitType.Pixel)</td> </tr>
</table>
<div class="codeblock"><pre class="csharp csharp"
style="font-family: courier new,courier,monospace;">Grid grid <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> Grid<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;
</span>;
ColumnDefinition col1 <span style="color: #008000;">=</span> <a href="http://www.google.com/search?
q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight: bold;">new</span></a>
ColumnDefinition<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
col1.
<span style="color: #0000FF;">Width</span> <span style="color: #008000;">=</span> GridLength.<span
style="color: #0000FF;">Auto</span>;
ColumnDefinition col2 <span style="color: #008000;">=</span> <a
href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-weight:
bold;">new</span></a> ColumnDefinition<span style="color: #000000;">&#40;</span><span style="color:
#000000;">&#41;</span>;
col2.<span style="color: #0000FF;">Width</span> <span style="color: #008000;">=
</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #0000ff; font-
weight: bold;">new</span></a> GridLength<span style="color: #000000;">&#40;</span><span style="color:
#FF0000;">1</span>,GridUnitType.<span style="color: #0000FF;">Star</span><span style="color: #000000;">&#41;
</span>;
grid.<span style="color: #0000FF;">ColumnDefinitions</span>.<span style="color: #0000FF;">Add</span>
<span style="color: #000000;">&#40;</span>col1<span style="color: #000000;">&#41;</span>;
grid.<span
style="color: #0000FF;">ColumnDefinitions</span>.<span style="color: #0000FF;">Add</span><span style="color:
#000000;">&#40;</span>col2<span style="color: #000000;">&#41;</span>;
</pre></div>
<h2>More on this
topic</h2>
<a href="GridSplitter.html">How to create a resizable column</a>

http://www.wpftutorial.net/GridLayout.html
Sun, 16 Feb 2014 08:23:05 +01002011-10-03 09:22:29
moc@zuehlke.com (Christian Moser)
<h1>Introduction to Windows Presentation Foundation</h1>

<h2>Overview</h2>
<p>The Windows Presentation Foundation is Microsofts next generation UI framework to create
applications with a rich user experience. It is part of the .NET framework 3.0 and higher.</p>
<p>WPF combines
application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based
rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution
independent.</p>
<p>The followinig illustration gives you an overview of the main new features of WPF</p>
<img
src="images/wpfMainFeatures.png" style="padding: 10px; padding-left: 120px;" />
<h2>Separation of Appearance and
Behavior</h2>
<p>WPF separates the appearance of an user interface from its behavior. The appearance is generally
specified in the <a href="XAML.html">Extensible Application Markup Language</a> (XAML), the behavior is
implemented in a managed programming language like C# or Visual Basic. The two parts are tied together by
databinding, events and commands. The separation of appearance and behavior brings the following benefits:
<ul>
<li>Appearance and behaviour are loosely coupled</li>
<li>Designers and developers can work on separate models.
</li>
<li>Graphical design tools can work on simple XML documents instead of parsing code.</li>
</ul>
</p>

<h2>Rich composition</h2>
<p>Controls in WPF are extremely composable. You can define almost any type of
controls as content of another. Although these flexibility sounds horrible to designers, its a very powerful feature if you
use it appropriate. Put an image into a button to create an image button, or put a list of videos into a combobox to
choose a video file.</p>
<img style="padding-left: 150px;" src="images/playsound_button.png" />
<div
class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color:
#800000;"><span style="color: #800000;">&lt;Button<span style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;StackPanel</span> <span style="color:
#ff0000;">Orientation</span>=<span style="color: #0000ff;">&quot;Horizontal&quot;</span><span style="color:
#800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Image</span>
<span style="color: #ff0000;">Source</span>=<span style="color: #0000ff;">&quot;speaker.png&quot;</span> <span
style="color: #ff0000;">Stretch</span>=<span style="color: #0000ff;">&quot;Uniform&quot;</span><span
style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;TextBlock</span> <span style="color: #ff0000;">Text</span>=<span style="color:
#0000ff;">&quot;Play Sound&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/StackPanel<span style="color: #800000;">&gt;</span></span>
</span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/Button<span style="color:
#800000;">&gt;</span></span></span>
</pre></div>
<h2>Highly customizable</h2>
<p>Because of the strict
separation of appearance and behavior you can easily change the look of a control. The concept of <a

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

href="Styles.html">styles</a> let you skin controls almost like CSS in HTML. <a
href="Templates.html">Templates</a> let you replace the entire appearance of a control.</p>
<p>The following
example shows an default WPF button and a customized button.</p>
<img style="padding-left: 100px;"
src="images/introduction_buttons.png" />
<h2>Resolution independence</h2>
<p>All measures in WPF are logical
units - not pixels. A logical unit is a 1/96 of an inch. If you increase the resolution of your screen, the user interface
stays the same size - it just gets crispier. Since WPF builds on a vector based rendering engine it's incredibly easy to
build scaleable user interfaces.</p>
<img style="padding-left: 120px;" src="images/wpf_scaling.png" />
http://www.wpftutorial.net/WPFIntroduction.html
Sun, 16 Feb 2014 08:23:05 +01002011-08-15 18:49:42
moc@zuehlke.com (Christian Moser)
<h1>Context Menus in WPF</h1> <p>Context Menus can be defined on any
WPF controls by setting the <code>ContextMenu</code> property to an instance of a <code>ContextMenu</code>.
The items of a context menu are normal <code>MenuItems</code>.</p> <img style="padding: 10px; padding-left:
120px;" src='images/contextmenu.jpg' /> <div class="codeblock"><pre class="xaml xaml" style="font-family: courier
new,courier,monospace;"> <span style="color: #800000;"><span style="color: #800000;">&lt;RichTextBox<span
style="color: #800000;">&gt;</span></span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;RichTextBox</span>.ContextMenu<span style="color: #800000;">&gt;</span></span> <span
style="color: #800000;"><span style="color: #800000;">&lt;ContextMenu<span style="color: #800000;">&gt;</span>
</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;MenuItem</span> <span
style="color: #ff0000;">Command</span>=<span style="color: #0000ff;">&quot;Cut&quot;</span><span
style="color: #800000;">&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span>.Icon<span style="color: #800000;">&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;Image</span> <span style="color: #ff0000;">Source</span>=<span
style="color: #0000ff;">&quot;Images/cut.png&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/MenuItem</span>.Icon<span style="color:
#800000;">&gt;</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;/MenuItem<span
style="color: #800000;">&gt;</span></span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span> <span style="color: #ff0000;">Command</span>=<span style="color:
#0000ff;">&quot;Copy&quot;</span><span style="color: #800000;">&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;MenuItem</span>.Icon<span style="color: #800000;">&gt;</span>
</span> <span style="color: #800000;"><span style="color: #800000;">&lt;Image</span> <span style="color:
#ff0000;">Source</span>=<span style="color: #0000ff;">&quot;Images/copy.png&quot;</span> <span style="color:
#800000;">/&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;/MenuItem</span>.Icon<span style="color: #800000;">&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;/MenuItem<span style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;MenuItem</span> <span style="color:
#ff0000;">Command</span>=<span style="color: #0000ff;">&quot;Paste&quot;</span><span style="color:
#800000;">&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span>.Icon<span style="color: #800000;">&gt;</span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;Image</span> <span style="color: #ff0000;">Source</span>=<span
style="color: #0000ff;">&quot;Images/paste.png&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/MenuItem</span>.Icon<span style="color:
#800000;">&gt;</span></span> <span style="color: #800000;"><span style="color: #800000;">&lt;/MenuItem<span
style="color: #800000;">&gt;</span></span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;/ContextMenu<span style="color: #800000;">&gt;</span></span></span> <span style="color:
#800000;"><span style="color: #800000;">&lt;/RichTextBox</span>.ContextMenu<span style="color:
#800000;">&gt;</span></span> <span style="color: #800000;"><span style="color:
#800000;">&lt;/RichTextBox<span style="color: #800000;">&gt;</span></span></span> </pre></div> <h2>Show
ContextMenus on a disabled controls</h2> <p>If you rightclick on a disabled control, no context menu is shown by
default. To enable the context menu for disabled controls you can set the <code>ShowOnDisabled</code> attached
property of the <code>ContextMenuService</code> to <code>True</code>.</p> <div class="codeblock"><pre
class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color: #800000;"><span
style="color: #800000;">&lt;RichTextBox</span> <span style="color: #ff0000;">IsEnabled</span>=<span
style="color: #0000ff;">&quot;False&quot;</span> ContextMenuService.<span style="color:
#ff0000;">ShowOnDisabled</span>=<span style="color: #0000ff;">&quot;True&quot;</span><span style="color:
#800000;">&gt;</span></span> <span style="color: #800000;"><span style="color:

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

#800000;">&lt;RichTextBox</span>.ContextMenu<span style="color: #800000;">&gt;</span></span>


<span
style="color: #800000;"><span style="color: #800000;">&lt;ContextMenu<span style="color: #800000;">&gt;</span>
</span></span>
...
<span style="color: #800000;"><span style="color: #800000;">&lt;/ContextMenu<span
style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/RichTextBox</span>.ContextMenu<span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;/RichTextBox<span style="color: #800000;">&gt;
</span></span></span>
</pre></div>
<h2>Merge ContextMenus</h2>
<p>If you want to fill a menu with items
coming from multiple sources, you can use the <code>CompositeCollection</code> to merge multiple collection into
one.</p>
<div class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;">

<span style="color: #800000;"><span style="color: #800000;">&lt;Window</span> <span style="color:
#ff0000;">xmlns</span>=<span style="color:
#0000ff;">&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span></span>
<span
style="color: #800000;"> <span style="color: #ff0000;">xmlns:x</span>=<span style="color:
#0000ff;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span></span>
<span style="color:
#800000;"> <span style="color: #ff0000;">xmlns:sys</span>=<span style="color: #0000ff;">&quot;clr-
namespace:System;assembly=mscorlib&quot;</span><span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;Grid</span> <span style="color:
#ff0000;">Background</span>=<span style="color: #0000ff;">&quot;Transparent&quot;</span><span style="color:
#800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;Grid</span>.Resources<span style="color: #800000;">&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;x:Array</span> <span style="color: #ff0000;">Type</span>=<span
style="color: #0000ff;">&quot;{x:Type sys:Object}&quot;</span> <span style="color: #ff0000;">x:Key</span>=
<span style="color: #0000ff;">&quot;extensions&quot;</span><span style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Separator</span> <span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span> <span style="color: #ff0000;">Header</span>=<span style="color:
#0000ff;">&quot;Extension MenuItem 1&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;MenuItem</span> <span style="color:
#ff0000;">Header</span>=<span style="color: #0000ff;">&quot;Extension MenuItem 2&quot;</span> <span
style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span> <span style="color: #ff0000;">Header</span>=<span style="color:
#0000ff;">&quot;Extension MenuItem 3&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;/x:Array<span style="color: #800000;">&gt;</span>
</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/Grid</span>.Resources<span
style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;Grid</span>.ContextMenu<span style="color: #800000;">&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;ContextMenu<span style="color: #800000;">&gt;</span></span>
</span>
<span style="color: #800000;"><span style="color: #800000;">&lt;ContextMenu</span>.ItemsSource<span
style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;CompositeCollection<span style="color: #800000;">&gt;</span></span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;MenuItem</span> <span style="color: #ff0000;">Header</span>=
<span style="color: #0000ff;">&quot;Standard MenuItem 1&quot;</span> <span style="color: #800000;">/&gt;
</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;MenuItem</span> <span
style="color: #ff0000;">Header</span>=<span style="color: #0000ff;">&quot;Standard MenuItem 2&quot;</span>
<span style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span> <span style="color: #ff0000;">Header</span>=<span style="color:
#0000ff;">&quot;Standard MenuItem 3&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;CollectionContainer</span> <span style="color:
#ff0000;">Collection</span>=<span style="color: #0000ff;">&quot;{StaticResource extensions}&quot;</span> <span
style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/CompositeCollection<span style="color: #800000;">&gt;</span></span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/ContextMenu</span>.ItemsSource<span style="color:
#800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/ContextMenu<span style="color: #800000;">&gt;</span></span></span>
<span style="color:

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

#800000;"><span style="color: #800000;">&lt;/Grid</span>.ContextMenu<span style="color: #800000;">&gt;


</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/Grid<span style="color:
#800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/Window<span style="color: #800000;">&gt;</span></span></span>
</pre></div>
<h2
id="mvvm">How to bind a Command on a ContextMenu within a DataTemplate using MVVM</h2>
<p>Since the
<code>Popuup</code> control has it's separate visual tree, you cannot use find ancestor to find the
<code>Grid</code>. The trick here is to use the <code>PlacementTarget</code> property, that contains the element,
the ContextMenu is aligned to, what is the <code>Grid</code> in our case.</p>
<p>But this is only half of the
solution. Because of the data template, the <code>DataContext</code> is set to a dataitem, and not the view model. So
you need another relative source lookup, to find the view model. Trick Nr. 2 is to use the <code>Tag</code> property
to bind the view model from outside to the grid, which is the <code>PlacementTarget</code> used above. And there
we are.</p>
<div class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;">

<span style="color: #800000;"><span style="color: #800000;">&lt;DataTemplate<span style="color: #800000;">&gt;
</span></span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Grid</span> <span
style="color: #ff0000;">Tag</span>=<span style="color: #0000ff;">&quot;{Binding DataContext, RelativeSource=
{RelativeSource AncestorType={x:Type ListBox}}}&quot;</span><span style="color: #800000;">&gt;</span>
</span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Grid</span>.ContextMenu<span
style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;ContextMenu</span> <span style="color: #ff0000;">DataContext</span>=<span style="color:
#0000ff;">&quot;{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}&quot;</span><span
style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span> <span style="color: #ff0000;">Content</span>=<span style="color:
#0000ff;">&quot;Cut&quot;</span> <span style="color: #ff0000;">Command</span>=<span style="color:
#0000ff;">&quot;{Binding CutCommand}&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;MenuItem</span> <span style="color:
#ff0000;">Content</span>=<span style="color: #0000ff;">&quot;Copy&quot;</span> <span style="color:
#ff0000;">Command</span>=<span style="color: #0000ff;">&quot;{Binding CopyCommand}&quot;</span> <span
style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;MenuItem</span> <span style="color: #ff0000;">Content</span>=<span style="color:
#0000ff;">&quot;Paste&quot;</span> <span style="color: #ff0000;">Command</span>=<span style="color:
#0000ff;">&quot;{Binding PasteCommand}&quot;</span> <span style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/ContextMenu<span style="color: #800000;">&gt;
</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/Grid</span>.ContextMenu<span style="color: #800000;">&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/Grid<span style="color: #800000;">&gt;</span></span></span>

<span style="color: #800000;"><span style="color: #800000;">&lt;/DataTemplate<span style="color: #800000;">&gt;
</span></span></span>
</pre></div>
<h2>How to open a context menu from code</h2>
<p>The following sample
shows you how to open a context menu of a control programmatically:</p>
<div class="codeblock"><pre
class="csharp csharp" style="font-family: courier new,courier,monospace;"> <span style="color: #0600FF; font-
weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">void</span>
OpenContextMenu<span style="color: #000000;">&#40;</span>FrameworkElement element<span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight:
bold;">if</span><span style="color: #000000;">&#40;</span> element.<span style="color:
#0000FF;">ContextMenu</span> <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-
weight: bold;">null</span> <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span>
element.<span style="color: #0000FF;">ContextMenu</span>.<span style="color:
#0000FF;">PlacementTarget</span> <span style="color: #008000;">=</span> element;
element.<span style="color:
#0000FF;">ContextMenu</span>.<span style="color: #0000FF;">IsOpen</span> <span style="color: #008000;">=
</span> true;
<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
</pre>
</div>
http://www.wpftutorial.net/ContextMenu.html
Sun, 16 Feb 2014 08:23:05 +01002011-05-23 08:36:43
moc@zuehlke.com (Christian Moser)
<h1>WPF ListBox Control</h1> <img style="padding-left: 80px;"
src="images/listbox1.png" /> <h2>Introduction</h2> <p>The ListBox control displays a list of items. The user can
select one or multiple items depending on the selection mode. The typical usage of a listbox in WPF is to bind its items
to a list of business objects and display them by applying a data template.</p>
<br/>
<div class="codeblock"><pre

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color: #800000;"><span


style="color: #800000;">&lt;ListBox</span> <span style="color: #ff0000;">Margin</span>=<span style="color:
#0000ff;">&quot;20&quot;</span><span style="color: #800000;">&gt;</span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;ListBoxItem<span style="color: #800000;">&gt;</span></span>
</span>New York<span style="color: #800000;"><span style="color: #800000;">&lt;/ListBoxItem<span style="color:
#800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;ListBoxItem<span style="color: #800000;">&gt;</span></span></span>Los Angeles<span
style="color: #800000;"><span style="color: #800000;">&lt;/ListBoxItem<span style="color: #800000;">&gt;</span>
</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;ListBoxItem<span style="color:
#800000;">&gt;</span></span></span>Paris<span style="color: #800000;"><span style="color:
#800000;">&lt;/ListBoxItem<span style="color: #800000;">&gt;</span></span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;ListBoxItem<span style="color: #800000;">&gt;</span></span>
</span>Zurich<span style="color: #800000;"><span style="color: #800000;">&lt;/ListBoxItem<span style="color:
#800000;">&gt;</span></span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/ListBox<span style="color: #800000;">&gt;</span></span></span>
</pre></div>
<h2>How to define
a Trigger for IsSelected in the DataTemplate</h2>
<p>If you want to change the appearance of a ListBoxItem when it
is selected, you have to bind the IsSelected property of the ListBoxItem. But this is a bit tricky, you have to use a
relative source with FindAcestor to navigate up the visual tree until you reach the ListBoxItem.</p>
<div
class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color:
#800000;"><span style="color: #800000;">&lt;DataTemplate</span> <span style="color: #ff0000;">x:Key</span>=
<span style="color: #0000ff;">&quot;myDataTemplate&quot;</span><span style="color: #800000;">&gt;</span>
</span>
<span style="color: #800000;"><span style="color: #800000;">&lt;Border</span> <span style="color:
#ff0000;">x:Name</span>=<span style="color: #0000ff;">&quot;border&quot;</span> <span style="color:
#ff0000;">Height</span>=<span style="color: #0000ff;">&quot;50&quot;</span><span style="color: #800000;">&gt;
</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;TextBlock</span> <span
style="color: #ff0000;">Text</span>=<span style="color: #0000ff;">&quot;{Binding Text}&quot;</span> <span
style="color: #800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/Border<span style="color: #800000;">&gt;</span></span></span>
<span style="color: #800000;">
<span style="color: #800000;">&lt;DataTemplate</span>.Triggers<span style="color: #800000;">&gt;</span></span>

<span style="color: #800000;"><span style="color: #800000;">&lt;DataTrigger</span> <span style="color:
#ff0000;">Binding</span>=<span style="color: #0000ff;">&quot;{Binding RelativeSource=</span>
<span
style="color: #800000;"> {RelativeSource Mode=FindAncestor, AncestorType=</span>
<span style="color:
#800000;"> {x:Type ListBoxItem}},Path=IsSelected}&quot;</span> <span style="color: #ff0000;">Value</span>=
<span style="color: #0000ff;">&quot;True&quot;</span><span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;Setter</span> <span style="color:
#ff0000;">TargetName</span>=<span style="color: #0000ff;">&quot;border&quot;</span> <span style="color:
#ff0000;">Property</span>=<span style="color: #0000ff;">&quot;Height&quot;</span> <span style="color:
#ff0000;">Value</span>=<span style="color: #0000ff;">&quot;100&quot;</span><span style="color:
#800000;">/&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;/DataTrigger<span style="color: #800000;">&gt;</span></span></span>
<span style="color:
#800000;"><span style="color: #800000;">&lt;/DataTemplate</span>.Triggers<span style="color: #800000;">&gt;
</span></span>
<span style="color: #800000;"><span style="color: #800000;">&lt;/DataTemplate<span style="color:
#800000;">&gt;</span></span></span>
</pre></div>
<h2>More articles about the ListBox</h2>
[sublist]

http://www.wpftutorial.net/ListBox.html
Sun, 16 Feb 2014 08:23:05 +01002011-05-23 08:36:27
moc@zuehlke.com
(Christian Moser)
<h1>Designtime vs. Runtime</h1>
<h2>Introduction</h2>
<p>An application often looks great at
runtime, but when you open it in a designer like VisualStudio or Expression Blend, the experience is quite different.
The rason is that at designtime:
<ul>
<li><b>UserControls are not embedded in a parent view</b>
<ul>
<li>Width and
Height are not set</li>
</ul>
</li>
<li><b>Constructor of the root-element is not called</b>
<ul>
<li>Root Element is
replaced by the designer</li>
<li>ViewModel is not created</li>
</ul>
<li><b>Controls behave different</b>
<ul>
<li>No mouse and keyboard events</li>
<li>Design time extensions loaded</li>
</ul>
</li>
</ul>
This can be kind of
annoying, especially if you want to edit data templates or layout controls.</p>
<img
src="images/designtimevsruntime.png" style="margin-left: 50px;" />
<h2>Designtime attributes</h2>
<p>To improve
the design experience, Microsoft provides special designtime attributes that can be added to any WPF element and
serve as a hint for the design tool.</p>
<p>The designtime attributes are defined in a special namespace, that is usually

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

mapped to the <code>d:</code> prefix. To tell the XAML parser not to interprete these attributes at runtime, the
markup compatibility namespace is mapped to <code>mc:</code> and with the <code>mc:Ignorable="d"</code>
instruction, the <code>d:</code> namespace is excluded.</p>
<div class="codeblock"><pre class="xaml xaml"
style="font-family: courier new,courier,monospace;"> <span style="color: #800000;"><span style="color:
#800000;">&lt;Window</span> </span>
<span style="color: #800000;"> xmlns:d =<span style="color:
#0000ff;">&quot;http://schemas.microsoft.com/expression/blend/2008&quot;</span></span>
<span style="color:
#800000;"> <span style="color: #ff0000;">xmlns:mc</span>=<span style="color:
#0000ff;">&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;</span></span>
<span
style="color: #800000;"> <span style="color: #ff0000;">mc:Ignorable</span>=<span style="color:
#0000ff;">&quot;d&quot;</span> <span style="color: #800000;">/&gt;</span></span>
</pre></div>
<h2>
<code>d:DesignHeight</code> and <code>d:DesignWidth</code></h2>
<p>The <code>d:DesignHeight</code> and
<code>d:DesignWidth</code> sets a fixed height and width for the element at designtime</p>
<div
class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color:
#800000;"><span style="color: #800000;">&lt;UserControl</span></span>
<span style="color: #800000;"> <span
style="color: #ff0000;">xmlns</span>=<span style="color: #0000ff;">&quot;http://schemas.microsoft.com/...&quot;
</span></span>
<span style="color: #800000;"> <span style="color: #ff0000;">xmlns:x</span>=<span style="color:
#0000ff;">&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span></span>
<span style="color:
#800000;"> <span style="color: #ff0000;">d:DesignWidth</span>=<span style="color: #0000ff;">&quot;640&quot;
</span> <span style="color: #ff0000;">d:DesignHeight</span>=<span style="color: #0000ff;">&quot;480&quot;
</span> <span style="color: #800000;">&gt;</span></span>
<span style="color: #800000;"><span style="color:
#800000;">&lt;UserControl</span> <span style="color: #800000;">/&gt;</span></span>
</pre></div>
<h2>
<code>d:LayoutOverrides</code></h2>
<p>If a property is set to a fixed value at runtime, but you want to override it at
designtime, you can use the <code>d:LayoutOverrides</code> attribute. All properties that should be ignored at
designtime can be listed, separated by a semicolon.</p>
<div class="codeblock"><pre class="xaml xaml" style="font-
family: courier new,courier,monospace;"> <span style="color: #800000;"><span style="color:
#800000;">&lt;Border</span> <span style="color: #ff0000;">Height</span>=<span style="color:
#0000ff;">&quot;250&quot;</span> <span style="color: #ff0000;">Width</span>=<span style="color:
#0000ff;">&quot;160&quot;</span> <span style="color: #ff0000;">d:LayoutOverrides</span>=<span style="color:
#0000ff;">&quot;Width, Height&quot;</span> <span style="color: #800000;">&gt;</span></span>
<span
style="color: #800000;"><span style="color: #800000;">&lt;/Border<span style="color: #800000;">&gt;</span>
</span></span>
</pre></div>
<h2>Additional Resources</h2>
<a href="http://msdn.microsoft.com/en-
us/library/ff602277(v=vs.95).aspx">MSDN Designtime-attributes</a>
<p><b>This article is still under
construction</b></p>
http://www.wpftutorial.net/DesigntimeVsRuntime.html
Sun, 16 Feb 2014 08:23:05 +01002011-
05-04 15:22:02
moc@zuehlke.com (Christian Moser)
<h1>Templates and Styles</h1>
<p>One of WPF's most
powerful feature is the ability to completely replace the look and feel of user interface elements.</p>
<h2>Styles</h2>

<p>The concept of styles let you remove all properties values from the individual user interface elements and combine
them into a style. A style consists of a list of property setters. If you apply a style it <strong>sets the properties on the
user interface element</strong> to the styles' values. The idea is quite similar to Cascading Styles Sheets (CSS) in web
development.<br/>
Using styles gives you the following advantages:
<ul>
<li>Removes redundancy from your
code</li>
<li>Let you change the appearance of a set of controls from a single point</li>
<li>Gives you the possibility
to swap the style at runtime</li>
</ul>
</p>
<a class="articleref" href="Styles.html">Learn more about Styles</a>

<h2>Templates</h2>
<p>An element like a button consists of multpiple composed parts: A border, a chrome and a
content presenter. With styles you can only change the appearance from "outside" by setting public properties. With a
template you can <b>replace parts inside a user interface element.</b>.<br/>
Using templates gives you the following
advantages:
<ul>
<li>Change the parts inside a user interface element</li>
<li>Reduce the numbers custom
controls</li>
</ul>
</p>
<a class="articleref" href="Templates.html">Learn more about Templates</a>

http://www.wpftutorial.net/TemplatesStyles.html
Sun, 16 Feb 2014 08:23:05 +01002011-05-03 10:40:49
moc@zuehlke.com (Christian Moser)
<h1>Drag and Drop in WPF</h1> <h2>Introduction</h2> <p>Drag&Drop can
drasticly improve the productiviy and user experience of a software. But only a few programmers provide drag and
drop functionality in their applications, because they think its much more dificult than it really is. This article shows
how simple drag and drop can be implemented in WPF.</p> <h2>Drag&Drop in 6 Steps</h2> <ol> <li>Detect a drag
as a combinatination of <b>MouseMove</b> and <b>MouseLeftButtonDown</b></li> <li>Find the data you want to
drag and create a <b>DataObject</b> that contains the format, the data and the allowed effects.</li>
<li>Initiate the
dragging by calling <b>DoDragDrop()</b></li>
<li>Set the <b>AllowDrop</b> property to <b>True</b> on the

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

elements you want to allow dropping.</li>


<li>Register a handler to the <b>DragEnter</b> event to detect a dragging
over the drop location. Check the format and the data by calling <b>GetDataPresent()</b> on the event args. If the data
can be dropped, set the <b>Effect</b> property on the event args to display the appropriate mouse cursor.</li>
<li>When the user releases the mouse button the <b>DragDrop</b> event is called. Get the data by calling the
<b>GetData()</b> method on the <b>Data</b> object provided in the event args.</b> </ol>
<p>...and that's all the
magic.</p>
<h2>Drag</h2>
<p>To start the drag operation, we have to detect a mouse move while the left mouse
button is pressed. To do this we have to hook up handlers on the <code>PreviewMouseMove</code> and
<code>PreviewMouseLeftButtonDown</code> events.</p>
<p>To prevent occasionally drags, its a good design to not
start the drag operation until the user has moved the mouse cursor by a couple of pixels. WPF provides a constant that
contains the amount of pixel that Windows uses.</p>
<p>When the drag is initiated, we need to specify the data we
want to drag. In our case its the data of the <code>ListViewItem</code> we dragged. We find the
<code>ListViewItem</code> in the <code>OriginalSource</code> of the mouse event args. By calling
<code>ItemContainerGenerator.ItemFromContainer</code> we get the data behind the <code>ListViewItem</code>.
</p>
<p>Create a <code>DataObject</code> to transport the data to the drop location. The constructor takes two
arguments. A string that describes the format and the data we want to drag.</p>
<br/>
<div class="codeblock"><pre
class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color: #800000;"><span
style="color: #800000;">&lt;ListView</span> <span style="color: #ff0000;">x:Name</span>=<span style="color:
#0000ff;">&quot;DragList&quot;</span> </span>
<span style="color: #800000;"> <span style="color:
#ff0000;">PreviewMouseLeftButtonDown</span>=<span style="color:
#0000ff;">&quot;List_PreviewMouseLeftButtonDown&quot;</span> </span>
<span style="color: #800000;"> <span
style="color: #ff0000;">PreviewMouseMove</span>=<span style="color: #0000ff;">&quot;List_MouseMove&quot;
</span><span style="color: #800000;">/&gt;</span></span>
</pre></div>
<div class="codeblock"><pre class="csharp
csharp" style="font-family: courier new,courier,monospace;"> <span style="color: #0600FF; font-weight:
bold;">private</span> <span style="color: #0600FF; font-weight: bold;">void</span>
List_PreviewMouseLeftButtonDown<span style="color: #000000;">&#40;</span><span style="color: #2b91af; font-
weight: bold;">object</span> sender, MouseButtonEventArgs e<span style="color: #000000;">&#41;</span>
<span
style="color: #000000;">&#123;</span>
<span style="color: #008000;">// Store the mouse position</span>
startPoint
<span style="color: #008000;">=</span> e.<span style="color: #0000FF;">GetPosition</span><span style="color:
#000000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">null</span><span style="color:
#000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
</pre></div>
<div class="codeblock"><pre
class="csharp csharp" style="font-family: courier new,courier,monospace;"> <span style="color: #0600FF; font-
weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">void</span> List_MouseMove<span
style="color: #000000;">&#40;</span><span style="color: #2b91af; font-weight: bold;">object</span> sender,
MouseEventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #008000;">// Get the current mouse position</span>
Point mousePos <span style="color:
#008000;">=</span> e.<span style="color: #0000FF;">GetPosition</span><span style="color: #000000;">&#40;
</span><span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #000000;">&#41;</span>;
Vector diff <span style="color: #008000;">=</span> startPoint <span style="color: #008000;">-</span> mousePos;
<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #000000;">&#40;</span>e.<span
style="color: #0000FF;">LeftButton</span> <span style="color: #008000;">==</span> MouseButtonState.<span
style="color: #0000FF;">Pressed</span> <span style="color: #008000;">&amp;&amp;</span>
Math.<span
style="color: #0000FF;">Abs</span><span style="color: #000000;">&#40;</span>diff.<span style="color:
#0000FF;">X</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">&gt;</span>
SystemParameters.<span style="color: #0000FF;">MinimumHorizontalDragDistance</span> ||
Math.<span
style="color: #0000FF;">Abs</span><span style="color: #000000;">&#40;</span>diff.<span style="color:
#0000FF;">Y</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">&gt;</span>
SystemParameters.<span style="color: #0000FF;">MinimumVerticalDragDistance</span> <span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #008000;">// Get the
dragged ListViewItem</span>
ListView listView <span style="color: #008000;">=</span> sender <span style="color:
#0600FF; font-weight: bold;">as</span> ListView;
ListViewItem listViewItem <span style="color: #008000;">=
</span> FindAnchestor<span style="color: #008000;">&lt;</span>ListViewItem<span style="color: #008000;">&gt;
</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;
</span>DependencyObject<span style="color: #000000;">&#41;</span>e.<span style="color:
#0000FF;">OriginalSource</span><span style="color: #000000;">&#41;</span>;
<span style="color: #008000;">//

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

Find the data behind the ListViewItem</span>


Contact contact <span style="color: #008000;">=</span> <span
style="color: #000000;">&#40;</span>Contact<span style="color: #000000;">&#41;</span>listView.<span
style="color: #0000FF;">ItemContainerGenerator</span>.
<span style="color: #0000FF;">ItemFromContainer</span>
<span style="color: #000000;">&#40;</span>listViewItem<span style="color: #000000;">&#41;</span>;
<span
style="color: #008000;">// Initialize the drag &amp; drop operation</span>
DataObject dragData <span style="color:
#008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color:
#0000ff; font-weight: bold;">new</span></a> DataObject<span style="color: #000000;">&#40;</span><span
style="color: #666666;">&quot;myFormat&quot;</span>, contact <span style="color: #000000;">&#41;</span>;
DragDrop.<span style="color: #0000FF;">DoDragDrop</span><span style="color: #000000;">&#40;
</span>listViewItem, dragData, DragDropEffects.<span style="color: #0000FF;">Move</span><span style="color:
#000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span> <span style="color: #000000;">&#125;
</span>
</pre></div>
<div class="codeblock"><pre class="csharp csharp" style="font-family: courier
new,courier,monospace;"> <span style="color: #008000;">// Helper to search up the VisualTree</span>
<span
style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight:
bold;">static</span> T FindAnchestor<span style="color: #008000;">&lt;</span>T<span style="color:
#008000;">&gt;</span><span style="color: #000000;">&#40;</span>DependencyObject current<span style="color:
#000000;">&#41;</span>
where T <span style="color: #008000;">:</span> DependencyObject
<span style="color:
#000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">do</span>
<span style="color:
#000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">if</span><span style="color:
#000000;">&#40;</span> current <a href="http://www.google.com/search?q=is+msdn.microsoft.com"><span
style="color: #0000ff; font-weight: bold;">is</span></a> T <span style="color: #000000;">&#41;</span>
<span
style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight: bold;">return</span> <span
style="color: #000000;">&#40;</span>T<span style="color: #000000;">&#41;</span>current;
<span style="color:
#000000;">&#125;</span>
current <span style="color: #008000;">=</span> VisualTreeHelper.<span style="color:
#0000FF;">GetParent</span><span style="color: #000000;">&#40;</span>current<span style="color:
#000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF; font-weight:
bold;">while</span> <span style="color: #000000;">&#40;</span>current <span style="color: #008000;">!=</span>
<span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #000000;">&#41;</span>;
<span
style="color: #0600FF; font-weight: bold;">return</span> null;
<span style="color: #000000;">&#125;</span>
</pre>
</div>
<h2>Drop</h2>
<p>To make an element be a drop location, set the <b>AllowDrop</b> property to true. When
the user drags an item over the element, the <b>DragEnter</b> event is called. In this event you can analyze the data
and decide if a drop is allowed or not.</p>
<p>When the user releases the mouse button the <b>Drop</b> event is
called. The data is available in the <b>DataObject</b> provided in the DragEventArgs.</p>
<br/>
<div
class="codeblock"><pre class="xaml xaml" style="font-family: courier new,courier,monospace;"> <span style="color:
#800000;"><span style="color: #800000;">&lt;ListView</span> <span style="color: #ff0000;">x:Name</span>=
<span style="color: #0000ff;">&quot;DropList&quot;</span> </span>
<span style="color: #800000;"> <span
style="color: #ff0000;">Drop</span>=<span style="color: #0000ff;">&quot;DropList_Drop&quot;</span> </span>

<span style="color: #800000;"> <span style="color: #ff0000;">DragEnter</span>=<span style="color:
#0000ff;">&quot;DropList_DragEnter&quot;</span> </span>
<span style="color: #800000;"> <span style="color:
#ff0000;">AllowDrop</span>=<span style="color: #0000ff;">&quot;True&quot;</span> <span style="color:
#800000;">/&gt;</span></span>
</pre></div>
<div class="codeblock"><pre class="csharp csharp" style="font-
family: courier new,courier,monospace;"> <span style="color: #0600FF; font-weight: bold;">private</span> <span
style="color: #0600FF; font-weight: bold;">void</span> DropList_DragEnter<span style="color: #000000;">&#40;
</span><span style="color: #2b91af; font-weight: bold;">object</span> sender, DragEventArgs e<span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight:
bold;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>e.<span
style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">GetDataPresent</span><span style="color:
#000000;">&#40;</span><span style="color: #666666;">&quot;myFormat&quot;</span><span style="color:
#000000;">&#41;</span> ||
sender <span style="color: #008000;">==</span> e.<span style="color:
#0000FF;">Source</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;
</span>
e.<span style="color: #0000FF;">Effects</span> <span style="color: #008000;">=</span> DragDropEffects.
<span style="color: #0000FF;">None</span>;
<span style="color: #000000;">&#125;</span>
<span style="color:
#000000;">&#125;</span>
</pre></div>
<div class="codeblock"><pre class="csharp csharp" style="font-family:
courier new,courier,monospace;"> <span style="color: #0600FF; font-weight: bold;">private</span> <span

rss.html[2/16/2014 2:23:27 PM]


Christian Moser's WPF Tutorial.net

style="color: #0600FF; font-weight: bold;">void</span> DropList_Drop<span style="color: #000000;">&#40;</span>


<span style="color: #2b91af; font-weight: bold;">object</span> sender, DragEventArgs e<span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF; font-weight:
bold;">if</span> <span style="color: #000000;">&#40;</span>e.<span style="color: #0000FF;">Data</span>.<span
style="color: #0000FF;">GetDataPresent</span><span style="color: #000000;">&#40;</span><span style="color:
#666666;">&quot;myFormat&quot;</span><span style="color: #000000;">&#41;</span><span style="color:
#000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
Contact contact <span style="color:
#008000;">=</span> e.<span style="color: #0000FF;">Data</span>.<span style="color: #0000FF;">GetData</span>
<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;myFormat&quot;</span><span
style="color: #000000;">&#41;</span> <span style="color: #0600FF; font-weight: bold;">as</span> Contact;
ListView listView <span style="color: #008000;">=</span> sender <span style="color: #0600FF; font-weight:
bold;">as</span> ListView;
listView.<span style="color: #0000FF;">Items</span>.<span style="color:
#0000FF;">Add</span><span style="color: #000000;">&#40;</span>contact<span style="color: #000000;">&#41;
</span>;
<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
</pre></div>
http://www.wpftutorial.net/DragAndDrop.html
Sun, 16 Feb 2014 08:23:05 +01002011-04-19 16:59:14

rss.html[2/16/2014 2:23:27 PM]


WPF Tutorial | Christian Moser

Christian Moser Share... Feed About Christian Moser


   
     

Home

WPF Inspector

Getting started
About Christian Moser
Fundamentals
Christian Moser is working as a software architect and user experience designer
User Experience
at Zühlke Engineering in Zürich, Switzerland. He has gathered his experience in
Patterns several successful projects with Microsoft .NET technologies.

Controls
His passion is the design of graphical user interfaces and the simplification of
complex tasks to provide a rich experience to the user.
Custom Controls
He started developing application with WPF in early 2005. The power and
Layout flexibility of WPF fascinated him from the first second. The technology enables
you to build next generation user experiences.
Input
Do you like WPF Tutorial?
Data Binding
You can now suppport my work with a donation:
Styling

Localization

Interaction

Resources License

2D Graphics All samples of this web site are free for use in non-commercial and commercial
projects. They are all licensed unter the Microsoft Public License (MS-PL)
3D Graphics

Animation
Contact Christian Moser
Multimedia

Zühlke Engineering AG
Documents
Wiesenstrasse 10a

CH-8952 Schlieren
Windows 7
Switzerland
Interoperability
Phone: +41 44 733 66 17
Performance Mail: moc@zuehlke.com
Twitter: @christian_moser
Expression Blend

Tools

UI Automation

christian.html[2/16/2014 2:24:07 PM]


WPF Tutorial | Learn WPF in two Weeks

Home
    Getting started
    Learn WPF in two Weeks Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Learn WPF in one Week
Custom Controls
I started to build a one week training course to learn WPF. Starting with the basics and going through the important concepts of
Layout the framework up to more complex topics. I hope you like it.
Input

Data Binding Day 1 - Getting started


Styling
Install the development tools
Localization Learn the basic concepts of WPF
Create your first WPF application
Interaction
Learn how WPF changed the development workflow
Resources

2D Graphics
Day 2 - Concepts of WPF
3D Graphics
Get an introduction to XAML
Animation Learn about the hierarchical relation of elements in WPF
Multimedia Find out about the magic behind DependencyProperties
Get familiar with routed events.
Documents

Windows 7
Day 3 - Layout and Controls
Interoperability
Learn the layout basics
Performance
See the grid layout panel in action
Expression Blend Stack elements with the stackpanel
Get an overview about the variety of included controls.
Tools
Have a look at 3rd-party libraries
UI Automation

Day 4 - DataBinding and UI Architecture


Introduction to WPF DataBinding

LearnWPFin14Days.html[2/16/2014 2:24:24 PM]


WPF Tutorial | Learn WPF in two Weeks
How to display, sort and filter data
Using the Model-View-ViewModel Pattern
Learn how to validate user input
Create your own ValueConverter
Enhance the MVVM pattern by using Behaviors and Actions

Day 5 - Templates and Styles


Learn how to build rich user experience with WPF
Style the appearance of your controls
Completely replace the look of a control
How to display complex data in lists by using DataTemplates.

Some of the articles are not yet finished. The content for the subsequent days will follow soon... :-)

  ► Tutorial   ► Java Web Tutorial   ► Learn Quick Books   ► Coding Learning

Last modified: 2010-12-12 13:33:36


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 30.May 2011

so where are the last 9 days?


me

Commented on 2.June 2011

its a very good material .............give me examples also


sathya

Commented on 2.June 2011

very good Stuff.

Hi
Thank U :)

Commented on 7.June 2011

Just to let you know that even when the title says learn in one week the link at the menu says learn in
Ignacio
two weeks.

Commented on 10.June 2011

Last modified: 2010-01-05 12:01:58


Camila

Commented on 10.June 2011

Last modified: 2010-01-05 12:01:58

Camila
he forgot

LearnWPFin14Days.html[2/16/2014 2:24:24 PM]


WPF Tutorial | Learn WPF in two Weeks

Commented on 14.June 2011

pls change ur shirt. jeezus.


dood

Commented on 16.June 2011

thank you sir.................thanks

syed farooq...

Commented on 17.June 2011

hi.. i m new i want to learn wpf and wcf with in 2 week ... is it possible

mukund

Commented on 22.June 2011

it exist in pdf format ? I want to learn WPF but the best time to learn for me is when I commute by train.
sybe30
This training course seems to be very interresting.

Commented on 7.July 2011

very nice,Can you give me an example??


young

Commented on 16.July 2011

hi,sir namaste,i want to know detail abt WPF,WCF and Silverlight

soumya
plz sir help me.thnx
from...

Commented on 22.July 2011

Awesome Chris! Within an hour, I learnt all the fundas of WPF. Your diagrams are really very helpful in
Maharajan...
understanding the many abstract and vague concepts clearly.

Earlier I read some other articles and books but could not get a basic gripon WPF.

But after reading your whole article, I am really impressed and have a lot of confidence in working in
WPF project. Expecting more articled from you.

Commented on 26.July 2011

nice
vipin

Commented on 27.July 2011

hummmmm usefull 4 me &amp; my frnds


nency

Commented on 1.August 2011

very easy to understand and implement the WPF application.


krishna

Commented on 1.August 2011

very easy to understand and implement the WPF application.


krishna

Commented on 1.August 2011

Very Nice article.


Lalit

Commented on 1.August 2011

hi bro.. thnx for the great work :)

LearnWPFin14Days.html[2/16/2014 2:24:24 PM]


WPF Tutorial | Learn WPF in two Weeks
Hasan...
and i'm waiting for the rest..

Great Job man !!

Commented on 3.August 2011

Zhang Zhi very cool... this article is useful.. thank you for sharing... hope to see next article soon.
Ren

Commented on 3.August 2011

Great job!!
walter

Commented on 13.August 2011

Good article.. where is the rest ???????


Lavi

Commented on 2.September 2011

:)
kata

Commented on 6.September 2011

it's really useful! but hopefully you can finish the remaining days we really appreciate your help! God
chao
bless you!

Commented on 19.September 2011

Ankita its really good training.. i want to learn wcf also sir..
Johnson

Name

E-Mail (optional)

Comment

Post Comment

LearnWPFin14Days.html[2/16/2014 2:24:24 PM]


WPF Tutorial | Introduction to WPF

Home
    Getting started
    Introduction to WPF Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Introduction to Windows Presentation Foundation
Custom Controls

Layout
Overview
Input
The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It
Data Binding is part of the .NET framework 3.0 and higher.

Styling WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based
rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.
Localization
The followinig illustration gives you an overview of the main new features of WPF
Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation
Separation of Appearance and Behavior
WPF separates the appearance of an user interface from its behavior. The appearance is generally specified in the Extensible
Application Markup Language (XAML), the behavior is implemented in a managed programming language like C# or Visual Basic.

WPFIntroduction.html[2/16/2014 2:25:14 PM]


WPF Tutorial | Introduction to WPF
The two parts are tied together by databinding, events and commands. The separation of appearance and behavior brings the
following benefits:

Appearance and behaviour are loosely coupled


Designers and developers can work on separate models.
Graphical design tools can work on simple XML documents instead of parsing code.

Rich composition
Controls in WPF are extremely composable. You can define almost any type of controls as content of another. Although these
flexibility sounds horrible to designers, its a very powerful feature if you use it appropriate. Put an image into a button to create an
image button, or put a list of videos into a combobox to choose a video file.

 
<Button>
<StackPanel Orientation="Horizontal">
<Image Source="speaker.png" Stretch="Uniform"/>
<TextBlock Text="Play Sound" />
</StackPanel>
</Button>
 
 

Highly customizable
Because of the strict separation of appearance and behavior you can easily change the look of a control. The concept of styles let you
skin controls almost like CSS in HTML. Templates let you replace the entire appearance of a control.

The following example shows an default WPF button and a customized button.

Resolution independence
All measures in WPF are logical units - not pixels. A logical unit is a 1/96 of an inch. If you increase the resolution of your screen, the
user interface stays the same size - it just gets crispier. Since WPF builds on a vector based rendering engine it's incredibly easy to
build scaleable user interfaces.

Last modified: 2011-08-15 18:49:42


Copyright (c) by Christian Moser, 2011.

WPFIntroduction.html[2/16/2014 2:25:14 PM]


WPF Tutorial | Introduction to WPF

 Comments on this article

Show all comments

Commented on 17.September 2011

Very useful for beginner in just 5 min .


Pham Kien
Thanks a lot.
Quoc

Commented on 19.September 2011

very good...
pragati

Commented on 19.September 2011

It really gud :)
Haritha

Commented on 20.September 2011

Good one
bhanu

Commented on 20.September 2011

Thank you..I think its more helpful for the beginners in WPF
sreejith

Commented on 20.September 2011

very helpful and easy to understand


Amit Verma

Commented on 20.September 2011

Similar to MSDN documentation but looks nicer &amp; richer


Abu Hanin

Commented on 21.September 2011

there is an sql error on the tutorials like user desing process...please fix it out asap...thankyou

kartik

Commented on 21.September 2011

Thanks Sir, thank you so much for all notes and example of WPF.........
Sweta Pandey

Commented on 22.September 2011

It is so beautifully explained that any one can understand.

Dhruvangini
Thanks

Commented on 22.September 2011

that is wonderful
BoYu Gao

Commented on 22.September 2011

You really need a spellchecker and a proofreader. Crispier??


Mark

WPFIntroduction.html[2/16/2014 2:25:14 PM]


WPF Tutorial | Introduction to WPF

Commented on 22.September 2011

one word. AWESOME!


awesome

Commented on 23.September 2011

Very nice article for WPF Beginners...


Garima

Commented on 23.September 2011

Pushing the beginners to mine more !!! .... Good


sakthi

Commented on 23.September 2011

Very nice article for WPF Beginners...


Garima

Commented on 24.September 2011

Cool.. been looking for a nice WPF intro and this is by far the best and coolest... thanks
RobertS

Commented on 25.September 2011

This is very helpful to learn


anjali

Commented on 26.September 2011

This article has given nice introduction to the wpf beginners.


chaitanya

Commented on 26.September 2011

Mobashir Good Explaination


Ahmad

Commented on 26.September 2011

really...good one

Roshan

Commented on 27.September 2011

Good one
Nithya

Commented on 27.September 2011

What a intro?????
Mukesh

Commented on 27.September 2011

very useful
pradeep

Commented on 27.September 2011

thnxx sir nice intro


deepak

Name

E-Mail (optional)

WPFIntroduction.html[2/16/2014 2:25:14 PM]


WPF Tutorial | Introduction to WPF
Comment

Post Comment

WPFIntroduction.html[2/16/2014 2:25:14 PM]


WPF Tutorial | DataGrid

Home
    Controls
    DataGrid Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF DataGrid Control
Custom Controls

Layout

Input

Data Binding
Introduction
Styling

Localization Since .NET 4.0, Microsoft is shipping a DataGrid control that provides all the basic functionality needed, like:

Interaction Auto generation of columns


Manual definition of columns
Resources
Selection
2D Graphics Grouping
Column sorting, reordering and resizing
3D Graphics
Row Details
Animation Alternating BackgroundBrush

Multimedia
Frozen columns
Headers Visibility
Documents How to template autogenerated columns
Windows 7

Interoperability

Performance Basic usage: Auto generate columns


Expression Blend
To show a basic data grid , just drop a DataGrid control to your view and bind the ItemsSource to a collection of data objects
Tools and you're done. The DataGrid provides a feature called AutoGenerateColumns that automatically generates column according
to the public properties of your data objects. It generates the following types of columns:
UI Automation
TextBox columns for string values
CheckBox columns for boolean values
ComboBox columns for enumerable values

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid
Hyperlink columns for Uri values

 
<DataGrid ItemsSource="{Binding Customers}" />
 
 

Manually define columns


Alternatively you can define your columns manually by setting the AutoGenerateColumns property to False. In this case you
have to define the columns in the Columns collection of the data grid. You have the following types of columns available:

DataGridCheckBoxColumn for boolean values


DataGridComboBoxColumn for enumerable values
DataGridHyperlinkColumn for Uri values
DataGridTemplateColumn to show any types of data by defining your own cell template
DataGridTextColumn to show text values

 
<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Image}" />

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
 
 

Selection
The data grid includes a variety of selection modes. They are configured by the SelectionMode and SelectionUnit property.

The SelectionMode can be set to Single or Extended to define if one or multiple units can be selected simultaneously.
The SelectionUnit defines the scope of one selection unit. It can be set to Cell, CellAndRowHeader and FullRow.

 
<DataGrid ItemsSource="{Binding Customers}"
SelectionMode="Extended" SelectionUnit="Cell" />
 
 

Column sorting, reordering and resizing


The data grid provides features to sort, reorder and resize columns. They can be enabled or disabled by the following properties:

CanUserReorderColumns enables or disables column re-ordering


CanUserResizeColumns enables or disables column resizing
CanUserResizeRows enables or disables row resizing
CanUserSortColumns enables or disables column sorting

 
<DataGrid ItemsSource="{Binding Customers}"
CanUserReorderColumns="True" CanUserResizeColumns="True"

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid
CanUserResizeRows="False" CanUserSortColumns="True"/>
 
 

Grouping
The data grid also supports grouping. To enable grouping you have to define a CollectionView that contains to least one
GroupDescription that defines the criterias how to group.

 
Customers = new ListCollectionView(_customers);
Customers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));
 
 
Second thing you need to do is defining a template how the groups should look like. You can do this by setting the GroupStyle to
something like the following snippet.

 
<DataGrid ItemsSource="{Binding GroupedCustomers}">
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander>
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=ItemCount}"/>
<TextBlock Text="Items"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
 
 

Row Details
The data grid provides a feature that shows a detail panel for a selected row. It can be enabled by setting a DataTemplate to the
RowDetailsTemplate property. The data template gets the object that is bound to this row passed by the DataContext and can
bind to it.

 
<DataGrid ItemsSource="{Binding Customers}">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Image Height="100" Source="{Binding Image}" />
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
 
 
Row Details depending on the type of data

You can specify a RowDetailsTemplateSelector that selects a data template according to the type or data that this row
contains. To do this, create a type that derives from DataTemplateSelector and override the SelectTemplate method. In
the items argument you get the data and you can determine which data template to display. Return an instance of that data
template as return value.

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid

 
public class GenderTemplateSelector : DataTemplateSelector
{
public DataTemplate MaleTemplate { get; set; }
public DataTemplate FemaleTemplate { get; set; }
 
public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
var customer = item as Customer;
if (customer == null)
return base.SelectTemplate(item, container);
 
if( customer.Gender == Gender.Male)
{
return MaleTemplate;
}
return FemaleTemplate;
}
}
 
 

 
<l:GenderTemplateSelector x:Key="genderTemplateSelector">
<l:GenderTemplateSelector.MaleTemplate>
<DataTemplate>
<Grid Background="LightBlue">
<Image Source="{Binding Image}" Width="50" />
</Grid>
</DataTemplate>
</l:GenderTemplateSelector.MaleTemplate>
<l:GenderTemplateSelector.FemaleTemplate>
<DataTemplate>
<Grid Background="Salmon">
<Image Source="{Binding Image}" Width="50" />
</Grid>
</DataTemplate>
</l:GenderTemplateSelector.FemaleTemplate>
</l:GenderTemplateSelector>
 

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid
<DataGrid ItemsSource="{Binding Customers}"
RowDetailsTemplateSelector="{StaticResource genderTemplateSelector}" />
 
 

Alternating BackgroundBrush
You can define a an AlternatingRowBackground that is applied every even row. You can additionally specify an
AlternationCount if you only want to ink every every n-th data row.

 
<DataGrid ItemsSource="{Binding Customers}"
AlternatingRowBackground="Gainsboro" AlternationCount="2"/>
 
 

Frozen Columns
The data grid also supports the feature to freeze columns. That means they stay visible while you scoll horizontally through all
columns. This is a useful feature to keep a referencing column like an ID or a name always visible to keep your orientation while
scrolling.

To freeze a numer of columns just set the FrozenColumnCount property to the number of columns you want to freeze.

 
<DataGrid ItemsSource="{Binding Customers}" FrozenColumnCount="2" />
 
 

Headers visbility
You can control the visibility of row and column headers by setting the HeadersVisibility property to either
None,Row,Column or All

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid
 
<DataGrid ItemsSource="{Binding Customers}" HeadersVisibility="None" />
 
 

How to template autogenerated columns


If you want to autogenerate columns using AutoGenerateColumns="True", you cannot use CellTemplates, because the
DataGrid autogenerates either a text, combo, hyperlink or checkbox column, but none of these are templateable. A simple
workaround is to hook into the autogeneration, cancel it and always create a DataGridTemplateColumn. The following snippet
shows the idea (the code is just a draft):

 
public class MyDataGrid : DataGrid
{
 
public DataTemplateSelector CellTemplateSelector
{
get { return (DataTemplateSelector)GetValue(CellTemplateSelectorProperty); }
set { SetValue(CellTemplateSelectorProperty, value); }
}
 
public static readonly DependencyProperty CellTemplateSelectorProperty =
DependencyProperty.Register("Selector", typeof(DataTemplateSelector),
typeof(MyDataGrid),
new FrameworkPropertyMetadata(null));
 
 
 
protected override void
OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
{
e.Cancel = true;
Columns.Add(new DataGridTemplateColumn
{
Header = e.Column.Header,
CellTemplateSelector = CellTemplateSelector
});
}
}
 
 
 
<l:MyDataGrid ItemsSource="{Binding}"
AutoGenerateColumns="True"
CellTemplateSelector="{StaticResource templateSelector}" />
 
 

  ► Tutorial   ► ActionScript   ► Flash CS3   ► Flash 9


Last modified: 2011-04-19 08:55:41


Copyright (c) by Christian Moser, 2011.

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid

 Comments on this article

Show all comments

Commented on 24.May 2011

Good tutorial...
Sreekumar

Commented on 26.May 2011

I need to create DataGrid dynamically in special way.

Shail
Let&acirc;��s say I have two columns for grid 1) FieldName and 2) FieldValue which comes from
database table.

Now one row data could have drop down, and other row could have text, and other row could have
check box in Field Value. How do I create this kind of dataGrid dynamically? My biggest challenge is
interacting with ColumnTemplate in individual cell level.

FieldName | Field Value

Sex | Radio Button to select Male or Female

Age | Drop Down Combo box to select age from 1 to 100

Name | Text box


is Employed | Check box to indicate whether employed or not

And another biggest challenge is I need to have Event on each FieldValue cell.

Event could be click, double click, Right mouse click, Enter etc.
Thank you

Shail

Commented on 30.May 2011

Very very nice article explaining every aspect of the grid with a Good Code example. Eager to see some
Anil Kumar...
more articles on various controls..

Commented on 10.June 2011

please help i bind complete datagrid but how 2 work same as datagridview in window appllication

patel...
like dg.Rows.column.cell is not in datagrid and how 2 count totalrows like dg.rows.counthow 2 do in
datagrid

Commented on 10.June 2011

which control equel datagridview in window app to wpf vs2010 reason i new in wpf vs 2010
patel...

Commented on 17.June 2011

awesome..i think its a knowledge of ocean


bhagavan

Commented on 5.July 2011

The datagrid in net4.0 is not good supported for mvvm.

eshao
THe datagrid don't have the &quot;command&quot; property like button,

Commented on 5.July 2011

if u use the datagrid wirh mvvm, u must do lot extra work that will hit u out off earth.
eshao

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid

Commented on 7.July 2011

Superb, very Nice Article. It helped me a Lot. Thank U.


Srinivas

Commented on 13.July 2011

There is a great problem using grouping - when you call .Refresh() method of ListCollectionView, to
Dan
update layout, it redraws all the datagrid and close all your groups.

May anybody answer how to refresh the data without those problems?

Commented on 13.July 2011

There is a great problem using grouping - when you call .Refresh() method of ListCollectionView, to
Dan
update layout, it redraws all the datagrid and close all your groups.

May anybody answer how to refresh the data without those problems?

Commented on 21.July 2011

How did you made the View Source option disable on this page?
Dev

Commented on 23.July 2011

What should I do if I want another node directioned from the costumers class?

Luis
e.g.
public class Customer : INotifyPropertyChanged

private string _firstName;

private string _lastName;

private Gender _gender;

private Uri _webSite;

private bool _newsletter;

private string _image;

private Phone _phones;// &lt;-------- this one

.
}

//where:

public class Phone:INotifyPropertyChanged

private int _homeNumber;

private int _celNumber;

private int _workNumber;

private int _faxNumber;

I want to display &quot;Phone&quot; values on a dataGrid, preferibly in a comboboxCell, I just want to


display them, not edit them

thanks

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid

Commented on 23.July 2011

What should I do if I want another node directioned from the costumers class?

Luis
e.g.
public class Customer : INotifyPropertyChanged

private string _firstName;

private string _lastName;

private Gender _gender;

private Uri _webSite;

private bool _newsletter;

private string _image;

private Phone _phones;// &lt;-------- this one

.
}

//where:

public class Phone:INotifyPropertyChanged

private int _homeNumber;

private int _celNumber;

private int _workNumber;

private int _faxNumber;

I want to display &quot;Phone&quot; values on a dataGrid, preferibly in a comboboxCell, I just want to


display them, not edit them

thanks

Commented on 27.July 2011

Is there anyway to get those check boxes to work with one click? The currently require two clicks to use.
Derek
One to select the cell and one to click the check box.

Commented on 28.July 2011

I have a problem on paging,in which i want to show google type paging like 1 2 3 4...400 please suggest
Prabhat
me,
khare

Commented on 2.August 2011

Hari Kumar (and others) you are missing the point of the WPF datagrid, you don't access the rows/cells
Steve
directly, the datagrid should be bound to a data set, changes made on the screen are reflected back to
the data set and if you change the data set these changes are reflected on the screen.

It takes a bit of getting used to, but it's very powerfull once you understand how to use it.

Commented on 10.August 2011

Would anyone know, how to make the grids look a bit more stylish as opposed to the normal windows

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid
Chirag
'blue' selection. I would like to add a bit more touch and feel

Commented on 20.August 2011

tanks alot.very good


zahra

Commented on 23.August 2011

I have a question about grouping. Let's say, I have a group style in resource dictionary, and I want to set
Ruslan
datagrid group style to the group style from xaml. How can this be achieved?

Thank you in advance,

Ruslan

Commented on 23.August 2011

I have a question about grouping. Let's say, I have a group style in resource dictionary, and I want to set
Ruslan
datagrid group style to the group style from xaml. How can this be achieved?

Thank you in advance,

Ruslan

Commented on 31.August 2011

Soby very Nice Article.


Mathew

Commented on 12.September 2011

can u help me out?

Bhavneet
actually problem is that i'm doing a project in WPF but when i drag grid on it then there is no property
for autocolomn property or add colomn property.is the problem is of studio problem?

i'm using visual studio 2008..

Commented on 23.September 2011

detective Nice Article. Thanks for such a nice article.


jeera

Commented on 27.September 2011

Superb article.

Harikrishnan
How can I generate column dynamically from user preference column number values?

Ex: If I have 3 columns C1,C2,C3 and user chenges the order to C3,C1,C2 - I have to load the same way
the user changed it the next time...

Can anyone Help!!!!

Name

E-Mail (optional)

Comment

Post Comment

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | DataGrid

DataGrid.html[2/16/2014 2:25:31 PM]


WPF Tutorial | Create a simple WPF application

Home
    Getting started
    Create a simple WPF application Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to create a simple WPF application
Custom Controls

Layout
In Visual Studio 2008
Input
Open Visual Studio 2008 and choose "File", "New", "Project..." in the main menu. Choose "WPF Application" as project type.
Data Binding
Choose a folder for your project and give it a name. Then press "OK"
Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation
Visual Studio creates the project and automatically adds some files to the solution. A Window1.xaml and an App.xaml. The structure
looks quite similar to WinForms, except that the Window1.designer.cs file is no longer code but it's now declared in XAML as
Window1.xaml

HelloWPF.html[2/16/2014 2:26:07 PM]


WPF Tutorial | Create a simple WPF application

Open the Window1.xaml file in the WPF designer and drag a Button and a TextBox from the toolbox to the Window

Select the Button and switch to the event view in the properties window (click on the little yellow lightning icon). Doubleclick on the
"Click" event to create a method in the codebehind that is called, when the user clicks on the button.

Note: If you do not find a yellow lightning icon, you need to install the Service Pack 1 for VisualStudio on your machine.
Alternatively you can doubleclick on the button in the designer to achieve the same result.

Visual Studio automatically creates a method in the code-behind file that gets called when the button is clicked.
 

HelloWPF.html[2/16/2014 2:26:07 PM]


WPF Tutorial | Create a simple WPF application
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Hello WPF!";
}
 
 
The textbox has automatically become assigned the name textBox1 by the WPF designer. Set text Text to "Hello WPF!" when the
button gets clicked and we are done! Start the application by hit [F5] on your keyboard.

Isn't this cool!

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2010-02-08 17:51:47


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 16.August 2011

The Great Website For WPF Learn Thanks Sir.


Faisal H...

Commented on 22.August 2011

Begginer Examples Good


Sudarshan

Commented on 23.August 2011

hi, i have already started doing the wpf application, but now im facing the problem that for different
ROHITH
resolutions my application is not visible properly and some of part of the applications r getting
cropped,,,, i have used the grid control to place the buttons, but for other resolutions the buttons r
getting displaced, so pls any help me out how to resolve it,,,,,,,,,,

Commented on 25.August 2011

HelloWPF.html[2/16/2014 2:26:07 PM]


WPF Tutorial | Create a simple WPF application
thanks ...

Anjum
Its too esy to understand

Commented on 25.August 2011

Thanks !
Anjum
Its too easy to understand .

Commented on 26.August 2011

Very useful. Thanks


Jalindar

Commented on 28.August 2011

Its good,but what's new with WPF! It can simply be done with winforms.Please give some example which
Sree
describe the WPF specialty.

Commented on 30.August 2011

oooooo

grege
you Are very smart

Commented on 31.August 2011

good demo
ankit

Commented on 5.September 2011

worst example i didn't find need to demonstrate here. we can do in windows form only...
siva

Commented on 5.September 2011

worst example i didn't find need to demonstrate here. we can do in windows form only...
siva

Commented on 6.September 2011

Superb for beginners

mahesh
Thanks for providing

Commented on 8.September 2011

Thank you very much. It was my 1st WPF sample.... Thanks again..... :)

Vinay

Commented on 12.September 2011

Very useful tutorial... thanks :) I just wanna give 1 suggestion; if you could add a link @ Bottom for next
Vinay
page then it will be better..

Commented on 12.September 2011

WPF is for desktop application or web application???????


abc

Commented on 13.September 2011

super very much useful for beginers

kishore

HelloWPF.html[2/16/2014 2:26:07 PM]


WPF Tutorial | Create a simple WPF application

Commented on 13.September 2011

NICE VERY MUCH USEFUL

KISHORE

Commented on 14.September 2011

After creating an application I am not getting any control on toolbox to add on .xaml page.I need help.

Sumantra

Commented on 20.September 2011

Good Example for beginner...


Roshni Shah

Commented on 21.September 2011

very useful........ Thanks

kalaivanan

Commented on 22.September 2011

very useful!:-)

Lokesh...

Commented on 22.September 2011

It is Very useful for Beginners


Shivu

Commented on 24.September 2011

Really nice. I am the beginner for learning Dot net but like to learn more
MMS

Commented on 27.September 2011

Nice article for beginners.


Ashok

Commented on 27.September 2011

Mahesh It's cool


Mane

Name

E-Mail (optional)

Comment

Post Comment

HelloWPF.html[2/16/2014 2:26:07 PM]


WPF Tutorial | XAML

Home
    Fundamentals
    XAML Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Introduction to XAML
Custom Controls
XAML stands for Extensible Application Markup Language. Its a simple language based on XML to create and initialize .NET objects
Layout with hierarchical relations. Altough it was originally invented for WPF it can by used to create any kind of object trees.
Input Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF and for electronic paper in the XPS standard.
Data Binding All classes in WPF have parameterless constructors and make excessive usage of properties. That is done to make it perfectly fit for
XML languages like XAML.
Styling

Localization
Advantages of XAML
Interaction
All you can do in XAML can also be done in code. XAML ist just another way to create and initialize objects. You can use WPF without
Resources
using XAML. It's up to you if you want to declare it in XAML or write it in code. Declare your UI in XAML has some advantages:
2D Graphics
XAML code is short and clear to read
3D Graphics Separation of designer code and logic
Animation Graphical design tools like Expression Blend require XAML as source.
The separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.
Multimedia

Documents
XAML vs. Code
Windows 7
As an example we build a simple StackPanel with a textblock and a button in XAML and compare it to the same code in C#.
Interoperability
 
Performance <StackPanel>
Expression Blend
<TextBlock Margin="20">Welcome to the World of XAML</TextBlock>
<Button Margin="10" HorizontalAlignment="Right">OK</Button>
Tools </StackPanel>
 
UI Automation
 
The same expressed in C# will look like this:

 
// Create the StackPanel

XAML.html[2/16/2014 2:26:24 PM]


WPF Tutorial | XAML
StackPanel stackPanel = new StackPanel();
this.Content = stackPanel;
 
// Create the TextBlock
TextBlock textBlock = new TextBlock();
textBlock.Margin = new Thickness(10);
textBlock.Text = "Welcome to the World of XAML";
stackPanel.Children.Add(textBlock);
 
// Create the Button
Button button = new Button();
button.Margin= new Thickness(20);
button.Content = "OK";
stackPanel.Children.Add(button);
 
 
As you can see is the XAML version much shorter and clearer to read. And that's the power of XAMLs expressiveness.

Properties as Elements
Properties are normally written inline as known from XML <Button Content="OK" />. But what if we want to put a more
complex object as content like an image that has properties itself or maybe a whole grid panel? To do that we can use the property
element syntax. This allows us to extract the property as an own child element.

 
<Button>
<Button.Content>
<Image Source="Images/OK.png" Width="50" Height="50" />
</Button.Content>
</Button>
 
 

Implicit Type conversion


A very powerful construct of WPF are implicit type converters. They do their work silently in the background. When you declare a

BorderBrush, the word "Blue" is only a string. The implicit BrushConverter makes a
System.Windows.Media.Brushes.Blue out of it. The same regards to the border thickness that is beeing converted implicit
into a Thickness object. WPF includes a lot of type converters for built-in classes, but you can also write type converters for your
own classses.

 
<Border BorderBrush="Blue" BorderThickness="0,10">
</Border>
 
 

Markup Extensions
Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime. Markup
extensions are surrouded by curly braces (Example: Background="{StaticResource NormalBackgroundBrush}"). WPF
has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension. These are the built-in
markup extensions:

Binding
To bind the values of two properties together.
StaticResource
XAML.html[2/16/2014 2:26:24 PM]
WPF Tutorial | XAML

One time lookup of a resource entry


DynamicResource
Auto updating lookup of a resource entry
TemplateBinding
To bind a property of a control template to a dependency property of the control
x:Static
Resolve the value of a static property.
x:Null
Return null


The first identifier within a pair of curly braces is the name of the extension. All preciding identifiers are named parameters in the form
of Property=Value.
The following example shows a label whose Content is bound to the Text of the textbox. When you type a text
into the text box, the text property changes and the binding markup extension automatically updates the content of the label.

 
<TextBox x:Name="textBox"/>
<Label Content="{Binding Text, ElementName=textBox}"/>
 
 

Namespaces
At the beginning of every XAML file you need to include two namespaces.
The first is http://schemas.microsoft.com/winfx/2006/xaml/presentation. It is mapped to all wpf controls in
System.Windows.Controls.
The second is http://schemas.microsoft.com/winfx/2006/xaml it is mapped to System.Windows.Markup that
defines the XAML keywords.

The mapping between an XML namespace and a CLR namespace is done by the XmlnsDefinition attribute at assembly level.
You can also directly include a CLR namespace in XAML by using the clr-namespace: prefix.
 
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Window>
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2013-12-13 09:08:46


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 15.July 2011

Nice...
Ganesh

Commented on 18.July 2011

good content for beginners.


batham

XAML.html[2/16/2014 2:26:24 PM]


WPF Tutorial | XAML

Commented on 20.July 2011

its very comprehensive . thanks alot


Safoura

Commented on 21.July 2011

good content for beginners.


batham

Commented on 22.July 2011

nice
AT

Commented on 1.August 2011

Very Helpful!! I liked it!!

Rahul

Thanks!

Commented on 4.August 2011

Very Good, thank you


Ali

Commented on 8.August 2011

When I can understand a new subject in a few minutes that means that it is &quot;clear and
Jack Shasha
concise&quot; as I like it. I am a technical writer and always striving to achieve a similar effect. Thanks.

Commented on 16.August 2011

Thanks a lot..!!! It is really very easy to understand


sai

Commented on 18.August 2011

Screw the WPF chapt in my C#2010 for dummies, this is how a proper tutorial should be.
OSK

Commented on 23.August 2011

The code above is only longer because of the parameterless constructors. XAML allows a line to initialise
Ian
an object. You need a line for each parameter in code because of the lack of constructors.

Commented on 24.August 2011

Ramya Thanks alot good one

krishna

Commented on 26.August 2011

Thank you for this short n precise tutorial..!


Girish

Commented on 26.August 2011

Good one and easily understandable.

Mahesh
Thank U

Commented on 26.August 2011

Good one and easily understandable.

XAML.html[2/16/2014 2:26:24 PM]


WPF Tutorial | XAML
Mahesh
Thank U

Commented on 6.September 2011

Very cool tutorial. Is there a way though that you could put forward and next buttons? Thanks.
Jason

Commented on 6.September 2011

bibin tv

Commented on 9.September 2011

And i was thinking i would never learn XAML


Darpok

Commented on 14.September 2011

Hello! kfedfaa interesting kfedfaa site! I'm really like it! Very, very kfedfaa good!
Pharme195

Commented on 14.September 2011

Hello! fdkcgae interesting fdkcgae site! I'm really like it! Very, very fdkcgae good!
Pharmg537

Commented on 16.September 2011

very well said!!


dk

Commented on 21.September 2011

Thanks. A very good and succint read. Waiting for more articles.

Atif Hussain

Commented on 24.September 2011

Fantastic Notes
LampGlow...

Commented on 24.September 2011

Thanks A Lot......
Baljinder

Commented on 25.September 2011

great ..
innocent...

Name

E-Mail (optional)

Comment

XAML.html[2/16/2014 2:26:24 PM]


WPF Tutorial | XAML

Post Comment

XAML.html[2/16/2014 2:26:24 PM]


WPF Tutorial | Grid Panel

Home
    Layout
    Grid Panel Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Grid Panel
Custom Controls
Introduction
Layout
How to define rows and columns
Input
How to add controls to the grid
Data Binding
Resize columns or rows
Styling
How to share the width of a column over multiple grids
Localization
Using GridLenghts from code
Interaction

Resources
Introduction
2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools The grid is a layout panel that arranges its child controls in a tabular structure of rows and columns. Its functionality is similar to the
HTML table but more flexible. A cell can contain multiple controls, they can span over multiple cells and even overlap themselves.
UI Automation
The resize behaviour of the controls is defined by the HorizontalAlignment and VerticalAlignment properties who define
the anchors. The distance between the anchor and the grid line is specified by the margin of the control

GridLayout.html[2/16/2014 2:27:02 PM]


WPF Tutorial | Grid Panel

Define Rows and Columns


The grid has one row and column by default. To create additional rows and columns, you have to add RowDefinition items to the
RowDefinitions collection and ColumnDefinition items to the ColumnDefinitions collection. The following example
shows a grid with three rows and two columns.

The size can be specified as an absolute amount of logical units, as a percentage value or automatically.

Fixed Fixed size of logical units (1/96 inch)


Auto Takes as much space as needed by the contained control
Star (*) Takes as much space as available (after filling all auto and fixed sized columns), proportionally
divided over all star-sized columns. So 3*/5* means the same as 30*/50*. Remember that star-
sizing does not work if the grid size is calculated based on its content.

 
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="28" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
</Grid>
 
 

How to add controls to the grid


To add controls to the grid layout panel just put the declaration between the opening and closing tags of the Grid. Keep in mind
that the row- and columndefinitions must precced any definition of child controls.

The grid layout panel provides the two attached properties Grid.Column and Grid.Row to define the location of the control.

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="28" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Name:"/>
<Label Grid.Row="1" Grid.Column="0" Content="E-Mail:"/>
<Label Grid.Row="2" Grid.Column="0" Content="Comment:"/>
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" />
<TextBox Grid.Column="1" Grid.Row="2" Margin="3" />
<Button Grid.Column="1" Grid.Row="3" HorizontalAlignment="Right"
MinWidth="80" Margin="3" Content="Send" />
</Grid>
 

GridLayout.html[2/16/2014 2:27:02 PM]


WPF Tutorial | Grid Panel

Resizable columns or rows


WPF provides a control called the GridSplitter. This control is added like any other control to a cell of the grid. The special thing
is that is grabs itself the nearest gridline to change its width or height when you drag this control around.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Content="Left" Grid.Column="0" />
<GridSplitter HorizontalAlignment="Right"
VerticalAlignment="Stretch"
Grid.Column="1" ResizeBehavior="PreviousAndNext"
Width="5" Background="#FFBCBCBC"/>
<Label Content="Right" Grid.Column="2" />
</Grid>
 
The best way to align a grid splitter is to place it in its own auto-sized column. Doing it this way prevents overlapping to adjacent cells.
To ensure that the grid splitter changes the size of the previous and next cell you have to set the ResizeBehavior to
PreviousAndNext.

The splitter normally recognizes the resize direction according to the ratio between its height and width. But if you like you can also
manually set the ResizeDirection to Columns or Rows.

<GridSplitter ResizeDirection="Columns"/>
 

How to share the width of a column over multiple grids


The shared size feature of the grid layout allows it to synchronize the width of columns over multiple grids. The feature is very useful if
you want to realize a multi-column listview by using a grid as layout panel within the data template. Because each item contains its
own grid, the columns will not have the same width.

By setting the attached property Grid.IsSharedSizeScope to true on a parent element you define a scope within the column-
widths are shared.

To synchronize the width of two columndefinitions, set the SharedSizeGroup to the same name.

 
<ItemsControl Grid.IsSharedSizeScope="True" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>

GridLayout.html[2/16/2014 2:27:02 PM]


WPF Tutorial | Grid Panel
<ColumnDefinition SharedSizeGroup="FirstColumn" Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=Key}" TextWrapping="Wrap"/>
<TextBlock Text="{Binding Path=Value}" Grid.Column="1" TextWrapping="Wrap"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
 
 
Useful Hints

Columns and rows that participate in size-sharing do not respect Star sizing. In the size-sharing scenario, Star sizing is treated as Auto.
Since TextWrapping on TextBlocks within an SharedSize column does not work you can exclude your last column from the shared
size. This often helps to resolve the problem.

Using GridLenghts from code


If you want to add columns or rows by code, you can use the GridLength class to define the differenz types of sizes.

Auto sized GridLength.Auto


Star sized new GridLength(1,GridUnitType.Star)
Fixed size new GridLength(100,GridUnitType.Pixel)

Grid grid = new Grid();


 
ColumnDefinition col1 = new ColumnDefinition();
col1.Width = GridLength.Auto;
ColumnDefinition col2 = new ColumnDefinition();
col2.Width = new GridLength(1,GridUnitType.Star);
 
grid.ColumnDefinitions.Add(col1);
grid.ColumnDefinitions.Add(col2);
 

More on this topic


How to create a resizable column

  ► Tutorial   ► Adobe InDesign   ► InDesign CS3   ► Adobe Print

Last modified: 2011-10-03 09:22:29


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 30.March 2011

Nice one Bro...


Antony Nadan

GridLayout.html[2/16/2014 2:27:02 PM]


WPF Tutorial | Grid Panel

Commented on 30.March 2011

I have a problem with Grid inside ItemsControl. The Grid as DataTemplate with 1 row and 3 columns
Ričardas
(each must have Width = Auto). When I populate buttons, they are shown with different widths
(according to text lengths) - HorizontalAlignment=&quot;Stretch&quot; does not work. It fails to
preserve same column width in each populated grid. Setting Column width to * is not an option to
me, because sometimes I have one or two not visible columnns, and I want remaining visible columns
(e.g. buttons) take whole width. The Grid.IsSharedSizeScope=&quot;True&quot; also does not help...

Commented on 31.March 2011

differenz types =&gt; different types

Paul
Great article. Thanks! You have some more typos in your tutorails, especially some if insted of it. I'll try
to add it in comments in respectfull pages.

Commented on 21.April 2011

Superb.........,
Om Prakash
I Heart fully,

Thank you for your nice Material

Om Prakash Bishnoi
Software Engineer ,

DotSquare, Jaipur(RAj.)

Commented on 5.May 2011

This is my firts time to use WPF, It is a great help. Keep it up man! Thanks
Dennis

Commented on 5.May 2011

its very easy to learn as beginner


Arun

Commented on 5.May 2011

sandeep Fantastic Article...Well explained..


sharma

Commented on 18.May 2011

We need more details.

Ray Akkanson
Ra Akkanson

Commented on 19.May 2011

Hi,

Simi
that my first time to using grid layout.

So can u tell me d proper way that how can i run any program.

Commented on 23.May 2011

Good One...........:-)
Manoj

GridLayout.html[2/16/2014 2:27:02 PM]


WPF Tutorial | Grid Panel

Commented on 28.May 2011

thanks for the good explanation.


ray akkanson

Commented on 5.June 2011

Thanks it was very helpfull, it is my first time using Grid


forogh

Commented on 14.June 2011

Nice one
J

Commented on 21.June 2011

btf..nice article
Ashu

Commented on 30.June 2011

its a very nice....


Rakhi

Commented on 12.July 2011

Thanks for this. I keep finding myself getting back to your web (which is both well organized and
Tomer Avni
presented) and your topics are great !

B.T.W the part of GridLength(1,GridUnitType.Star) gave me the solution I was looking for the past 2
hours! (I couldn't help but creating element in code rather the XAML)

Commented on 30.July 2011

G2One thank for sharing your great think.....


Network

Commented on 1.August 2011

How we can retrieve values of each column by iterating ?????


kisalay

Commented on 3.August 2011

Thanks,this definition is very useful


periyasamy

Commented on 16.August 2011

Nice
Vijay

Commented on 25.August 2011

kya hai ye sab Ha ?????????????????????????????


yeda anna

Commented on 25.August 2011

how sexy is this documents


yeda anna

Commented on 8.September 2011

Good to learn
sreenivas

GridLayout.html[2/16/2014 2:27:02 PM]


WPF Tutorial | Grid Panel

Commented on 9.September 2011

Hi,

Gagan M
I just found a typo. Will be better if you can get it rectified since it might be confusing for others.

In 'Define Rows and Columns' section,

'The following example shows a grid with three rows and two columns.' (Instead there are four rows
and two columns in the example)

Thanks.

Commented on 22.September 2011

Thanks~ It is easy to understand for me !

Randy

Name

E-Mail (optional)

Comment

Post Comment

GridLayout.html[2/16/2014 2:27:02 PM]


WPF Tutorial | Dependency Properties

Home
    Fundamentals
    Dependency Properties Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Dependency Properties
Custom Controls
Introduction
Layout
Value resolution strategy
Input
The magic behind it
Data Binding
How to create a DepdencyProperty
Styling
Readonly DependencyProperties
Localization
Attached DependencyProperties
Interaction
Listen to dependency property changes
Resources
How to clear a local value
2D Graphics

3D Graphics Introduction
Animation
When you begin to develop appliations with WPF, you will soon stumble across DependencyProperties. They look quite similar to
Multimedia normal .NET properties, but the concept behind is much more complex and powerful.

Documents
The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the
Windows 7 value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from
Interoperability
DependencyObject.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values
Performance
provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you
Expression Blend want to set.

Tools The advantages of dependency properties are

UI Automation Reduced memory footprint



It's a huge dissipation to store a field for each property when you think that over 90% of the properties of a UI control typically
stay at its initial values. Dependency properties solve these problems by only store modified properties in the instance. The
default values are stored once within the dependency property.

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties

Value inheritance

When you access a dependency property the value is resolved by using a value resolution strategy. If no local value is set, the
dependency property navigates up the logical tree until it finds a value. When you set the FontSize on the root element it
applies to all textblocks below except you override the value.

Change notification

Dependency properties have a built-in change notification mechanism. By registering a callback in the property metadata you
get notified, when the value of the property has been changed. This is also used by the databinding.

Value resolution strategy


Every time you access a dependency property, it internally resolves the value by following the precedence from high to low. It checks
if a local value is available, if not if a custom style trigger is active,... and continues until it founds a value. At last the default value is
always available.

The magic behind it


Each WPF control registers a set of DependencyProperties to the static DependencyProperty class. Each of them consists of
a key - that must be unique per type - and a metadata that contain callbacks and a default value.

All types that want to use DependencyProperties must derive from DependencyObject. This baseclass defines a key, value
dictionary that contains local values of dependency properties. The key of an entry is the key defined with the dependency property.

When you access a dependency property over its .NET property wrapper, it internally calls GetValue(DependencyProperty) to
access the value. This method resolves the value by using a value resolution strategy that is explained in detail below. If a local value
is available, it reads it directly from the dictionary. If no value is set if goes up the logical tree and searches for an inherited value. If no
value is found it takes the default value defined in the property metadata. This sequence is a bit simplified, but it shows the main
concept.

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties

How to create a DependencyProperty


To create a DependencyProperty, add a static field of type DepdencyProperty to your type and call
DependencyProperty.Register() to create an instance of a dependency property. The name of the DependendyProperty
must always end with ...Property. This is a naming convention in WPF.

To make it accessable as a normal .NET property you need to add a property wrapper. This wrapper does nothing else than internally
getting and setting the value by using the GetValue() and SetValue() Methods inherited from DependencyObject and passing the
DependencyProperty as key.

Important: Do not add any logic to these properties, because they are only called when you set the property from code. If
you set the property from XAML the SetValue() method is called directly.

If you are using Visual Studio, you can type propdp and hit 2x tab to create a dependency property.

 
// Dependency Property
public static readonly DependencyProperty CurrentTimeProperty =
DependencyProperty.Register( "CurrentTime", typeof(DateTime),
typeof(MyClockControl), new FrameworkPropertyMetadata(DateTime.Now));
 
// .NET Property wrapper
public DateTime CurrentTime
{
get { return (DateTime)GetValue(CurrentTimeProperty); }
set { SetValue(CurrentTimeProperty, value); }
}
 
 
Each DependencyProperty provides callbacks for change notification, value coercion and validation. These callbacks are registered on
the dependency property.

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties
 
new FrameworkPropertyMetadata( DateTime.Now,
OnCurrentTimePropertyChanged,
OnCoerceCurrentTimeProperty ),
OnValidateCurrentTimeProperty );
 
 
Value Changed Callback

The change notification callback is a static method, that is called everytime when the value of the TimeProperty changes. The new
value is passed in the EventArgs, the object on which the value changed is passed as the source.
 
private static void OnCurrentTimePropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
MyClockControl control = source as MyClockControl;
DateTime time = (DateTime)e.NewValue;
// Put some update logic here...
}
 
 
Coerce Value Callback

The coerce callback allows you to adjust the value if its outside the boundaries without throwing an exception. A good example is a
progress bar with a Value set below the Minimum or above the Maximum. In this case we can coerce the value within the allowed
boundaries. In the following example we limit the time to be in the past.

 
private static object OnCoerceTimeProperty( DependencyObject sender, object data )
{
if ((DateTime)data > DateTime.Now )
{
data = DateTime.Now;
}
return data;
}
 
 
Validation Callback

In the validate callback you check if the set value is valid. If you return false, an ArgumentException will be thrown. In our example
demand, that the data is an instance of a DateTime.

 
private static bool OnValidateTimeProperty(object data)
{
return data is DateTime;
}
 
 

Readonly DependencyProperties
Some dependency property of WPF controls are readonly. They are often used to report the state of a control, like the
IsMouseOver property. Is does not make sense to provide a setter for this value.

Maybe you ask yourself, why not just use a normal .NET property? One important reason is that you cannot set triggers on normal
DependencyProperties.html[2/16/2014 2:27:23 PM]
WPF Tutorial | Dependency Properties

.NET propeties.

Creating a read only property is similar to creating a regular DependencyProperty. Instead of calling
DependencyProperty.Register() you call DependencyProperty.RegisterReadonly(). This returns you a
DependencyPropertyKey. This key should be stored in a private or protected static readonly field of your class. The key gives
you access to set the value from within your class and use it like a normal dependency property.

Second thing to do is registering a public dependency property that is assigned to


DependencyPropertyKey.DependencyProperty. This property is the readonly property that can be accessed from external.

 
// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey =
DependencyProperty.RegisterReadOnly("IsMouseOver",
typeof(bool), typeof(MyClass),
new FrameworkPropertyMetadata(false));
 
// Register the public property to get the value
public static readonly DependencyProperty IsMouseoverProperty =
IsMouseOverPropertyKey.DependencyProperty;
 
// .NET Property wrapper
public int IsMouseOver
{
get { return (bool)GetValue(IsMouseoverProperty); }
private set { SetValue(IsMouseOverPropertyKey, value); }
}
 
 

Attached Properties
Attached properties are a special kind of DependencyProperties. They allow you to attach a value to an object that does not know
anything about this value.

A good example for this concept are layout panels. Each layout panel needs different data to align its child elements. The Canvas
needs Top and Left, The DockPanel needs Dock, etc. Since you can write your own layout panel, the list is infinite. So you see, it's
not possible to have all those properties on all WPF controls.

The solution are attached properties. They are defined by the control that needs the data from another control in a specific context.
For example an element that is aligned by a parent layout panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element that provides the attached property.
To set the the Canvas.Top and Canvas.Left property of a button aligned within a Canvas panel, you write it like this:

<Canvas>
<Button Canvas.Top="20" Canvas.Left="20" Content="Click me!"/>
</Canvas>
 
 
public static readonly DependencyProperty TopProperty =
DependencyProperty.RegisterAttached("Top",
typeof(double), typeof(Canvas),
new FrameworkPropertyMetadata(0d,
FrameworkPropertyMetadataOptions.Inherits));
 
public static void SetTop(UIElement element, double value)
{

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties
element.SetValue(TopProperty, value);
}
 
public static double GetTop(UIElement element)
{
return (double)element.GetValue(TopProperty);
}
 
 

Listen to dependency property changes


If you want to listen to changes of a dependency property, you can subclass the type that defines the property and override the
property metadata and pass an PropertyChangedCallback. But an much easier way is to get the
DependencyPropertyDescriptor and hookup a callback by calling AddValueChanged()

 
DependencyPropertyDescriptor textDescr = DependencyPropertyDescriptor.
FromProperty(TextBox.TextProperty, typeof(TextBox));
 
if (textDescr!= null)
{
textDescr.AddValueChanged(myTextBox, delegate
{
// Add your propery changed logic here...
});
}
 
 

How to clear a local value


Because null is also a valid local value, there is the constant DependencyProperty.UnsetValue that describes an unset value.

button1.ClearValue( Button.ContentProperty );
 

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2010-02-08 17:52:30


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 27.May 2011

Very Goooddddd !!

Ali
Thanks.

Commented on 4.June 2011

Very good explanation of DependencyProperty


Fadi Raheel

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties

Commented on 9.June 2011

Could you please put a XAML sample of the binding to the property developed in the code? Thanks.
Adriano

Commented on 12.June 2011

The only article that does not confuse readers on Dependency Properties
Jay

Commented on 17.June 2011

Nice attempt at an explanation of DependencyProperty. It could be better organized.


Hal

Commented on 20.June 2011

YES !
Rene

Commented on 24.June 2011

Good, very nice article. Thanks


Satyabrata

Commented on 5.July 2011

Thank you for spending the time to prepare this article. I have already read the MSDN articles on
Stefan
dependency properties as well as Pro WPF and Silverlight MVVM: Effective Application Development
with Model-View-ViewModel (Apress 2010), so understanding your article was easy for me. What is
omitted from all of these is a lowest common denominator fully working example that is useful (or at
least can be extended to be useful). MSDN uses a silly fish tank example. Provide a second example
that builds on the first in order to illustrate the advanced concepts like callbacks.

Commented on 17.July 2011

Thanks thanks for this wonderful tutorial it really helped me a lot to understand DependencyProperties
Aymen
, I just still have a question , I don't understand the fact that the dependency property is declared as
static so how comes that every instance has its own value this is the only misundestanding I still have I
need your help , thanks in advance .

Commented on 18.July 2011

Thank you very much.i was looking like this type of article
mahanth

Commented on 21.July 2011

Very useful for me. Thanks


Tronel

Commented on 28.July 2011

very nice and useful


balaji

Commented on 2.August 2011

You will need to read this about 10 times to Understand what is going on. I understand a little bit now
daanyaal
about DP, much better than msnd

Commented on 3.August 2011

Awesome! Very well explained.


Xus

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties

Commented on 4.August 2011

Very nice explanation on dependency properties............finally understood the concept ! Thanks for
Maya
posting this.

Commented on 8.August 2011

Good.. Nice Article


Ankush Gupta

Commented on 15.August 2011

I m the beginner of WPF. wow! thts really great to have site like this. Thanks. its helping me a lot.
Cryptic

Commented on 19.August 2011

why is the dependency property declared as readonly if you are also using the SetValue method
blah!!!blah!!!

Commented on 25.August 2011

Rithuu Content is Precise and well defined. Thanks for writing this article.
Mangala

Commented on 28.August 2011

Thanks! much clearer than many articles.


Nahum

Commented on 6.September 2011

Thank you a lot :)

seyed
There is an miistake on Readonly DependencyProperties section. Wrapper method is defined as 'int'
but DependencyProperty is already as 'bool'.

Also, i couldn't use 'Listen to dependency property changes' section.

Can you explain some more info about it? Where i must insert these codes?

Thank's again :)

Commented on 16.September 2011

Mayank Very Nice Post man


Gupta

Commented on 22.September 2011

Hi Christian

Ohad
Thanks for your detailed explanation!

I have few questions :

1. At the begining when you expalnied about the advantages one of them was &quot;Reduced
memory footprint&quot; u wrote that when using DP it reduces memory storage compare to Normal
Properties because it &quot;only stores modified properties in the instance &amp; The default values
are stored once within the dependency property&quot;.

I understand that when storring only changes it reduces memory storage but what does it mean that
the default values are &quot;stored within the dependency property&quot;? i mean they must be
stored somewhere when application runs, so where would that be?
so why DP takes less memory than Normal Property?

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties
2.You wrote that DP are stored in Dictionary instaed of Field like Normal properties.

i wanted to know how is this fact empowers DP compared to normal Prop'. why is it
better?

3.I understood that there are &quot;Readonly DP&quot; but i have noticed that when using the
shortcutin Visual Studio for creating regular DP (propdp) a

&quot; public static readonly DependencyProperty MyProperty&quot; is added.

so what is the difference when adding &quot;readonly&quot; statement in regular DP and ReadOnly
DP?

4. Maybe a silly question but what is the meaning of &quot;Dependency&quot; in Dependency


Properties?

5. Why is the dependency property must be defined as static?

Commented on 25.September 2011

Hi Christian

ohad
Thanks for your detailed explanation!

I have few questions :

1. At the begining when you expalnied about the advantages one of them was &quot;Reduced
memory footprint&quot; u wrote that when using DP it reduces memory storage compare to Normal
Properties because it &quot;only stores modified properties in the instance &amp; The default values
are stored once within the dependency property&quot;.

I understand that when storring only changes it reduces memory storage but what does it mean that
the default values are &quot;stored within the dependency property&quot;? i mean they must be
stored somewhere when application runs, so where would that be?
so why DP takes less memory than Normal Property?

2.You wrote that DP are stored in Dictionary instaed of Field like Normal properties.

i wanted to know how is this fact empowers DP compared to normal Prop'. why is it
better?

3.I understood that there are &quot;Readonly DP&quot; but i have noticed that when using the
shortcutin Visual Studio for creating regular DP (propdp) a

&quot; public static readonly DependencyProperty MyProperty&quot; is added.

so what is the difference when adding &quot;readonly&quot; statement in regular DP and ReadOnly
DP?

4. Maybe a silly question but what is the meaning of &quot;Dependency&quot; in Dependency


Properties?

5. Why DP are always declared as Static?

6. why when updating data from Model to View we have to use DP or NotiftyPropertyChange instead
of normal property,

and when updating data from View to Model we have to use Normal Property?

Commented on 25.September 2011

hello
dsd

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Dependency Properties
Name

E-Mail (optional)

Comment

Post Comment

DependencyProperties.html[2/16/2014 2:27:23 PM]


WPF Tutorial | Development Tools

Home
    Getting started
    Development Tools Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Development Tools
Custom Controls
Microsoft provides two development tools for WPF applications. One is Visual Studio, made for developers and the other is
Layout Expression Blend made for designers. While Visual Studio is good in code and XAML editing, it has a rare support for all the
graphical stuff like gradients, template editing, animation, etc. This is the point where Expression Blend comes in. Blend covers the
Input
graphical part very well but it has (still) rare support for code and XAML editing.
Data Binding
So the conclusion is that you will need both of them.
Styling

Localization
Microsoft Visual Studio 2010
Interaction
Visual Studio is the tool for developers to develop WPF applications. It includes a graphical designer for WPF since version 2008. If
Resources you're using Visual Studio 2005 you can install an add-on that enables you to develop WPF applications.

2D Graphics Microsoft provides a free Express Edition of Visual Studio that also includes the WPF designer. You can download it from the following
URL
3D Graphics
Download Microsoft Visual C# 2010 - Express Edition
Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

Microsoft Expression Blend 3 + Sketch Flow


wpfdevtools.html[2/16/2014 2:28:07 PM]
WPF Tutorial | Development Tools

Expression Blend is the tool for designers. It's part of the Expression Studio, a new tool suite from Microsoft especially created for user
experience designers. Blend covers all the missing features of the Visual Studio designer like styling, templating, animations, 3D
graphics, resources and gradients.

In the latest Version it also includes a powerful prototyping tool called SketchFlow. Expression Blend can open solution files created by
visual studio.

Download Microsoft Expression Blend 3

Other useful tools


WPF Inspector
Snoop (Inspect the Visual Tree of running WPF applications)
Mole (Data Visualizer for Visual Studio
XAML Power Toys
WPF Performance Suite

Last modified: 2010-06-25 18:11:31


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 4.June 2011

Tank you!
ali

Commented on 13.June 2011

Wow nice! I want to learn wpf.


Wow

Commented on 15.June 2011

its nice information its very very easy to understand that you presented
balaraman

wpfdevtools.html[2/16/2014 2:28:07 PM]


WPF Tutorial | Development Tools

sooooooo thank full to you

Commented on 16.June 2011

Very Nice Articles for beginners


sekhar

Commented on 16.June 2011

good one...
sarath

Commented on 23.June 2011

Very good website for giving initial and advance knowledge of WPF and how to implement in any
Jamil Akhtar
Application.

Commented on 24.June 2011

Really nice info,

Datla
why dont you add next page/previous page button.

Commented on 3.July 2011

Coole Website:

Sedat
Werde jetzt mal den Inhalt checken.

F&Atilde;&frac14;r Studierende oder Recherchierend w&Atilde;&curren;ren &quot;Next&quot; und


&quot;Previous&quot;-Buttons 'ne coole Sache.

Commented on 9.July 2011

thanks a lot
alireza

Commented on 9.July 2011

Thanks!!!

Siva

Commented on 12.July 2011

good one...
satyawan

Commented on 14.July 2011

User-friendly and interesting site indeed! ZELJKO legendo


Ivan

Commented on 17.July 2011

Nice work. I want more :-)


Andrew

Commented on 20.July 2011

thanks..i m trying to learn WPF and this is so helpfull

Sagar
.......

Commented on 20.July 2011

it is realy good

Zeeda

wpfdevtools.html[2/16/2014 2:28:07 PM]


WPF Tutorial | Development Tools

Commented on 21.July 2011

Hi moser, your site looks awesome.Iam new to the wpf ..i have one query in my mind can we develop
Sanjay
both offline and web application by using wpf???

Commented on 28.July 2011

Indeed a Good Site To Start Off With WPF..Thanks :)


Akshatha

Commented on 1.August 2011

Neelam Great Job!!! Kindly post some tutorials for learning .net framework 3.5
Sharma

Commented on 7.August 2011

Looking forward to it. Thanks for putting this together!


Jonathan

Commented on 5.September 2011

Nice Tutorial...Thank you..


Saroj

Commented on 13.September 2011

Nice Article.Easy to understand...


Rushyendra

Commented on 14.September 2011

Mai Vĩnh Thanks! I'll enjoy!

Sang

Commented on 16.September 2011

Good article for beginners.


Ramya
Thank you:)

Commented on 16.September 2011

thank you ,it is good for beginners,it makes me to complete the following
Hanan

Commented on 22.September 2011

Awesome tutorial
Santosh

Name

E-Mail (optional)
Comment

Post Comment

wpfdevtools.html[2/16/2014 2:28:07 PM]


WPF Tutorial | Development Tools

wpfdevtools.html[2/16/2014 2:28:07 PM]


WPF Tutorial | WPF Inspector

Home
    WPF Inspector Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Inspector
Custom Controls

Layout
NEW: XAML Inspector - cross platform visual Debugging
Input
Have a look at XAML inspector. The successor of WPF Inspector. It brings all the features of WPF Inspector to all XAML platofrms
Data Binding (WPF, Silveright, WinRT and Windows Phone).

Styling Visit project page: www.xamlinspector.com

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend WPF Inspector is a utility that attaches to a running WPF application to troubleshoot common problems with layouting, databinding or
styling. WPF Inspector allows you to explore a live view of the logical- and visual tree, read and edit property values of elements,
Tools
watch the data context, debug triggers, trace styles and much more. Since March 2011, WPF Inspector is open source and available
UI Automation on CodePlex.

Download WPF Inspector from CodePlex

Inspector.html[2/16/2014 2:28:53 PM]


WPF Tutorial | WPF Inspector

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2013-10-17 13:47:17


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 3.January 2011

Christian,

Vins
I can't get it to work.. Version 0.9.5 gives me error "Object Reference Not Set" when I click Inspect
after selecting my wpf application.

Any clue?

Thanks!

Commented on 10.January 2011

Would be very appreciated to see it working on WPF 4.0 coz we haven't been using 3.5 for a long
xusan
and may be would not work on that version soon, any ways thank you for sharing this wonderfull tool

Commented on 17.January 2011

same as the one above me. i get this error.


shemesh

Commented on 18.January 2011

Very usefull tool I used under Windows 7 x64 and Visual Studio 2008

Tony
since I work with Visual Studio 2010, it's no longer working

if you release the source code, we could help you improve this great tool

(note : Snoop is also a good tool but it doesn't work too)

Commented on 29.January 2011

Agree with the above. We could really help you improve this great tool (and probably make it work
Mel
for a wider audience).

I've been trying to use it in my win7 VS2010 box to no avail. it works on my winxp VS2008 though.

Commented on 10.February 2011

@Tony:

Cory Plotts
Snoop does work for WPF 3.5/4.0 and x86/x64 ... just make sure that you have the latest version at
http://snoopwpf.codeplex.com.

If you have grabbed the version from Pete Blois' site ... that one ONLY works for WPF 3.5 and x86.

Commented on 24.February 2011

@Cory Plotts

Tony
The latest version works... sometimes... (many times I can't snoop into the application, the "Snoop this
application" button doesn't do anything, the "Magnify" button is working)

and when I successfully Snoop the application, Snoop is stuck at the ContentPresenter of the main

Inspector.html[2/16/2014 2:28:53 PM]


WPF Tutorial | WPF Inspector
window, I can't "snoop" into my injected view (my project use CAB/SCSF)

Commented on 3.March 2011

hallo,,,,i jhon IT student, can u pls help me to develop my thesis,

jhon
using wpf, pls view me some sample or give me some sites that can
help me in developing may programm..thanks..

Commented on 11.March 2011

nice work
Rohatash

Commented on 11.March 2011

Great work with this new release!

Borislav Ivanov
I hit a small problem:

I have two running 2 WPF applicaions and choose to attach to one of them, but WPF Inspector
attaches to the other one:

- .NET 4.0 64-bit (this is Metro Twit)

- .NET 3.0 32-bit (this is my app, that I cannot attach to)

If I stop the Metro Twit, I can succesfully attach to my app.

Commented on 17.March 2011

I just realized that if I put a disabled button to register the application unless you enter a valid serial,
edgar
you can enable that button easy. 0_o

Great application!

Commented on 23.March 2011

It is very usefull for me..

suresh
I learn wpf basic easily..this is great.
ramasamy

Commented on 23.March 2011

Hi Borislav,

Christian
the problem has been fixed in version 0.9.8. You can download it directly from codeplex.
Moser

Commented on 23.March 2011

Really a gud site for WPF learners..


Aly

Commented on 29.March 2011

It's great site who are working on WPF for the first time .
Debashish...

Commented on 13.April 2011

It's good site for Beginner who are working on WPF


Girish K

Commented on 14.April 2011

Mole is another great way to visualize WPF apps, they just put out Mole 2010 and it's really awesome
Jane
for what I'm doing with WPF at work.

Inspector.html[2/16/2014 2:28:53 PM]


WPF Tutorial | WPF Inspector
www.molosoft.com

Commented on 16.April 2011

Very handy tool ,,, more features than snoop....


tauqir

One Suggestion : The Main Inspector should not exit when we close the application we are inspecting.
We have to rerun inspector every time we want to inspect.
Hope to see this in future release.

Commented on 18.April 2011

Hello Christian.

Tobias
your Tool is very nice.

But, it is not possible to read complete Text of Errors, if they are very long. It is not possible to scroll,
or rightclick to copy text to clipboard.

It would be very nice and good to have this feature.

Greets

Tobi

Commented on 29.April 2011

Hi,

Rohit

WPF Inspector is an awesome stuff for a wpf developer. But i'm facing an issue with it.

can you provide any work around for this - http://stackoverflow.com/questions/5831354/cannot-add-


geometrydrawing-to-drawinggroup

Thanks,

Commented on 3.May 2011

Sir please give demo video how to work on this? i am not able to know this one.Its showing empty.
shankar

Commented on 17.June 2011

Very promissins concept, I've been looking for something like this for some time.
Thomaz
But I'm having trouble attaching it to my application. Seems like no matter which application I select in
the Attach box WPF inspector always attaches to itself.

Commented on 19.July 2011

Good
Sai Govind.N.K

Commented on 14.August 2011

... Show de Bola!!


Rodrigo

Commented on 26.September 2011

Really helpful resource


Tamas

Inspector.html[2/16/2014 2:28:53 PM]


WPF Tutorial | WPF Inspector
Name

E-Mail (optional)

Comment

Post Comment

Inspector.html[2/16/2014 2:28:53 PM]


WPF Tutorial | List of 3rd-Party Controls

Home
    Controls
    List of 3rd-Party Controls Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF - Third Party Controls
Custom Controls

Layout
WPF Component Vendors
Input
Mindscape
Data Binding Component Art
Styling DevExpress
SyncFusion
Localization
Infragistics
Interaction Xceed
Telerik
Resources
Actipro
2D Graphics divelements
Binary Mission
3D Graphics
Ice Blue
Animation

Multimedia

Documents Bar Code Misc


Windows 7
Neodynamics BarCode WPF Toolkit
Interoperability Actipro BarCode Infragistics Tab Control
Mindscape Flow Diagrams
Performance

Expression Blend Data Grids


Office Components
Tools Infragistics Data Grid
UI Automation Xceed Data Grid Spire.DOC for WPF
Component One Data Grid Spire.XLS for WPF
Syncfusion Essential Grid
Telerik RadGridView for WPF
ComponentArt DataGrid Outlook Bar
3rdPartyLibs.html[2/16/2014 2:29:10 PM]
WPF Tutorial | List of 3rd-Party Controls

Mindscape Datagrid
Infragistics Outlook Bar
Actipro Outlook Bar
CAD DevComponents Outlook Bar
Odyssey Outlook Bar
Topology Framework .NET Odyssey Explorer Bar
Eyeshot Telerik RadOutlookBar for WPF
Mono GtkSharp Mindscape Outlook Bar
CadLib 3.5 DWG DXF .NET Library Component One Outlook Bar
sgCode
SeeDraw
Panels

Charts Infragistics Carousel Panel


Telerik WPF Carousel Control
Infragistics xamChart Telerik RadTileView for WPF
Swordfish Charts Mindscape Coverflow Control
Component One Chart Telerik Virtualizing Wrap Panel
Visifire Chart for WPF and Silverlight Component One HyperPanel
WPF Graph on Code Project
Free 3D Chart
Free High Performance 3D Chart Progress Bars
D3 Dynamic Data Display
Mindscape Progress Bar
Syncfusion Essential Chart
Syncfusion Gauge
Telerik RadGauge for WPF Property Grids
Telerik RadChart for WPF
ComponentArt Chart Actipro Property Grid
Mindscape Chart Mindscape Property Grid
ChartFX for WPF Component One Property Grid
NextWave Chart for WPF
NextWave Gauge for WPF
PDF & Reporting
Color Picker Infragistics Reporting for WPF
Component One Reports
Mindscape Color Picker Component One PDF Viewer
Telerik Color Picker IceBlue PDF Viewer
Free Color Picker (CodePlex) IceBlue PDF for WPF
Component One Color Picker o2sol PDFView4NET

Diagram Editors Ribbon


Orbifold Visualizers Fluent Ribbon Control Suite
Syncfusion Essential Diagram Editor Infragistics Ribbon
Actipro Ribbon
DevComponents Ribbon
Dialogs and Windows Odyssey Ribbon
Telerik WPF UI RibbonBar
Pure WPF FileOpen, FileSave and
Free Microsoft WPF Ribbon Control
FolderBrowser Dialogs
divelements Ribbon
divelements Shell

3rdPartyLibs.html[2/16/2014 2:29:10 PM]


WPF Tutorial | List of 3rd-Party Controls
BinaryMisson Ribbon

Dock
Schedule
Infragistics Dock Manager
DevComponents Schedule Control
Actipro Dock Panel
DevComponents DateTime Picker
DevComponents Dock Panel
Component One Schedule
WPF Docking Library (Open Source)
Timeline Control
Avalon Dock (Open Source)
Telerik RadScheduler for WPF
Telerik RadDocking for WPF
Free WPF Schedule Control
divelements Dock
Mindscape Schedule Control
Mindscape Time Explorer
Editors Infragistics MonthCalendar

Infragistics xamEditors
Xceed Editors Slider
DevComponents Numeric Editor
Mindscape Dual-Slider
Telerik RadNumericUpDown for WPF
Component One Dual-Slider
Syncfusion Essential Edit (with Syntax
Highlighting)
WPF Calendar Control Toolbar
Mindscape Rich Text Editor
Telerik Image Editor DevExpress ToolBar
Odyssey Breadcrumb Bar
ComponentArt Toolbar
Effects
Transitionals - Framework to transition between Theming
screens.
WPF Shader and Transition FX WPF Theme Selector
Windows Presentation Foundation Pixel Shader
Effects Library
DotWay WPF - Color Picker, Panels and several Tree
Shader Effects
Telerik RadTree View for WPF
Telerik Drag&Drop for WPF
Mindscape Multicolumn Tree

GIS and Maps


Web Browser
ESRI ArcGIS Controls for WPF
Chromium Web Browser
Microsoft Virual Earth Control
Sharp Map Control

Wizard
Multimedia divelements Wizard
Actipro Wizard
DirectShowLib - .NET Wrapper for DirectShow
VideoRenderElement
Webcam Control
3D
WPF Media Kit - DVD Player, DirectShow,
WebCam Xceed 3D Views

3rdPartyLibs.html[2/16/2014 2:29:10 PM]


WPF Tutorial | List of 3rd-Party Controls

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2013-03-08 21:43:42


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 1.March 2009

Also, check out... http://www.telerik.com


Pete

Commented on 19.May 2009

Theo VERY NICE. THANK YOU!!!!


Zographos

Commented on 12.August 2009

Current version/replacement for "WPF Docking Library (Open Source)":

Mani
http://avalondock.codeplex.com

Please update.

Commented on 14.August 2009

FluidKit

pcdny
http://www.codeplex.com/fluidkit

Commented on 14.August 2009

FluidKit

pcdny
http://www.codeplex.com/fluidkit

Commented on 28.August 2009

You can try with Syncfusion WPF controls.

Bala
http://www.syncfusion.com/

Commented on 4.January 2010

can nebody telme wer i can get the freeware software for datagrid in wpf
pooja

Commented on 7.January 2010

please add timeline control from http://timeline.codeplex.com


asyrov

Commented on 25.February 2010

Here my FolderBrowseDialog http://wpfdialogs.codeplex.com/

TKundNobody

3rdPartyLibs.html[2/16/2014 2:29:10 PM]


WPF Tutorial | List of 3rd-Party Controls
The lost WPF Dialogs^^

Commented on 26.February 2010

very informative
Abirami

Commented on 26.February 2010

Please, add "Fluent Ribbon Control Suite" fluent.codeplex.com (to Toolbar section).

daVinci
Fluent Ribbon Control Suite is a library that implements an Office-like (Microsoft® Office Fluent�
user interface) for the Windows Presentation Foundation (WPF). It provides well-customized controls
such as RubbonTabControl, Gallery, QuickAccessToolbar, ScreenTip, StatusBar and so on. It is
bundled with the most up-to-date Office 2010 styles

Commented on 23.March 2010

Can you please add a www.componentart.com they're big players too.


John W.

Commented on 13.April 2010

Is WPF Window forms have Help Button(?) ?. pls let me know.Its very urgent.
Ranjan

Commented on 13.April 2010

I've used the Telerik WPF controls in previous work and I can confirm they're very easy to use and
David Cummins
pretty sexy.

Commented on 13.April 2010

I've used the Telerik WPF controls in previous work and I can confirm they're very easy to use and
David Cummins
pretty sexy.

Commented on 10.August 2010

Is there anyone test performance of grids that contains blinking, changing layout, painting (like real
yunus
time feed) with large data?

Commented on 10.August 2010

Is there anyone test performance of grids that contains blinking, changing layout, painting (like real
yunus
time feed) with large data?

Commented on 10.August 2010

componenArt.. componentone, and syncfusion which one is most good.. i want to purchase one
AFtab
anyone guide me

Commented on 11.August 2010

I am wondering how to create one!!!

Qualitatserz...
1) Creat the variable to store the value (include scale, range of the dial, etc etc) 2)draw the
background,and the form of the line, needle or hand 3) HOW TO CREATE THE NEEDLE ROTATION
EFFECT ???? animation??? somebody know how do the third party does???? thanks

Commented on 3.October 2010

3rdPartyLibs.html[2/16/2014 2:29:10 PM]


WPF Tutorial | List of 3rd-Party Controls
mlm.mylpsindia.com LivePath SOftwares Pvt. Ltd.

mlm.mylpsind...
MLM : Multi Level Marketing Softwares : Live Path softwares pvt. ... Contact us at
info@mylpsindia.com or contact at +91- 9549533331,9649433331 for all contacts

Commented on 30.November 2010

Sofa (Open Source), A wrapper for previously mentioned AvalonDock (Open Source) in the docking
WPF Sofa
libraries category, http://sofawpf.codeplex.com
TEAM

Commented on 22.December 2010

FYI,I have used AM Chart component to display the large data in charts.Its having zooming features in
Ravi P
linecharts,bar charts.

Commented on 10.February 2011

Here are some other helpful Links:

Pascal Szorath
- Multimedia: http://directcanvas.codeplex.com/ (A hardware accelerated, 2D drawing API that
supports vector graphics, multimedia files, extensible pixel shaders, blending modes and more!)

- Misc: http://j832.com/bagotricks/ (A collection of libraries and demos for WPF, Silverlight, and
Windows Phone 7)

- Effects : http://blog.pixelingene.com/?p=12 (Transitioncontainer)

- Injection: http://ninject.org/ Injection Toolkit

- MVVM: http://sachabarber.net/?page_id=523 (Chinch)

- MVVM: http://www.galasoft.ch/mvvm/getstarted/ (MVVM Light Toolkit)

Commented on 15.March 2011

GOOD ONE
James

Commented on 21.June 2011

Die ESRI WPF/Silverlight controls k&Atilde;&para;nnte man noch als GIS-Controls aufnehmen.

Jay
http://help.arcgis.com/en/webapi/silverlight/index.html

Name

E-Mail (optional)

Comment

Post Comment

3rdPartyLibs.html[2/16/2014 2:29:10 PM]


WPF Tutorial | Query Screen Resolutions

Home
    Interoperability
    Query Screen Resolutions Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF replacemenet for Screen.AllScreens()
Custom Controls
Many WPF applications want to check the available screen resolution to adjust window placements of sizes. In WinForms was a nice
Layout helper called Screen.AllScreens that returned a list of screens with their corresponding resolution. To use it from WPF you have
to reference System.Windows.Forms and System.Windows.Drawing which is not always what you want (because of
Input
application load time, dependencies, ambigue class names, etc.).
Data Binding
To get around this limitation I created a helper called Monitor which is a simple port of the Screen functionality from WinForms.
Styling
 
Localization public class Monitor
{
Interaction #region Dll imports
 
Resources
[DllImport("user32.dll", CharSet = CharSet.Auto)]
2D Graphics [ResourceExposure(ResourceScope.None)]
private static extern bool GetMonitorInfo
3D Graphics
(HandleRef hmonitor, [In, Out]MonitorInfoEx info);
Animation  
[DllImport("user32.dll", ExactSpelling = true)]
Multimedia
[ResourceExposure(ResourceScope.None)]
Documents private static extern bool EnumDisplayMonitors
(HandleRef hdc, IntPtr rcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
Windows 7  
private delegate bool MonitorEnumProc
Interoperability
(IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr lParam);
Performance  
[StructLayout(LayoutKind.Sequential)]
Expression Blend
private struct Rect
Tools {
public int left;
UI Automation
public int top;
public int right;
public int bottom;
}

ScreenResolutions.html[2/16/2014 2:29:47 PM]


WPF Tutorial | Query Screen Resolutions
 
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
private class MonitorInfoEx
{
internal int cbSize = Marshal.SizeOf(typeof(MonitorInfoEx));
internal Rect rcMonitor = new Rect();
internal Rect rcWork = new Rect();
internal int dwFlags = 0;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
internal char[] szDevice = new char[32];
}
 
private const int MonitorinfofPrimary = 0x00000001;
 
#endregion
 
public static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
 
public System.Windows.Rect Bounds { get; private set; }
public System.Windows.Rect WorkingArea { get; private set; }
public string Name { get; private set; }
 
public bool IsPrimary { get; private set; }
 
private Monitor(IntPtr monitor, IntPtr hdc)
{
var info = new MonitorInfoEx();
GetMonitorInfo(new HandleRef(null, monitor), info);
Bounds = new System.Windows.Rect(
info.rcMonitor.left, info.rcMonitor.top,
info.rcMonitor.right - info.rcMonitor.left,
info.rcMonitor.bottom - info.rcMonitor.top);
WorkingArea = new System.Windows.Rect(
info.rcWork.left, info.rcWork.top,
info.rcWork.right - info.rcWork.left,
info.rcWork.bottom - info.rcWork.top);
IsPrimary = ((info.dwFlags & MonitorinfofPrimary) != 0);
Name = new string(info.szDevice).TrimEnd((char)0);
}
 
public static IEnumerable<Monitor> AllMonitors
{
get
{
var closure = new MonitorEnumCallback();
var proc = new MonitorEnumProc(closure.Callback);
EnumDisplayMonitors(NullHandleRef, IntPtr.Zero, proc, IntPtr.Zero);
return closure.Monitors.Cast<Monitor>();
}
}
 
private class MonitorEnumCallback
{
public ArrayList Monitors { get; private set; }
 

ScreenResolutions.html[2/16/2014 2:29:47 PM]


WPF Tutorial | Query Screen Resolutions
public MonitorEnumCallback()
{
Monitors = new ArrayList();
}
 
public bool Callback(IntPtr monitor, IntPtr hdc,
IntPtr lprcMonitor, IntPtr lparam)
{
Monitors.Add(new Monitor(monitor, hdc));
return true;
}
}
}
 
 

  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Web Design Books

Last modified: 2012-12-06 16:52:36


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments


No comments for this article

Name

E-Mail (optional)

Comment

Post Comment

ScreenResolutions.html[2/16/2014 2:29:47 PM]


WPF Tutorial | Books

Home
    Getting started
    Books Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Books about WPF
Custom Controls

Layout
Windows Presentation Foundation 4.5 Cookbook
Input
The book contains over 80 recipes to effectively and efficiently develop rich Windows client
Data Binding
applications on the Windows platform. It is full of illustrations, diagrams, and tips with clear step-
Styling by-step instructions and real world examples to gain a strong foundation of WPF features and
patterns. It shows how to leverage the MVVM pattern to build decoupled, maintainable apps.
Localization
Autor: Pavel Yosifovich
Interaction
ISBN: 978-1849686228
Resources Published: Sept 2012

2D Graphics Find it at Packt publishing

3D Graphics

Animation WPF 4 - Unleashed


Multimedia In my opinion one of the best books about WPF - now updated to version 4.0. It's printed fully in
color, so all code samples have syntax highlighting. It includes all the good explanations and
Documents
samples of version 3 including new chapters about multitouch, XAML 2009, VSM, improved text
Windows 7 rendering, windows 7 shell integration and more.

Interoperability Autor: Adam Nathan

Performance
ISBN: 978-0672331190
Published: June 2010
Expression Blend
Find it at Amazon
Tools

UI Automation
WPF Control Development Unleashed

In this book, two leading Windows Presentation Foundation experts give developers everything
they need to build next-generation WPF applications--software that is more robust, usable, and

WPFBools.html[2/16/2014 2:30:02 PM]


WPF Tutorial | Books

compelling. Drawing on their close ties with Microsoft's WPF development team, Pavan Podila and
Kevin Hoffman give you a clear, robust, and practical understanding of WPF, its underpinnings, its
overall architecture, and its design philosophy.

Autor: Pavan Podila, Kevin Hoffman


ISBN: 978-0672330339
Published: September 2009
Find it at Amazon

Windows Presentation Foundation - Unleashed     (My favorite!)

In my opinion one of the best book about WPF. It covers all important themes including 3D
programming. All code samples have syntax highlighting. Digging deeper sections with additional
informations for advanced programmers.

Autor: Adam Nathan


ISBN: 978-0672328916
Published: January 2007
Find it at Amazon

Application = Code + Markup

"Get the definitive guide to the Windows Presentation Foundation (WPF), the new client
programming interface for the Microsoft .NET Framework 3.0 and Windows Vista. Award-winning
author Charles Petzold teaches you how to combine C# code and the Extensible Application
Markup Language (XAML) to develop applications for the WPF.". I cannot unterstand how anyone
can write a book about a UI technology without a single illustration. If you prefer gray text to
colorful images, it might be the book for you.

Autor: Charles Petzold


ISBN: 978-0735619579
Published: August 2006

Essential Windows Presentation Foundation

Chris Anderson was one of the chief architects of the next-generation GUI stack, the Windows
Presentation Framework (WPF), which is the subject of this book. Chris's insights shine a light from
the internals of WPF to those standing at the entrance, guiding you through the concepts that
form the foundation of his creation.

Autor: Chris Anderson


ISBN: 978-0321374479
Published: April 2007

Foundations of WPF: An Introduction to Windows Presentation Foundation

Foundations of WPF: An Introduction to Windows Presentation Foundation teaches you everything

WPFBools.html[2/16/2014 2:30:02 PM]


WPF Tutorial | Books

you need to get started with the technology, and is broken into three parts. The first introduces
and contextualizes the WPF technology; the second part dives deeper into the facets of the
technology that are of immediate and valuable use in developing applications; the last part offers
you the real-world perspective you need to be productive in the community and customer base.

Autor: Laurence Moroney


ISBN: 978-1590597606
Published: November 2006

Pro WPF in C# 2008

This book explains how WPF works from the ground up. It follows on from the author s previous
and highly successful books, covering Windows Forms (WPF's predecessor technology) and earlier
versions of WPF. It is a one-stop shop in Apress proven Pro style that leaves readers with a deep
understanding of the technology and able to take the concepts away and apply them for
themselves.

Autor: Matthew McDonald


ISBN: 978-1590599556
Published: Februar 2008

Foundations of WPF: An Introduction to Windows Presentation Foundation

If you want to build applications that take full advantage of Windows Vista's new user interface
capabilities, you need to learn Microsoft's Windows Presentation Foundation (WPF). This new
edition, fully updated for the official release of .NET 3.0, is designed to get you up to speed on this
technology quickly.

Autor: Chris Sells and Ian Griffiths


ISBN: 978-0596510374
Published: September 2007

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2012-10-24 09:40:51


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 14.September 2010

i like ur tutorials.pls provide and free pdf books


Muthu

Commented on 14.September 2010

WPFBools.html[2/16/2014 2:30:02 PM]


WPF Tutorial | Books
i like ur tutorials.pls provide and free pdf books
Muthu

Commented on 29.September 2010

UjJEVY http://cgE8hcmk9Vvqlosr5wcBa6nk.com
melony

Commented on 14.October 2010

hi,

neo
can any one send above mentioned books links plzzz

Commented on 1.November 2010

Hi could any one send me the free ebooks which can be downloaded
sirisha Gundala

Commented on 13.November 2010

Hey sajan, varsha and sirisha..!! Download the books free of costs..!!
Mohanish

Commented on 16.November 2010

Can some one let me know, where i can found the freeversion of above books.. thanks
Praveen

Commented on 21.December 2010

Hi.. i need calculator program in c# .net wpf, with oops concepts.. i.e with class methods operator
arunkalis
overloading...pls help me and drop ur mail to: arunkalis@gmail.com

Commented on 22.December 2010

Hi everyone....

jehanzeb afridi
Nice article..

You can download many of those mentioned books from wwww.4shared.com

Regards

Jehanzeb afridi

Commented on 29.December 2010

Wow !!!
suvo

Commented on 7.January 2011

er.... all those people asking for free versions of the books. The authors didn't write them for free you
author
know!

Commented on 22.January 2011

Try in torrents..
Arka...

Commented on 28.January 2011

you are the best moser


sanjin...

Commented on 28.January 2011

This is Excellent.....

Abhishek

WPFBools.html[2/16/2014 2:30:02 PM]


WPF Tutorial | Books
I want a link from which I can download a free book....

Commented on 30.January 2011

Good work. How about a -next page - so I don't have to keep going back to the menu to proceed
akalan

Commented on 31.January 2011

http://www.mediafire.com/?vyjzln0mnjj (Windows.Presentation.Foundation.Unleashed)

BAd

Commented on 4.February 2011

wow,thx Bad :)
Not Bad

Commented on 23.March 2011

really !Very nice tutorial


Sudhakar

Commented on 30.March 2011

good material thanks &lt;a href=&quot; http://gs124.photobucket.com/groups/p2/PLJLLS8GT2


Ldeenpgk
&quot;&gt;loli bbs board
&lt;/a&gt; =-PPP

Commented on 26.April 2011

you can download from google. just type the title of book and &amp;pdf in keyword search
whiteTry

Commented on 10.May 2011

Do you know some books for C# or VB .NET ... but I mean good books like WPF 4 - Unleashed? And
Faith
what about ASP .NET? The internet is full of them but I want something really good and updated :D

Commented on 29.June 2011

I want to know more in depth about WPF like how itemscontrol,datatemplet,trigger,Icommand,routed


John
event work in WPF...any book or blog,video,,please suggest

Commented on 20.August 2011

Pls send me everything for free. I hope to develop software and sell it to get rich. Sure hope nobody
GiveMeAllImLaZ
downloads my software 4 free!

Commented on 22.August 2011

hhgh
hg

Commented on 23.August 2011

I started with Wrox, it is not really good no really action. Like the tutorial all ready :)
bole

Name

E-Mail (optional)

Comment

WPFBools.html[2/16/2014 2:30:02 PM]


WPF Tutorial | Books

Post Comment

WPFBools.html[2/16/2014 2:30:02 PM]


WPF Tutorial | Undo/Redo

Home
    Patterns
    Undo/Redo Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to implement undo/redo using MVVM
Custom Controls

Layout
Introduction

Input One feature that many users demand is a neatless undo/redo integration. This means that the application allows the user to revert
any modification he made - one by one - back to the start of the application and than eventually reapply them again. This improves
Data Binding
the usability a lot, because it allows the user to carelessly use an unclear command, because he is certain, that he can undo it if he
Styling was wrong. Today undo/redo has gotten almost standard for any modern data editing application.

Localization

Interaction

Resources

2D Graphics

3D Graphics The MVVM-Pattern


Animation
Because of the strong databinding functionality in WPF, most applications are using the popular MVVM (Model-View-ViewModel)
Multimedia pattern. The idea of this pattern is basically to define a class that aggregates all data and commands for a certain view and provides
them to the view as properties where it can bind to. Changes on properties are notified by an event on the
Documents
INotifyPropertyChanged interface.
Windows 7
A concept of implementing undo/redo
Interoperability

Performance A classical approach to implement undo/redo is to allow changes on the model only through commands. And every command should
be invertible. The user than executes an action, the application creates a command, executes it and puts an inverted command on
Expression Blend the undo-stack. When the user clicks on undo, the application executes the top-most (inverse) command on the undo-stack, inverts it
again (to get the original command again) and puts it on the redo-stack. That's it.
Tools
Scenario 1: Executing an action
UI Automation

UndoRedo.html[2/16/2014 2:30:40 PM]


WPF Tutorial | Undo/Redo

Scenario 2: Undoing an action

Adoption for WPF

We start with a base class that implements the INotifyPropertyChanged interface and provides a private method
Notify(string propertyName).

 
public class NotifyableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
 

UndoRedo.html[2/16/2014 2:30:40 PM]


WPF Tutorial | Undo/Redo
protected void Notify(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
 
 
Then we build the base class TrackableObject where all model objects or view models that are directly bound to the view should
inherit from.
 
public class TrackableObject : NotifyableObject
{
private readonly List<ITrackable> _trackableItems = new List<ITrackable>();
 
public bool HasChanges
{
get { return _trackableItems.Any(i => i.HasChanges); }
}
 
public IModificationTracker ModificationTracker { get; set; }
 
protected TrackableValue<T> RegisterTrackableValue<T>(string propertyName,
T defaultValue = default(T))
{
var property = new TrackableValue<T>(propertyName, Modify, Notify,
defaultValue);
_trackableItems.Add(property);
return property;
}
 
protected TrackableCollection<T> RegisterTrackableCollection<T>()
{
var collection = new TrackableCollection<T>(Modify);
_trackableItems.Add(collection);
return collection;
}
 
private void Modify(Action doAction, Action undoAction, Action notification)
{
var modification = new Modification(doAction, undoAction, notification);
modification.Execute();
ModificationTracker.TrackModification(modification);
}
}
 
 
To simplify the generation of modifactions when changing a property value, we build a generic wrapper for each property called
TrackableValue.

 
public class TrackableValue<T> : ITrackable
{
private readonly string _propertyName;

UndoRedo.html[2/16/2014 2:30:40 PM]


WPF Tutorial | Undo/Redo
private readonly Action<Action, Action, Action> _modifyCallback;
private readonly Action<string> _notifyAction;
private T _value;
 
public TrackableValue(string propertyName,
Action<Action, Action, Action> modifyCallback,
Action<string> notifyAction, T defaultValue)
{
_propertyName = propertyName;
_modifyCallback = modifyCallback;
_notifyAction = notifyAction;
_value = defaultValue;
}
 
public bool HasChanges
{
get { return _originalValue.Equals(_value); }
}
 
public T Value
{
get { return _value; }
set
{
var oldValue = _value;
_modifyCallback(() => _value = value,
() => _value = oldValue,
() => _notifyAction(_propertyName));
}
}
}
 
 
To same thing we need to do for collections to track add/remove of items from a collection
 
public class TrackableCollection<T> : IList<T>, ITrackable
{
private readonly Action<Action, Action, Action> _modifyCallback;
private readonly List<T> _list = new List<T>();
private readonly List<T> _originalList = new List<T>();
 
public TrackableCollection(Action<Action, Action, Action> modifyCallback)
{
_modifyCallback = modifyCallback;
}
 
public event EventHandler<EventArgs<T>> ItemAdded;
public event EventHandler<EventArgs<T>> ItemRemoved;
public event EventHandler CollectionChanged;
 
public bool HasChanges
{
get
{
if( _list.Count == _originalList.Count)

UndoRedo.html[2/16/2014 2:30:40 PM]


WPF Tutorial | Undo/Redo
{
return _list.Where((item, index) =>
!item.Equals(_originalList[index])).Any();
}
return true;
}
}
 
public void AcceptChanges()
{
_originalList.Clear();
_originalList.AddRange(_list);
}
 
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
 
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
 
public void Add(T item)
{
_modifyCallback(() =>
{
_list.Add(item);
ItemAdded.Notify(this, new EventArgs<T>(item));
},
() =>
{
_list.Remove(item);
ItemRemoved.Notify(this, new EventArgs<T>(item));
},
OnCollectionModified);
}
 
public void Clear()
{
var items = new T[_list.Count];
_list.CopyTo(items);
_modifyCallback(() =>
{
_list.ForEach(i => ItemRemoved.Notify(this, new EventArgs<T>(i)));
_list.Clear();
},
() =>
{
_list.AddRange(items);
_list.ForEach(i => ItemAdded.Notify(this, new EventArgs<T>(i)));
},
OnCollectionModified);
}
 
UndoRedo.html[2/16/2014 2:30:40 PM]
WPF Tutorial | Undo/Redo

public bool Contains(T item)


{
return _list.Contains(item);
}
 
public void CopyTo(T[] array, int arrayIndex)
{
_list.CopyTo(array, arrayIndex);
}
 
public bool Remove(T item)
{
var result = _list.Contains(item);
_modifyCallback(() =>
{
_list.Remove(item);
ItemRemoved.Notify(this, new EventArgs<T>(item));
},
() =>
{
_list.Add(item);
ItemAdded.Notify(this, new EventArgs<T>(item));
},
OnCollectionModified);
return result;
}
 
public int Count
{
get { return _list.Count; }
}
 
public bool IsReadOnly
{
get { return false; }
}
 
public int IndexOf(T item)
{
return _list.IndexOf(item);
}
 
public void Insert(int index, T item)
{
_modifyCallback(() =>
{
_list.Insert(index, item);
ItemAdded.Notify(this, new EventArgs<T>(item));
},
() =>
{
_list.Remove(item);
ItemRemoved.Notify(this, new EventArgs<T>(item));
},
OnCollectionModified);

UndoRedo.html[2/16/2014 2:30:40 PM]


WPF Tutorial | Undo/Redo
}
 
public void RemoveAt(int index)
{
var item = _list[index];
_modifyCallback(() =>
{
_list.Remove(item);
ItemRemoved.Notify(this, new EventArgs<T>(item));
},
() =>
{
_list.Insert(index, item);
ItemAdded.Notify(this, new EventArgs<T>(item));
},
OnCollectionModified);
}
 
public T this[int index]
{
get { return _list[index]; }
set
{
var oldItem = _list[index];
_modifyCallback(() =>
{
_list[index] = value;
ItemAdded.Notify(this, new EventArgs<T>(value));
},
() =>
{
_list[index] = oldItem;
ItemRemoved.Notify(this, new EventArgs<T>(oldItem));
},
OnCollectionModified);
}
}
 
private void OnCollectionModified()
{
CollectionChanged.Notify(this, EventArgs.Empty);
}
}
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2011-12-23 09:14:09


Copyright (c) by Christian Moser, 2011.

 Comments on this article

UndoRedo.html[2/16/2014 2:30:40 PM]


WPF Tutorial | Undo/Redo

Show all comments


No comments for this article

Name

E-Mail (optional)

Comment

Post Comment

UndoRedo.html[2/16/2014 2:30:40 PM]


WPF Tutorial | Getting started

Home
    Getting started Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Getting Started
Custom Controls
Welcome to the world of Windows Presentation Foundation. I'm sure you will be amazed by the possibilities of creating stunning user
Layout interfaces with a minimal effort. In these chapter you will gather the basic knowledge and setup your enviroment to immediately start
developing WPF applications.
Input

Data Binding
Next Steps
Styling

Localization Introduction to WPF


Development Tools
Interaction
Books
Resources
Create a simple WPF application
2D Graphics Instruction Videos
Learn WPF in two Weeks
3D Graphics

Animation
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Multimedia

Documents
Last modified: 2009-05-19 01:31:37
Windows 7 Copyright (c) by Christian Moser, 2011.

Interoperability

Performance

Expression Blend

Tools

UI Automation

GettingStarted.html[2/16/2014 2:30:56 PM]


WPF Tutorial | Fundamentals

Home
    Fundamentals Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Fundamentals
Custom Controls
WPF has some important new concepts that are beyond of what most .NET developers know from WinForms. But its very useful to
Layout understand these concepts before you start developing WPF applications.
Input
What's new in XAML in .NET 4.0
Data Binding XAML
Dependency Properties
Styling
Routed Events
Localization
Logical- and Visual Tree
Interaction Hard- and Softwarerequirements
WPF Troubleshooting
Resources

2D Graphics

3D Graphics

Animation
Last modified: 2009-05-19 01:31:13
Multimedia
Copyright (c) by Christian Moser, 2011.

Documents

Windows 7
 Comments on this article
Interoperability
Show all comments
Performance

Expression Blend Commented on 12.September 2011

Tools prashant what is WPF? could be explain me briefly ???

Kumar
UI Automation

Name

E-Mail (optional)

WPFFundamentals.html[2/16/2014 2:31:41 PM]


WPF Tutorial | Fundamentals
Comment

Post Comment

WPFFundamentals.html[2/16/2014 2:31:41 PM]


WPF Tutorial | User Experience

Home
    User Experience Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Designing the User Experience
Custom Controls
UX Design Process
Layout

Input
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Data Binding

Styling
Last modified: 2009-11-01 11:41:09
Localization Copyright (c) by Christian Moser, 2011.

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

UX.html[2/16/2014 2:31:56 PM]


WPF Tutorial | Patterns

Home
    Patterns Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Patterns to design a good WPF architecture
Custom Controls
Model-View-ViewModel Pattern
Layout
Dependency Injection
Input Undo/Redo
Data Binding DelegateCommand

Styling

Localization   ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Interaction
Last modified: 2010-02-10 10:33:22
Resources
Copyright (c) by Christian Moser, 2011.

2D Graphics

3D Graphics
 Comments on this article
Animation
Show all comments
Multimedia
No comments for this article
Documents

Windows 7 Name

Interoperability E-Mail (optional)

Performance
Comment

Expression Blend

Tools Post Comment

UI Automation

ArchitecturePattern.html[2/16/2014 2:32:10 PM]


WPF Tutorial | Controls

Home
    Controls Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Built-in Controls of WPF
Custom Controls
The WPF framework provides a rich set of built-in controls. The controls can be devided in the following categories.
Layout
List of 3rd-Party Controls
Input
DataGrid
Data Binding Calendar
Styling ItemsControl
LivePreview ComboBox
Localization
Dialogs
Interaction Slider
Resources Popup
RadioButton
2D Graphics
ToolTips
3D Graphics TextBox
Animation Menus
Expander
Multimedia
PasswordBox
Documents
ContextMenu
Windows 7 ListBox
ListView
Interoperability
TextBlock
Performance
Window
Expression Blend

Tools   ► Tutorial   ► C Sharp Tutorial   ► ASP Net Tutorial   ► Tutorial VB 2005
UI Automation

Last modified: 2008-10-18 01:05:14


Copyright (c) by Christian Moser, 2011.

Controls.html[2/16/2014 2:32:45 PM]


WPF Tutorial | Controls

 Comments on this article

Show all comments

Commented on 2.July 2009

can you make a mailing list, so everyone can subscribe and get a message in our mail evry time you
anonimo
public a new article?

Commented on 20.July 2009

Yeah, I agree with anonimo.

Farooq
Azam
Would love to subscribe to this site.

Commented on 11.February 2010

Yeah, i too agree with anonimo..it will helpfull


sathya

Commented on 14.February 2010

Yeah,I also agree with this idea


AlexG

Commented on 1.April 2010

Subscribe to the RSS feed. Mailing lists are old school.


Valamas

Commented on 12.July 2010

How to use combobox control in WPF?


Siju

Commented on 19.July 2010

great site. been here for two weeks. thank you for the wonderful tutorial!
UandI

Commented on 11.March 2011

Nice Website.

vinay
and i want to learn WPF and WCF Plz help me.

kasera

Commented on 7.April 2011

feeling good to learn this .... :)


sachin

Commented on 14.June 2011

Very Nice!. Why he never answer questions???


dch

Name

E-Mail (optional)

Comment

Controls.html[2/16/2014 2:32:45 PM]


WPF Tutorial | Controls
Post Comment

Controls.html[2/16/2014 2:32:45 PM]


WPF Tutorial | Custom Controls

Home
    Custom Controls Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Custom Controls
Custom Controls
UserControls vs. CustomControls
Layout
How to Create a Custom Control
Input

Data Binding

Styling

Localization
Last modified: 2009-06-16 02:05:43

Interaction Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

CustomControls.html[2/16/2014 2:33:10 PM]


WPF Tutorial | Layout

Home
    Layout Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Layout
Custom Controls
Introduction to WPF Layout
Layout
StackPanel
Input Grid Panel
Data Binding Dock Panel
Canvas Panel
Styling
Wrap Panel
Localization ViewBox
Interaction Create a Custom Layout Panel

Resources

2D Graphics   ► Tutorial   ► Adobe InDesign   ► InDesign CS3   ► Photoshop CS4

3D Graphics

Last modified: 2008-10-18 01:05:14


Animation
Copyright (c) by Christian Moser, 2011.

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

Layout.html[2/16/2014 2:33:46 PM]


WPF Tutorial | Input

Home
    Input Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Input
Custom Controls
Keyboard
Layout
RoutedCommands in a ContextMenu
Input Mouse
Data Binding Mutli Touch

Styling

Localization

Interaction
Last modified: 2009-05-19 01:32:02
Resources
Copyright (c) by Christian Moser, 2011.

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

Input.html[2/16/2014 2:34:15 PM]


WPF Tutorial | Data Binding

Home
    Data Binding Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Data Binding
Custom Controls
Data Binding Overview
Layout
Debug DataBinding Issues
Input Data Validation
Data Binding Value Converters
Data Viewing, Sorting and Filtering
Styling
Popular Data Binding Expressions
Localization How to Bind EnumValues
Interaction Elegant way for INotifyPropertyChanged

Resources

2D Graphics

3D Graphics

Last modified: 2008-10-18 01:07:42


Animation
Copyright (c) by Christian Moser, 2011.

Multimedia

Documents
 Comments on this article
Windows 7
Show all comments
Interoperability

Performance Commented on 28.September 2010

Hi. what about data binding whne you want a particular column in the grid to be able to accept drops from a
Expression Blend PVA
treeview? I mean I want to drag a node from RadTreeView into a column of a RadGridView? Is that possible?
Tools If yes then what do I bind the column to? If not bind then which event handlers should I be using in the code
behind to make the column accept the string data from the treenode? And if this is not possible then should I
UI Automation
be using a DataGrid instead of a RadGridView?? Any reply/help/ would be appreciated.

Name

Databinding.html[2/16/2014 2:34:59 PM]


WPF Tutorial | Data Binding
E-Mail (optional)
Comment

Post Comment

Databinding.html[2/16/2014 2:34:59 PM]


WPF Tutorial | Styling

Home
    Styling Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Templates and Styles
Custom Controls
One of WPF's most powerful feature is the ability to completely replace the look and feel of user interface elements.
Layout

Input
Styles
Data Binding
The concept of styles let you remove all properties values from the individual user interface elements and combine them into a style.
Styling
A style consists of a list of property setters. If you apply a style it sets the properties on the user interface element to the styles'
Localization values. The idea is quite similar to Cascading Styles Sheets (CSS) in web development.

Using styles gives you the following advantages:
Interaction
Removes redundancy from your code
Resources
Let you change the appearance of a set of controls from a single point
2D Graphics Gives you the possibility to swap the style at runtime

3D Graphics Learn more about Styles

Animation

Multimedia Templates
Documents An element like a button consists of multpiple composed parts: A border, a chrome and a content presenter. With styles you can only
change the appearance from "outside" by setting public properties. With a template you can replace parts inside a user interface
Windows 7
element..
Interoperability
Using templates gives you the following advantages:

Performance Change the parts inside a user interface element


Reduce the numbers custom controls
Expression Blend

Tools Learn more about Templates

UI Automation   ► Tutorial   ► Adobe InDesign   ► InDesign CS3   ► InDesign Template

Last modified: 2011-05-03 10:40:49


Copyright (c) by Christian Moser, 2011.

TemplatesStyles.html[2/16/2014 2:35:14 PM]


WPF Tutorial | Styling

 Comments on this article

Show all comments

Commented on 9.August 2010

Very clear article, as is the case for all those I've happened upon on the site so far. I was real interested in
Andre
getting more information about templates though, but it turns out the link is broken...
(http://www.wpftutorial.net/Templates.html)

Commented on 18.May 2011

Hi very interesting stuff on your site would be great to have a download attached to some of the articles that
elhuus
might need it.

I believe WPF styles and themes could have been better with a simpler syntax (a CSS like syntax) than with the
xml format just as they did for binding syntax.

thanks for the great help and articles you provide

Commented on 26.July 2011

wpf
andre

Name

E-Mail (optional)

Comment

Post Comment

TemplatesStyles.html[2/16/2014 2:35:14 PM]


WPF Tutorial | Localization

Home
    Localization Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Localization in WPF
Custom Controls
Evaluate a localization mechanism
Layout
Localization using a MarkupExtension
Input

Data Binding
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Styling

Localization
Last modified: 2010-02-23 00:17:46

Interaction Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics  Comments on this article

3D Graphics
Show all comments
Animation
Commented on 10.November 2010
Multimedia
Thanx, great article
A
Documents

Windows 7 Name
Interoperability E-Mail (optional)
Performance Comment

Expression Blend

Tools
Post Comment

UI Automation

Localisation.html[2/16/2014 2:35:50 PM]


WPF Tutorial | Interaction

Home
    Interaction Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Interactions
Custom Controls
Drag & Drop
Layout
Behaviors
Input

Data Binding
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Styling

Localization
Last modified: 2009-10-13 09:42:58

Interaction Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics  Comments on this article

3D Graphics
Show all comments
Animation No comments for this article

Multimedia
Name
Documents
E-Mail (optional)
Windows 7
Comment
Interoperability

Performance
Post Comment
Expression Blend

Tools

UI Automation

Interactions.html[2/16/2014 2:36:19 PM]


WPF Tutorial | Resources

Home
    Resources Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Resources
Custom Controls

Layout
Articles about WPF Resources
Input
MergedDictionaries
Data Binding
Read WPF resources from WinForms
Styling Set DynamicResource from Code

Localization Loading BAML

Interaction
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Resources

2D Graphics
Last modified: 2008-10-18 01:08:42
3D Graphics
Copyright (c) by Christian Moser, 2011.

Animation

Multimedia
 Comments on this article
Documents
Show all comments
Windows 7
No comments for this article
Interoperability

Performance Name

Expression Blend E-Mail (optional)

Comment
Tools

UI Automation

Post Comment

Resources.html[2/16/2014 2:36:53 PM]


WPF Tutorial | Resources

Resources.html[2/16/2014 2:36:53 PM]


WPF Tutorial | 2D Graphics

Home
    2D Graphics Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
2D Graphics
Custom Controls
Draw excactly on physical device pixels
Layout
Geometry Transformer
Input Images
Data Binding How to get a Bitmap from a Visual
DrawRoundedRectangle
Styling

Localization
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Interaction

Resources
Last modified: 2009-05-19 01:32:33
2D Graphics Copyright (c) by Christian Moser, 2011.

3D Graphics

Animation
 Comments on this article
Multimedia
Show all comments
Documents
Commented on 11.May 2009
Windows 7
hi
Interoperability jatin

Performance Commented on 19.August 2011

Expression Blend Nice Web site


hi
Tools

UI Automation Name

E-Mail (optional)
Comment

Graphics2D.html[2/16/2014 2:37:17 PM]


WPF Tutorial | 2D Graphics

Post Comment

Graphics2D.html[2/16/2014 2:37:17 PM]


WPF Tutorial | 3D Graphics

Home
    3D Graphics Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
3D Graphics
Custom Controls
Introduction to WPF 3D
Layout

Input
  ► 3D Graphics   ► Blender Tutorial   ► Drawing Tutorial   ► 3D Rendering
Data Binding

Styling
Last modified: 2009-07-04 16:20:50
Localization Copyright (c) by Christian Moser, 2011.

Interaction

Resources
 Comments on this article
2D Graphics
Show all comments
3D Graphics
Commented on 2.March 2009
Animation
I hope you continue the article..
Multimedia Lentucky

Documents Commented on 9.June 2009

Windows 7 plz continue

abbasek23
Interoperability
Commented on 20.June 2009
Performance
este es uno de mis mas grandes intereses de WPF. estare revisandolo continuamente esperando la
anonimo
Expression Blend informacion.

Tools
this is one of my biggest interests WPF. i will be reviewing the article for the information.
UI Automation

Commented on 24.June 2009

Still waiting for 3D graphics article.....


Deep232

Graphics3D.html[2/16/2014 2:37:54 PM]


WPF Tutorial | 3D Graphics

Commented on 2.July 2009

Is there any possiblity to develop Very Much Heavy CAD application with help of Directx and WPF but
olive
not opengl.

Commented on 3.July 2009

Deep232, i think that there are better ways to say(write) that.


anonimo

Commented on 4.July 2009

Hi Olive,

Christian
WPF allows you to seamlessly integrate 3D content into your application. It's all managed and easy to
Moser
use, but when it comes to high performance requirements, it's not the way to go. Since .NET 3.5 SP1,
Microsoft provides a D3DImage object, that allows direct interop with unmanaged DirectX.
I hope this helps.

Greetings

Christian

Commented on 9.June 2010

como hacer un comobox en wpf


Pedro

Commented on 9.June 2010

combobox en wpf

pedro

Commented on 11.March 2011

Rich Text Box in WPF


Rich Text...

Name

E-Mail (optional)
Comment

Post Comment

Graphics3D.html[2/16/2014 2:37:54 PM]


WPF Tutorial | Animation

Home
    Animation Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Animations in WPF
Custom Controls
Debugging Animations
Layout
Adjust the Frame Rate
Input

Data Binding
  ► Tutorial   ► 3D Max Tutorials   ► 3D Animation   ► Flash Animation
Styling

Localization
Last modified: 2009-05-19 01:32:48

Interaction Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics  Comments on this article

3D Graphics
Show all comments
Animation
Commented on 4.February 2011
Multimedia
it`s looking awesome
chinni
Documents

Windows 7 Commented on 5.August 2011

can i add flash in wpf.net


Interoperability rekha

Performance
Name
Expression Blend
E-Mail (optional)
Tools
Comment
UI Automation

Post Comment

Animation.html[2/16/2014 2:38:19 PM]


WPF Tutorial | Animation

Animation.html[2/16/2014 2:38:19 PM]


WPF Tutorial | Multimedia

Home
    Multimedia Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Multimedia in WPF
Custom Controls
This article is not yet finished...
Layout

Input
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Data Binding

Styling
Last modified: 2008-10-18 01:10:37
Localization
Copyright (c) by Christian Moser, 2011.

Interaction

Resources
 Comments on this article
2D Graphics
Show all comments
3D Graphics

Commented on 26.March 2009


Animation
I am creating a multimedia application and need to know about how to stream video.

Multimedia jk

Documents thanks

Windows 7
Commented on 16.May 2009
Interoperability
We are interest in multimedia application with WPF.
Peter
Performance

Expression Blend Commented on 22.May 2009

Tools
Is it possible to capture real-time Firewire stream with it? How ?
Rychard

UI Automation
Commented on 3.November 2009

I'm interested in video streaming as well.


ZC

Multimedia.html[2/16/2014 2:38:55 PM]


WPF Tutorial | Multimedia

Commented on 11.November 2009

We are interest in multimedia application with WPF.


gaurang

Commented on 19.January 2010

bell we are interested in multimedia application with wpf.


chell

Commented on 29.January 2010

I desperately need the solution to play flash files (.flv) in WPF


vikas

Commented on 11.August 2011

need to know multimedia application


namit

Name

E-Mail (optional)

Comment

Post Comment

Multimedia.html[2/16/2014 2:38:55 PM]


WPF Tutorial | Documents

Home
    Documents Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Documents
Custom Controls
Inline Images in a FlowDocument
Layout
FlowDocuments
Input

Data Binding
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Styling

Localization
Last modified: 2010-07-14 16:50:08

Interaction Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics  Comments on this article

3D Graphics
Show all comments
Animation No comments for this article

Multimedia
Name
Documents
E-Mail (optional)
Windows 7
Comment
Interoperability

Performance
Post Comment
Expression Blend

Tools

UI Automation

Documents.html[2/16/2014 2:39:10 PM]


WPF Tutorial | Windows 7

Home
    Windows 7 Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Using the Vista API
Custom Controls
Task Dialog
Layout
Glass Windows
Input Jumplists
Data Binding

Styling

Localization

Interaction Last modified: 2009-11-01 11:04:22


Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics

 Comments on this article


3D Graphics

Animation Show all comments


No comments for this article
Multimedia

Documents
Name
Windows 7 E-Mail (optional)
Interoperability Comment

Performance

Expression Blend
Post Comment

Tools

UI Automation

VistaAPI.html[2/16/2014 2:39:50 PM]


WPF Tutorial | Interoperability

Home
    Interoperability Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to get the Handle of a WPF Window
Custom Controls
 
Layout
IntPtr windowHandle = new WindowInteropHelper(
Input Application.Current.MainWindow).Handle;
 
Data Binding  
Styling
How to manually set the rendering mode to software
Localization
 
Interaction var source = PresentationSource.FromVisual(this);
var hwndTarget = source.CompositionTarget as HwndTarget;
Resources
if (hwndTarget != null)
2D Graphics {
hwndTarget.RenderMode = RenderMode.SoftwareOnly;
3D Graphics }
 
Animation
 
Multimedia

Documents   ► Tutorial   ► Learn Quick Books   ► Coding Learning   ► Basics

Windows 7

Interoperability Last modified: 2010-07-06 16:40:47


Copyright (c) by Christian Moser, 2011.

Performance

Expression Blend

 Comments on this article


Tools

UI Automation Show all comments

Commented on 14.November 2010

Can you provide more details on interoperability. Like how to use OCX files, Active X DLL created in
Veerendra...
VC++ in WPF applications.

Interoperability.html[2/16/2014 2:40:04 PM]


WPF Tutorial | Interoperability

Name

E-Mail (optional)

Comment

Post Comment

Interoperability.html[2/16/2014 2:40:04 PM]


WPF Tutorial | Performance

Home
    Performance Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Performance Optimization
Custom Controls
Top 11 WPF Performance Tips
Layout

Input
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes
Data Binding

Styling
Last modified: 2010-05-10 22:24:44
Localization Copyright (c) by Christian Moser, 2011.

Interaction

Resources
 Comments on this article
2D Graphics
Show all comments
3D Graphics
Commented on 24.April 2009
Animation
I like the suggestions. However, there are a few spelling mistakes.
Multimedia Sean

Thanks.
Documents

Windows 7
Commented on 19.May 2009
Interoperability Nice tips. It would be helpful if you mentioned some tips regarding the use of Visuals instead of
Theo
Performance
controls/elements higher in the hierarchy.
Zographos

Expression Blend
Commented on 12.August 2009
Tools
What about migrating our client applications developed on C#, using System.Data.SqlClient accessing
Ariel
UI Automation ot Sql Server 2005 databases? Shall we start now?

Commented on 29.January 2010

I don't understand what you mean by "cached resource dictionaries" can you please provide a small

Performance.html[2/16/2014 2:40:41 PM]


WPF Tutorial | Performance
Daniel
example?

Commented on 6.May 2010

faraya hot lebanon lebanese klynn k-lynn fashion show model lingerie snow mzar
y78dha7

Commented on 21.October 2010

<IMG>http://jerry-fisher.co.cc/93.jpg</IMG>
blyadieos
http://piska.chez.com/pelvimetry-civi.html УÑ�ебнÑ�е Ñ�илÑ�мÑ�: маÑ�Ñ�Ð
°Ð¶ гейÑ�и + обнаженнÑ�й маÑ�Ñ�аж (DVDRip)
http://piska.chez.com/misunderstand-a.html
http://blyadi.atspace.com/echoplex-apenda.html
http://piska.chez.com/india-methodica.html
http://piska.chez.com/shallowness-ant.html
http://piska.chez.com/scirrhous-prodi.html
http://blyadi.atspace.com/avulsive-antimo.html
http://piska.chez.com/pimaricin-ssts-.html
http://piska.chez.com/mainframe-apts-.html �о�но �олик Pretty Russian Teen
gets raped (DVDRip)
http://blyadi.atspace.com/chloe-hammock-e.html
http://blyadi.atspace.com/behemoth-trichl.html
http://piska.chez.com/sanitorium-pylo.html
http://piska.chez.com/tautologically-.html
http://piska.chez.com/attendees-sisyp.html
http://piska.chez.com/subregistrar-sk.html
http://piska.chez.com/disappointment-.html Ð�олодаÑ� Ð�евка Ð�Ñ�Ñ�Ð
°Ñ�Ñ�ваеÑ� У Ð�аÑ�нÑ� (DVDRip)
http://blyadi.atspace.com/portraitist-taf.html
http://blyadi.atspace.com/droplet-multi-a.html
http://piska.chez.com/ventral-counter.html
http://piska.chez.com/integrability-t.html
http://blyadi.atspace.com/towpath-raving-.html
http://blyadi.atspace.com/spawns-aggravat.html
http://blyadi.atspace.com/treasurer-quitc.html
http://blyadi.atspace.com/tetracaine-soci.html �о�но о�гии Euro Sex Party 2(2007)
<Orgy> (DVDRip)
http://blyadi.atspace.com/bbs-unforgettab.html
http://blyadi.atspace.com/egret-fair-buck.html
http://piska.chez.com/vagal-subpenas-.html
http://blyadi.atspace.com/stupifying-vibr.html
http://blyadi.atspace.com/obstetrician-da.html
http://blyadi.atspace.com/scrammed-machin.html
http://blyadi.atspace.com/easing-wanderer.html
http://piska.chez.com/unrestricted-ge.html �о�но � ак�оба�кой
North Pole 65 (2006)<All Sex> (DVDRip)
http://blyadi.atspace.com/participated-pa.html
http://piska.chez.com/fileid-rejoice-.html
http://piska.chez.com/slattern-rope-a.html
http://blyadi.atspace.com/macsyma-turrete.html
http://piska.chez.com/settee-one-card.html
http://piska.chez.com/index.html
http://blyadi.atspace.com/seemingness-cou.html
http://blyadi.atspace.com/index.html
http://blyadi.atspace.com/symposiums-usin.html
http://blyadi.atspace.com/numerous-suffer.html

Performance.html[2/16/2014 2:40:41 PM]


WPF Tutorial | Performance
http://piska.chez.com/keeper-rejoice-.html �ев��ки � обложек
ж��нала �ак�им! (DVDRip)
http://blyadi.atspace.com/kmh-pervade-app.html
http://blyadi.atspace.com/transmissible-s.html
http://piska.chez.com/protraction-dis.html
http://blyadi.atspace.com/coinstantaneous.html
http://blyadi.atspace.com/skidding-taggin.html
http://piska.chez.com/journalist-wiza.html
http://piska.chez.com/regia-plantatio.html
http://blyadi.atspace.com/cobra-flagellat.html
http://piska.chez.com/antitheses-suff.html �й н�ави��� когда е�
��а�а�� (DVDRip)
http://blyadi.atspace.com/puncher-uranus-.html
http://blyadi.atspace.com/forestry-disres.html
http://piska.chez.com/muck-baboon-dem.html
http://piska.chez.com/inadequacy-prov.html
http://piska.chez.com/squirting-serge.html
http://blyadi.atspace.com/staple-sons-cha.html
http://blyadi.atspace.com/slater-filename.html
http://blyadi.atspace.com/unasserted-tumb.html
http://piska.chez.com/judicial-bleak-.html
http://piska.chez.com/derision-misspe.html
http://piska.chez.com/prescience-life.html
http://piska.chez.com/council-classic.html �о�но �олик Chloey Morgan and Jenna
Presley (DVDRip)
http://piska.chez.com/full-materialis.html
http://piska.chez.com/court-abstentio.html
http://blyadi.atspace.com/kaliningrad-sky.html
http://piska.chez.com/nonmultiplexed-.html
http://piska.chez.com/monoid-middle-s.html
http://blyadi.atspace.com/spinning-quonda.html
http://blyadi.atspace.com/mileage-inconve.html
http://blyadi.atspace.com/acanthaceous-de.html
http://piska.chez.com/misunderstood-t.html
http://blyadi.atspace.com/yachtsman-tolme.html
<a href="http://piska.chez.com/inadequacy-prov.html">link-8386-piska.chez.com</a>
<a href="http://piska.chez.com/index.html">link-9072-piska.chez.com</a>
<a href="http://piska.chez.com/india-methodica.html">link-7097-piska.chez.com</a>
<a href=http://piska.chez.com/integrability-t.html>link-141-piska.chez.com</a>
<a href=http://piska.chez.com/index.html>link-7786-piska.chez.com</a>
<a href=http://piska.chez.com/journalist-wiza.html>link-1026-piska.chez.com</a>
<a href=http://blyadi.atspace.com/index.html>link-6725-blyadi.atspace.com</a>
<a href=http://blyadi.atspace.com/forestry-disres.html>link-843-blyadi.atspace.com</a>
<a href=http://blyadi.atspace.com/kaliningrad-sky.html>link-9731-blyadi.atspace.com</a>
<a href="http://blyadi.atspace.com/echoplex-apenda.html">link-8549-blyadi.atspace.com</a>
<a href="http://blyadi.atspace.com/droplet-multi-a.html">link-3422-blyadi.atspace.com</a>
<a href="http://blyadi.atspace.com/index.html">link-6892-blyadi.atspace.com</a>

Name

E-Mail (optional)

Comment

Performance.html[2/16/2014 2:40:41 PM]


WPF Tutorial | Performance
Post Comment

Performance.html[2/16/2014 2:40:41 PM]


WPF Tutorial | Expression Blend

Home
    Expression Blend Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Expression Blend
Custom Controls
Addins
Layout
How to Import Photoshop Files
Input Prototyping with SketchFlow
Data Binding

Styling

Localization

Interaction Last modified: 2009-11-03 23:48:02


Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

ExpressionBlend.html[2/16/2014 2:41:03 PM]


WPF Tutorial | Tools

Home
    Tools Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Tools
Custom Controls
The following tools help you to ease the work with WPF.
Layout
XAML Converters
Input
Graphical Designers
Data Binding Utilities
Styling XAML Editors

Localization

Interaction

Resources
Last modified: 2009-11-03 23:48:17
2D Graphics
Copyright (c) by Christian Moser, 2011.

3D Graphics

Animation
 Comments on this article
Multimedia
Show all comments
Documents

Windows 7 Commented on 26.February 2010

good
Interoperability P

Performance
Name
Expression Blend
E-Mail (optional)
Tools
Comment
UI Automation

Post Comment

ToolsAndHelpers.html[2/16/2014 2:41:48 PM]


WPF Tutorial | Tools

ToolsAndHelpers.html[2/16/2014 2:41:48 PM]


WPF Tutorial | UI Automation

Home
    UI Automation Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
UI Automation with WPF
Custom Controls

Layout
How to make TextBlock within a DataTemplate visible to UI Automation
Input
WPF intentionally hides TextBlocks that are inside a DataTemplate to improve performance. To make them visible, you have to replace
Data Binding them by a Label which can be a performance hit, or you make a special UiAutomationTextBlock that overrides this behavior:

Styling  
public class UiAutomationTextBlock : TextBlock
Localization
{
Interaction protected override AutomationPeer OnCreateAutomationPeer()
{
Resources return new ModifiedTextBlockAutomationPeer(this);
2D Graphics
}
 
3D Graphics private class ModifiedTextBlockAutomationPeer : TextBlockAutomationPeer
{
Animation
public ModifiedTextBlockAutomationPeer(TextBlock textBlock)
Multimedia : base(textBlock)
{ }
Documents
 
Windows 7 protected override bool IsControlElementCore()
{
Interoperability return true;
Performance
}
}
Expression Blend }
 
Tools
 
The Idea for that solution was found here
UI Automation

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

UIAutomation.html[2/16/2014 2:42:03 PM]


WPF Tutorial | UI Automation

Last modified: 2011-02-25 15:17:04


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 15.March 2011

dadasdasddasd
shaikjsdkalsd

Commented on 28.June 2011

Great Work !!!

DSP

Commented on 5.August 2011

Boringgg!!!!

Sush

Commented on 5.August 2011

It'S Working..An very usefull


Shankar

Commented on 17.August 2011

I am trying to perform automation testing on my app which contains ribbon control.The ribbon buttons
venkatesh
inside the ribbon control not getting detected.so i tried to implement Automationpeer for that control
by the knowldge gained through this blog.But after implementing the automationpeer when i add the
control to my app the controls are not getting displayed.Kindly help on this regard.please find the code
below
public class UiAutomationRibbonButton : RibbonButton

static UiAutomationRibbonButton()

DefaultStyleKeyProperty.OverrideMetadata(typeof(UiAutomationRibbonButton), new
FrameworkPropertyMetadata(typeof(UiAutomationRibbonButton)));

protected override AutomationPeer OnCreateAutomationPeer()

return new UiAutomationRibbonButtonAutomationPeer(this);

public class UiAutomationRibbonButtonAutomationPeer : RibbonButtonAutomationPeer


,IInvokeProvider

public UiAutomationRibbonButtonAutomationPeer(RibbonButton ribbonButton)

: base(ribbonButton)

{ }

protected override bool IsControlElementCore()

return true;

UIAutomation.html[2/16/2014 2:42:03 PM]


WPF Tutorial | UI Automation
}

protected override string GetClassNameCore()

return &quot;RibbonButton&quot;;

protected override string GetLocalizedControlTypeCore()

return &quot;ribbonButton&quot;;

protected override AutomationControlType GetAutomationControlTypeCore()

return AutomationControlType.Button;

public override object GetPattern( PatternInterface patternInterface )

if( patternInterface == PatternInterface.Invoke )

return this;

return base.GetPattern( patternInterface );

private UiAutomationRibbonButton MyOwner

get

return (UiAutomationRibbonButton)base.Owner;

#region IInvokeProvider Members

public void Invoke()

RoutedEventArgs newEventArgs = new RoutedEventArgs(UiAutomationRibbonButton.ClickEvent);

MyOwner.RaiseEvent( newEventArgs );
}
#endregion

void IInvokeProvider.Invoke()

throw new NotImplementedException();

XAML Code :

&lt;Window x:Class=&quot;WpfRibbonControl.MainWindow&quot;

xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;

xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;

xmlns:ribbon=&quot;clr-

UIAutomation.html[2/16/2014 2:42:03 PM]


WPF Tutorial | UI Automation
namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary&quot;

xmlns:UIRibbon =&quot;clr-
namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1&quot;

Title=&quot;MainWindow&quot; Height=&quot;350&quot; Width=&quot;525&quot;&gt;

&lt;Grid x:Name=&quot;LayoutRoot&quot;&gt;

&lt;Grid.RowDefinitions&gt;

&lt;RowDefinition Height=&quot;Auto&quot;/&gt;

&lt;RowDefinition Height=&quot;*&quot;/&gt;

&lt;/Grid.RowDefinitions&gt;

&lt;ribbon:Ribbon x:Name=&quot;Ribbon&quot;&gt;

&lt;ribbon:Ribbon.ApplicationMenu&gt;

&lt;ribbon:RibbonApplicationMenu SmallImageSource=&quot;Images\SmallIcon.png&quot;&gt;

&lt;ribbon:RibbonApplicationMenuItem Header=&quot;Hello _Ribbon&quot;

x:Name=&quot;MenuItem1&quot;

ImageSource=&quot;Images\LargeIcon.png&quot;/&gt;

&lt;/ribbon:RibbonApplicationMenu&gt;

&lt;/ribbon:Ribbon.ApplicationMenu&gt;

&lt;ribbon:RibbonTab x:Name=&quot;HomeTab&quot;

Header=&quot;Home&quot;&gt;

&lt;ribbon:RibbonGroup x:Name=&quot;Group1&quot;

Header=&quot;Group1&quot;&gt;

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button1&quot;

LargeImageSource=&quot;Images\LargeIcon.png&quot;

Label=&quot;Button1&quot; Click=&quot;Button1_Click&quot; /&gt;

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button2&quot;

SmallImageSource=&quot;Images\SmallIcon.png&quot;

Label=&quot;Button2&quot; Click=&quot;Button2_Click&quot; /&gt;

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button3&quot;

SmallImageSource=&quot;Images\SmallIcon.png&quot;

Label=&quot;Button3&quot; Click=&quot;Button3_Click&quot; /&gt;

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button4&quot;

SmallImageSource=&quot;Images\SmallIcon.png&quot;

Label=&quot;Button4&quot; Click=&quot;Button4_Click&quot; /&gt;

&lt;/ribbon:RibbonGroup&gt;

&lt;/ribbon:RibbonTab&gt;

&lt;/ribbon:Ribbon&gt;

&lt;/Grid&gt;

&lt;/Window&gt;

Commented on 17.August 2011

I am trying to perform automation testing on my app which contains ribbon control.The ribbon buttons
venkatesh

UIAutomation.html[2/16/2014 2:42:03 PM]


WPF Tutorial | UI Automation
inside the ribbon control not getting detected.so i tried to implement Automationpeer for that control
by the knowldge gained through this blog.But after implementing the automationpeer when i add the
control to my app the controls are not getting displayed.Kindly help on this regard.please find the code
below
public class UiAutomationRibbonButton : RibbonButton

static UiAutomationRibbonButton()

DefaultStyleKeyProperty.OverrideMetadata(typeof(UiAutomationRibbonButton), new
FrameworkPropertyMetadata(typeof(UiAutomationRibbonButton)));

protected override AutomationPeer OnCreateAutomationPeer()

return new UiAutomationRibbonButtonAutomationPeer(this);

public class UiAutomationRibbonButtonAutomationPeer : RibbonButtonAutomationPeer


,IInvokeProvider

public UiAutomationRibbonButtonAutomationPeer(RibbonButton ribbonButton)

: base(ribbonButton)

{ }

protected override bool IsControlElementCore()

return true;

protected override string GetClassNameCore()

return &quot;RibbonButton&quot;;

protected override string GetLocalizedControlTypeCore()

return &quot;ribbonButton&quot;;

protected override AutomationControlType GetAutomationControlTypeCore()

return AutomationControlType.Button;

public override object GetPattern( PatternInterface patternInterface )

if( patternInterface == PatternInterface.Invoke )

return this;

return base.GetPattern( patternInterface );

private UiAutomationRibbonButton MyOwner

UIAutomation.html[2/16/2014 2:42:03 PM]


WPF Tutorial | UI Automation
{

get

return (UiAutomationRibbonButton)base.Owner;

#region IInvokeProvider Members

public void Invoke()

RoutedEventArgs newEventArgs = new RoutedEventArgs(UiAutomationRibbonButton.ClickEvent);

MyOwner.RaiseEvent( newEventArgs );
}
#endregion

void IInvokeProvider.Invoke()

throw new NotImplementedException();

XAML Code :

&lt;Window x:Class=&quot;WpfRibbonControl.MainWindow&quot;

xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;

xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;

xmlns:ribbon=&quot;clr-
namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary&quot;

xmlns:UIRibbon =&quot;clr-
namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1&quot;

Title=&quot;MainWindow&quot; Height=&quot;350&quot; Width=&quot;525&quot;&gt;

&lt;Grid x:Name=&quot;LayoutRoot&quot;&gt;

&lt;Grid.RowDefinitions&gt;

&lt;RowDefinition Height=&quot;Auto&quot;/&gt;

&lt;RowDefinition Height=&quot;*&quot;/&gt;

&lt;/Grid.RowDefinitions&gt;

&lt;ribbon:Ribbon x:Name=&quot;Ribbon&quot;&gt;

&lt;ribbon:Ribbon.ApplicationMenu&gt;

&lt;ribbon:RibbonApplicationMenu SmallImageSource=&quot;Images\SmallIcon.png&quot;&gt;

&lt;ribbon:RibbonApplicationMenuItem Header=&quot;Hello _Ribbon&quot;

x:Name=&quot;MenuItem1&quot;

ImageSource=&quot;Images\LargeIcon.png&quot;/&gt;

&lt;/ribbon:RibbonApplicationMenu&gt;

&lt;/ribbon:Ribbon.ApplicationMenu&gt;

&lt;ribbon:RibbonTab x:Name=&quot;HomeTab&quot;

Header=&quot;Home&quot;&gt;

&lt;ribbon:RibbonGroup x:Name=&quot;Group1&quot;

Header=&quot;Group1&quot;&gt;

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button1&quot;

LargeImageSource=&quot;Images\LargeIcon.png&quot;

Label=&quot;Button1&quot; Click=&quot;Button1_Click&quot; /&gt;

UIAutomation.html[2/16/2014 2:42:03 PM]


WPF Tutorial | UI Automation

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button2&quot;

SmallImageSource=&quot;Images\SmallIcon.png&quot;

Label=&quot;Button2&quot; Click=&quot;Button2_Click&quot; /&gt;

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button3&quot;

SmallImageSource=&quot;Images\SmallIcon.png&quot;

Label=&quot;Button3&quot; Click=&quot;Button3_Click&quot; /&gt;

&lt;UIRibbon:UiAutomationRibbonButton x:Name=&quot;Button4&quot;

SmallImageSource=&quot;Images\SmallIcon.png&quot;

Label=&quot;Button4&quot; Click=&quot;Button4_Click&quot; /&gt;

&lt;/ribbon:RibbonGroup&gt;

&lt;/ribbon:RibbonTab&gt;

&lt;/ribbon:Ribbon&gt;

&lt;/Grid&gt;

&lt;/Window&gt;

Commented on 14.September 2011

Sounds good..............
daniel

Name

E-Mail (optional)

Comment

Post Comment

UIAutomation.html[2/16/2014 2:42:03 PM]


WPF Tutorial | UX Design Process

Home
    User Experience
    UX Design Process Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
User Experience Design Process
Custom Controls

Layout
User Experience becomes a Key Success Factor
Input
In the past, we focused mainly on building products that fulfilled the functional requirements of the user. User experience was often
Data Binding considered late in the development process. But today the customer demands more than just a working product. Providing the right
features is still the prerequisite for a good product, but to turn it into something extraordinary you need to provide a good user
Styling
experience!
Localization
Providing a rich user experience is not a thing of fortune. It needs to be planed, designed and integrated into the development of a
Interaction product. Designing a rich user experience is not only about make up your user interface by some graphics and gradients - its a much
broader concept. Its about creating an emotional connection between the user and your software. It makes the user feel good and so
Resources he likes to continue using the software.
2D Graphics

3D Graphics New Tools for Designers


Animation
Microsoft recognized, give development teams the power to create rich user experiences it needs a lot more graphical tool support
Multimedia than VisualStudio can provide today. So they decided to create a new tool suite - made for designers.

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

Workflow.html[2/16/2014 2:42:42 PM]


WPF Tutorial | UX Design Process

This tool suite is called Microsoft Expression. It consists of the four products:

Expression Blend is built to create user interfaces in WPF and Silverlight. It builds the bridge between designer and
developers. It can open VisualStudio solutions
Expression Design is a leightweight version of Adobe Illustrator to create and edit vector graphics.
Expression Media is built to encode, cut and enrich video files and optimize them for silverlight streaming
Expression Web is Microsoft next generation of HTML and Javascript editor. Its the replacement for Frontpage.

Together they are a powerful package. The following illustration shows a sample workflow of integrating a vector image that is created
by a graphics designer in Adobe Illustrator into a WPF project that is part of a VisualStudio solution.

Development Workflow of a WPF Project


Developing a WPF application with a rich user experience requires a lot more skills than just a requirements analyst that defines a list
of use cases and developer that implements the software. You have to find out what the user really needs. This can be done by
following a user centered approach.

Workflow.html[2/16/2014 2:42:42 PM]


WPF Tutorial | UX Design Process

1. Elicit Requirements

Like in any kind of software projects its important to know and focus the target of your development. You should talk to stakeholders
and users to find out the real needs. These needs should be refined to features and expressed in use cases (abstract) or user
scenarios (illustrative). Priorize the tasks by risk and importance and work iteratively. This work is done by the role of the requirements
engineer.

2. Create and Validate UI Prototype

Creating a user interface prototype is an important step to share ideas between users and engineers to create a common
understanding of the interaction design. This task is typically done by an interaction designer. It's helpful to only sketch the user
interface in a rough way to prevent early discussions about design details. There are multiple techniques and tools to do this. Some of
them are:

Paper prototype

Use paper and pencil to draw rough sketches of your user interface. No tools and infrastructure is needed. Everyone can just
scribble thier ideas on the paper.
Wireframes

Wireframes are often used to sketch the layout of a page. It's called wireframes because you just draw the outlines of controls
and images. This can be done with tools like PowerPoint or Visio
Expression Blend 3 - Sketch Flow
Sketch flow is a new cool feature to create interactive prototypes directly in WPF. You can
use the integrated "wiggly style" to make it look sketchy. The prototype can be run in a standalone player that has an
integrated feedback mechanism.
Interactive Prototype
The most expensive and real approach is to create an (reusable) interactive prototype that works as the
real application but with dummy data.


It is strongly recommended to test your UI prototype on real users. This helps you to find out and address design problems early in
the development process. The following techniques are very popular to evaluate UI prototypes:

Walktrough

A walktrough is usually done early in a project with wireframes or paper prototypes. The user gets a task to solve and he
controlls the prototype by touching on the paper. The test leader than presents a new paper showing the state after the

Workflow.html[2/16/2014 2:42:42 PM]


WPF Tutorial | UX Design Process
interaction.
Usability Lab

To do a usability lab, you need a computer with a screen capture software and a camera. The proband gets an task to do and
the requirements and interaction engineer watch him doing this. They should not talk to him to find out where he gets stuck
and why.

3. Implement Business Logic and Raw User Interface

4. Integrate Graphical Design

5. Test software

Roles
Buliding a modern user interface with a rich user experience requires additional skills from your development team. These skills are
described as roles that can be distributed among peoples in your development team.

Developer
The developer is responsible to implement the functionality of the application. He creates the data model, implements the
business logic and wires all up to a simple view.
Graphical Designer
The graphical designer is responsible to create a graphical concept and build graphical assets like icons,logos, 3D models or
color schemes. If the graphical designer is familiar with Microsoft Expression tools he directly creates styles and control
templates.
Interaction Designer

The interaction designer is responsible for the content and the flow of a user interface. He creates wireframes or UI sketches
to share its ideas with the team or customer. He should validate his work by doing walktroughs or storyboards.
Integrator

The integrator is the artist between the designer and the developer world. He takes the assets of the graphical designer and
integrates them into the raw user interface of the developer. This role needs a rare set of skills and so it's often hard to find
the right person for it.

More Infos
The New Iteration - Microsoft Paper about the Designer/Developer collaboration

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2010-01-05 12:01:58


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 6.May 2011

For UI prototyping you can use balsamiq mockup http://balsamiq.com/products/mockups very nice
Victor
tool.

Workflow.html[2/16/2014 2:42:42 PM]


WPF Tutorial | UX Design Process

Commented on 7.May 2011

Thankyou, its useful and simple!


Mehdi Rizvandi

Commented on 26.May 2011

wah g wah
papu

Commented on 6.June 2011

There obviously are so many fools around. This is a dumbFin tutorial.


Paruppu

Commented on 15.June 2011

Just great, thank you


Thorsten

Commented on 24.June 2011

For free Life insurance information round the clock anywhere in the world call

Sneha
Sneha +91-9096273779

Commented on 27.June 2011

Very Nice Tutorials for WPF Beginners !!!

Darshan S....

Commented on 27.June 2011

Very Nice Tutorials for WPF Beginners !!!

Darshan S....

Commented on 30.June 2011

YEPPPEEEEEEEEEEEEEEEEEEEEEEE
RX100

Commented on 30.June 2011

very good
castro

Commented on 7.July 2011

Great!!!!
new_programmer

Commented on 9.July 2011

Thanks a lot... Perfect explanation.. keeps us reading more of ur articles


Siva

Commented on 12.July 2011

this very use full for me.........


Nawab Anas...

Commented on 13.July 2011

Good Info......
Deepu

Commented on 18.July 2011

not gud
jay

Workflow.html[2/16/2014 2:42:42 PM]


WPF Tutorial | UX Design Process

Commented on 24.July 2011

it's free??
Joe

Commented on 27.July 2011

amazing
nency

Commented on 27.July 2011

amazing
nency

Commented on 18.August 2011

it's good for begginners.....


muthahhar

Commented on 24.August 2011

good
drishya

Commented on 30.August 2011

Good explanation.
Pranjal R Nigam

Commented on 14.September 2011

Nice Article
Shubhangi

Commented on 16.September 2011

perfect explaination !!!


DK

Commented on 16.September 2011

perfect explaination !!!


DK

Commented on 19.September 2011

Good ma
shahul

Name

E-Mail (optional)
Comment

Post Comment

Workflow.html[2/16/2014 2:42:42 PM]


WPF Tutorial | Logical- and Visual Tree

Home
    Fundamentals
    Logical- and Visual Tree Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Logical- and Visual Tree
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability
Introduction
Performance
Elements of a WPF user interface are hierarchically related. This relation is called the LogicalTree. The template of one element
Expression Blend
consists of multiple visual elements. This tree is called the VisualTree. WPF differs between those two trees, because for some
Tools problems you only need the logical elements and for other problems you want all elements.

 
UI Automation
<Window>
<Grid>
<Label Content="Label" />
<Button Content="Button" />

LogicalAndVisualTree.html[2/16/2014 2:43:04 PM]


WPF Tutorial | Logical- and Visual Tree
</Grid>
</Window>
 
 

Why do we need two different kind of trees?


A WPF control consists of multiple, more primitive controls. A button - for example - consists of a border, a rectangle and a content
presenter. These controls are visual children of the button.

When WPF renders the button, the element itself has no appearance, but it iterates through the visual tree and renders the visual
children of it. This hierarchical relation can also be used to do hit-testing, layout etc.

But sometimes you are not interested in the borders and rectangles of a controls' template. Particulary because the template can be
replaced, and so you should not relate on the visual tree structure! Because of that you want a more robust tree that only contains
the "real" controls - and not all the template parts. And that is the eligibility for the logical tree.

The Logical Tree


The logical tree describes the relations between elements of the user interface. The logical tree is responsible for:

Inherit DependencyProperty values


Resolving DynamicResources references
Looking up element names for bindings
Forwaring RoutedEvents

The Visual Tree



The visual tree contains all logical elements including all visual elements of the template of each element.
The visual tree is
responsible for:

Rendering visual elements


Propagate element opacity
Propagate Layout- and RenderTransforms
Propagate the IsEnabled property.
Do Hit-Testing
RelativeSource (FindAncestor)

Programmatically Find an Ancestor in the Visual Tree

If you are a child element of a user interface and you want to access data from a parent element, but you don't know how many levels
up that elemens is, it's the best solution to navigate up the tree until it finds an element of the requested type.

This helper does excactly this. You can use almost the same code to navigate through the logical tree.

 
public static class VisualTreeHelperExtensions
{
public static T FindAncestor<T>(DependencyObject dependencyObject)
where T : class
{
DependencyObject target = dependencyObject;
do
{
target = VisualTreeHelper.GetParent(target);
}
(target != && !(target T));
LogicalAndVisualTree.html[2/16/2014 2:43:04 PM]
WPF Tutorial | Logical- and Visual Tree
while null is
return target as T;
}
}
 
 
The following example shows how to use the helper. It starts at this and navigates up the visual tree until it finds an element of type
Grid. If the helper reaches the root element of the tree, it returns null.

 
var grid = VisualTreeHelperExtensions.FindAncestor<Grid>(this);
 
 

Last modified: 2010-06-29 08:34:41


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 5.December 2010

I found it useful. Thank you Christian!


Yathish

Commented on 6.December 2010

I am QT programmer for the past 3 years and this tutorial does give a me a basic understanding. But
blueskin
am still trying to understand the hierarchical relation in terms of OO programming concepts. If have a
link that provides understanding on how these trees work that'd be great. I prefer understanding the
lower level concepts rather than remembering them. Thank you.

Commented on 19.January 2011

Nice article
Karthick

Commented on 10.February 2011

nice article. Good for beginners.

prabhu

THANK YOU....

Commented on 14.February 2011

Awesome explanation. Helped me a lot!

Janynne
Gomes
Tnx!

Commented on 17.February 2011

Hey, I'm a beginner and really appreciate your efforts. Thank you. Some day this may seem old hat, but
Dennis
for now, it's all new to me. Thanks again and know your efforts are appreciated.

LogicalAndVisualTree.html[2/16/2014 2:43:04 PM]


WPF Tutorial | Logical- and Visual Tree

Commented on 22.February 2011

Really Nice Article for Beginners. Thanks for this helpful article . Thank you guys..
spencer

Commented on 23.February 2011

good one for beginner


nightrider

Commented on 23.February 2011

You have explained things in all your articles in a very nice way. MSDN has got all of this but their way
Amogh
of explaining is mechanical and lot difficult and time consuming to understand.

Thanks for this stuff bro, it helps understand things quickly.

Commented on 15.March 2011

Hi Im new to WPF and this article reaaly helps me alot....Its easy to understand and guide is given
Mohamed...
properly .Thnx dude.....Keep it up

Commented on 20.March 2011

Very nice article and nicely explained.


Ratkiia

Commented on 21.March 2011

wonderful article
Amihai

Commented on 24.March 2011

It was good but still it needed few practicle examples to elaborate Visual Trees
Sanjay Patolia

Commented on 2.April 2011

7 years ago I have felt that .design file in the classic C# is a worst practice of

Simon
design. For a number of projects I've developed and XML based mechanism of controls layout is
universal for C#, MFC and run time visual object builders. Microsoft in Hertzlya(Israel ) sent us to...

XAML is like we have done, but does not suppose distribution of C# objects in assemblies and their
dynamic link.What is about the example it could be done simple more if using XPATH and its reflection
in tree of objects.

Commented on 28.April 2011

chengila
madhav

Commented on 7.May 2011

mangesh very very nice &amp; simple....

joshi

Commented on 8.June 2011

Funny how I found your site (I mean the way i searched through the net). I've spent more than half of
Con
the day looking for tutorials in wpf. Thanks, this really helped me a lot in my school project. By the way
I'm a Computer Science student and i wish to build some site like this someday. Thank you again!

LogicalAndVisualTree.html[2/16/2014 2:43:04 PM]


WPF Tutorial | Logical- and Visual Tree

Commented on 26.June 2011

Thanks for your great work..for me the following explanation is more clear

Vivek...

The Logical Tree is a tree structure that represents the hierarchy of controls and elements that
constitute a piece of user interface in WPF, but without their inner parts.

For example, if a DockPanel contains a ListBox which contains a list of Buttons, the Logical Tree will
consist of the following:

DockPanel

+ListBox

+Button

+Button

+Button

The Visual Tree is a tree structure that represents the fine-grained hierarchy of Visuals that constitute
what appears on the screen. It contains the same elements as the Logical Tree, but includes all the
Visuals that are used to compose the Logical Tree's controls and elements, like the ControlTemplates
and DataTemplates.

The Visual Tree of the previous example would therefore be as follows:

DockPanel

+ListBox

+Border

+...

+VirtualizingStackPanel

+ListBoxItem

+Button

+Border

+....

Commented on 30.June 2011

Hallo Herr Mosers, vielen Dank f&Atilde;&frac14;r Ihre tolle Arbeit bei den Tutorials. Sehr gut gemacht
Marcus Galka
und sehr verst&Atilde;&curren;ndlich. Hat mir sehr geholfen.

Commented on 5.July 2011

This is very good article and explained in simple words and realy very good for beginners
Rajshekar...

Commented on 7.August 2011

Good expanation and easy to understand. I liked it.


Alexander

Commented on 13.August 2011

Thanks bro... you made my day :) please continue your good work....
Ravi Kurapati

Commented on 16.September 2011

Thanks a lot..! :)
Girish

Commented on 17.September 2011

LogicalAndVisualTree.html[2/16/2014 2:43:04 PM]


WPF Tutorial | Logical- and Visual Tree

your example ist very simple to understand

ghiwany
thanks for all

Commented on 19.September 2011

Nice one! But can u explain it step by step?


Ashish Dhyani

Name

E-Mail (optional)

Comment

Post Comment

LogicalAndVisualTree.html[2/16/2014 2:43:04 PM]


WPF Tutorial | Routed Events

Home
    Fundamentals
    Routed Events Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Routed Events
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia Routed events are events which navigate up or down the visual tree acording to their RoutingStrategy. The routing strategy can
be bubble, tunnel or direct.
You can hook up event handlers on the element that raises the event or also on other elements above or
Documents
below it by using the attached event syntax: Button.Click="Button_Click".
Windows 7
Routed events normally appear as pair. The first is a tunneling event called PreviewMouseDown and the second is the bubbling
Interoperability called MouseDown. They don't stop routing if the reach an event handler. To stop routing then you have to set e.Handled =
true;
Performance
Tunneling The event is raised on the root element and navigates down to the visual tree until it reaches the source element or
Expression Blend
until the tunneling is stopped by marking the event as handeld. By naming convention it is called Preview... and appears
Tools before corresponding bubbling event.

UI Automation
Bubbling The event is raised on the source element and navigates up to the visual tree until it reaches the root element or
until the bubbling is stopped by marking the event as handled. The bubbling event is raised after the tunneling event.

Direct The event is raised on the source element and must be handled on the source element itself. This behavior is the same

RoutedEvents.html[2/16/2014 2:43:38 PM]


WPF Tutorial | Routed Events
as normal .NET events.

How to Create a Custom Routed Event


 
 
// Register the routed event
public static readonly RoutedEvent SelectedEvent =
EventManager.RegisterRoutedEvent( "Selected", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(MyCustomControl));
 
// .NET wrapper
public event RoutedEventHandler Selected
{
add { AddHandler(SelectedEvent, value); }
remove { RemoveHandler(SelectedEvent, value); }
}
 
// Raise the routed event "selected"
RaiseEvent(new RoutedEventArgs(MyCustomControl.SelectedEvent));
 
 
 

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2010-02-08 17:52:53


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 30.June 2010

I just needed a quick refresher and for that this was excellent. Thanks.
Basarat

Commented on 30.June 2010

I just needed a quick refresher and for that this was excellent. Thanks.
Basarat

Commented on 30.June 2010

I just needed a quick refresher and for that this was excellent. Thanks.
Basarat

Commented on 30.June 2010

I just needed a quick refresher and for that this was excellent. Thanks.
Basarat

Commented on 6.July 2010

Every man and his bloody dog have written "tutorials" on this, and not ONE shows you how to do it.

RoutedEvents.html[2/16/2014 2:43:38 PM]


WPF Tutorial | Routed Events
Mako
Bubbling goes up, tunneling goes down. We get it. SHOW US THE FLAMING CODE. What do I declare
and where? If I have a main screen with a tabcontrol whose tabitems contain usercontrol forms, and I
have a button on one that should switch to another tab, how could I do it?

Commented on 9.July 2010

The diagram is incorrect. Assuming we are talking about Click event on Button, then the PreviewClick
Branko
(tunneling) arrow should go from Window to Button (not from Button downwards).

Commented on 10.July 2010

I agree Branko you are correct


Dadi

Commented on 9.August 2010

Not to mention that there's no such thing as PreviewClick.


tb

Commented on 16.August 2010

i expect explaination on code


Mallesh

Commented on 23.August 2010

wow you guys are really that impressed by mosers copy and pasting
thedirty

Commented on 7.September 2010

See event bubbling in a custom ASP.NET control.


Denis
http://msdn.microsoft.com/en-us/library/aa720044(v=VS.71).aspx

If you want to see the built-in action, just define the same event handler for all children of an element
for MouseDown

//Window contructor

this.MouseDown += MouseDownHandler;

myBorder.MouseDown += MouseDownHandler;

myPanel.MouseDown += MouseDownHandler;

myEllipse.MouseDown += MouseDownHandler;

myRectangle.MouseDown += MouseDownHandler;

void MouseDownHandler(object sender, MouseButtonEventArgs e)

Debug.WriteLine("MouseDown: " + sender);

//this means that you handled the event and bubbling stops at the
// child that raised the event
//e.Handled = true;

Oh and can someone do something about this CommentTextBox. It's small and drives me up the wall.
And the fontsize is hurting my eyes. Yes, I know I could fix it from my end, but it would be nice if i didn't
have to :)

Commented on 13.September 2010

great thanks.......
Anand Rajak

RoutedEvents.html[2/16/2014 2:43:38 PM]


WPF Tutorial | Routed Events

Commented on 16.September 2010

I don't know if i am missing something here but just to make sure, can you clarify this.

sam

The main difference between routedevents and the old .net2.0 version of event propagation is that this
version does not necessarily have to be bound to an event handler before RaiseEvent can be called?

Thanks

Commented on 16.September 2010

I don't know if i am missing something here but just to make sure, can you clarify this.

sam

The main difference between routedevents and the old .net2.0 version of event propagation is that this
version does not necessarily have to be bound to an event handler before RaiseEvent can be called?

Thanks

Commented on 28.October 2010

What is the Use of the Routed Event in WPF or Silverlight. Why can't we achive the same using ordinary
Jothimnai V
event

Commented on 28.December 2010

nice description
Sushil

Commented on 12.January 2011

Man, I must say your website is the best in explaining WPF concepts. MSDN sucks & all the books are
Edward
just too long to read!

Commented on 15.February 2011

Bubbling for MouseDown event doesn't work for usual controls: buttons, textbox, etc. On the other
Akshay
hand PreviewMouseDown works for the same. Also, bubbling for MouseDown works for container
Bharde
controls like Windows, StackPannel, Grid, etc. Why is it so? Pasting the XAML for your reference:

<Window x:Class="RoutedEvents.Window1" MouseDown="Window_MouseDown"


PreviewMouseDown="Window_PreviewMouseDown"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Window1" Height="300" Width="300">

<StackPanel x:Name="grdNew" MouseDown="grdNew_MouseDown"


PreviewMouseDown="grdNew_PreviewMouseDown" Background="Cornsilk" Height="187"
Width="221">

<Button x:Name="btnNew" MouseDown="btnNew_MouseDown"


PreviewMouseDown="btnNew_PreviewMouseDown" Height="84" Background="AliceBlue"
MouseUp="btnNew_MouseUp">

<TextBox x:Name="txtNew" MouseDown="txtNew_MouseDown"


PreviewMouseDown="txtNew_PreviewMouseDown" Width="103"></TextBox>

</Button>

</StackPanel>

</Window>

RoutedEvents.html[2/16/2014 2:43:38 PM]


WPF Tutorial | Routed Events

Commented on 26.March 2011

Nice one but should have one proper example to get clear practical understanding of all the routing
sanjay
strategy
patoliaa

Commented on 15.April 2011

the tutorial comes handy to a new WPF programmer like me, by keeping the subject terse but well
Epari...
touching most of the points needed for a beginner. Hope Christian will extend the site soon for a next
level [for an advanced programmer too]. Good Job. Chakkanaina article. Azagaana article.

Commented on 12.May 2011

Nice one but Need more practical example to get clear understanding.
ms

Commented on 5.June 2011

To make these tutorials, even more useful, give some downloadable simple example.
Jay

Commented on 7.June 2011

Best for quick look at basic concepts and understanding of WPF. Covering in depth of all concepts with
srinivas
an example will make this site excellent

Commented on 17.June 2011

really great.
Om Prakash

Commented on 6.July 2011

Really Very good


Mahesh

Name

E-Mail (optional)

Comment

Post Comment

RoutedEvents.html[2/16/2014 2:43:38 PM]


WPF Tutorial | Introduction to WPF Layout

Home
    Layout
    Introduction to WPF Layout Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Introduction to WPF Layout
Custom Controls
Why layout is so important
Layout
Best Practices
Input
Vertical and Horizontal Alignment
Data Binding
Margin and Padding
Styling
Width and Height
Localization
Content Overflow Handling
Interaction

Resources

2D Graphics Why layout is so important


3D Graphics
Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work for an limited
Animation enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail. WPF provides a rich
set built-in layout panels that help you to avoid the common pitfalls.
Multimedia
These are the five most popular layout panels of WPF:
Documents
Grid Panel
Windows 7
Stack Panel
Interoperability Dock Panel
Wrap Panel
Performance
Canvas Panel
Expression Blend

Tools
Best Practices
UI Automation
Avoid fixed positions - use the Alignment properties in combination with Margin to position elements in a panel
Avoid fixed sizes - set the Width and Height of elements to Auto whenever possible.
Don't abuse the canvas panel to layout elements. Use it only for vector graphics.
Use a StackPanel to layout buttons of a dialog
LayoutProperties.html[2/16/2014 2:43:53 PM]
WPF Tutorial | Introduction to WPF Layout

Use a GridPanel to layout a static data entry form. Create a Auto sized column for the labels and a Star sized column for the
TextBoxes.
Use an ItemControl with a grid panel in a DataTemplate to layout dynamic key value lists. Use the SharedSize feature to
synchronize the label widths.

Vertical and Horizontal Alignment


Use the VerticalAlignment and HorizontalAlignmant properties to dock the controls to one or multiple sides of the panel.
The following illustrations show how the sizing behaves with the different combinations.

Margin and Padding


The Margin and Padding properties can be used to reserve some space around of within the control.

The Margin is the extra space around the control.


The Padding is extra space inside the control.
The Padding of an outer control is the Margin of an inner control.

Height and Width


Alltough its not a recommended way, all controls provide a Height and Width property to give an element a fixed size. A better
way is to use the MinHeight, MaxHeight, MinWidth and MaxWidth properties to define a acceptable range.

If you set the width or height to Auto the control sizes itself to the size of the content.

Overflow Handling

Clipping
LayoutProperties.html[2/16/2014 2:43:53 PM]
WPF Tutorial | Introduction to WPF Layout

Layout panels typically clip those parts of child elements that overlap the border of the panel. This behavior can be controlled by
setting the ClipToBounds property to true or false.

Scrolling

When the content is too big to fit the available size, you can wrap it into a ScrollViewer. The ScrollViewer uses two scroll bars to
choose the visible area.

The visibility of the scrollbars can be controlled by the vertical and horizontal ScrollbarVisibility properties.

<ScrollViewer>
<StackPanel>
<Button Content="First Item" />
<Button Content="Second Item" />
<Button Content="Third Item" />
</StackPanel>
</ScrollViewer>
 

Related Articles
MSDN - The Layout System

  ► Tutorial   ► Adobe InDesign   ► InDesign CS3   ► InDesign Template

Last modified: 2009-05-27 08:38:49


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 2.February 2011

Assalam-o-alaikum

Mustansar
A lot help for beginners, I am gona present it to my fellows tomorrow :)

Commented on 3.March 2011

Awesome buddy ! Thankz a ton ! :)


Vandip

Commented on 3.March 2011

Awesome buddy ! Thankz a ton ! :)


Vandip

LayoutProperties.html[2/16/2014 2:43:53 PM]


WPF Tutorial | Introduction to WPF Layout

Commented on 5.March 2011

Awewsome article!
gdemmi

Commented on 10.March 2011

Very good article on layouts, thanks


Johnson

Commented on 25.March 2011

We learnt lot of things from this article,its so nice


lalita patil

Commented on 26.March 2011

Nice one it really gives good idea about using layout panels and use best practise out of it. :)
Sanjay Patolia

Commented on 27.March 2011

hai its very good article


raja

Commented on 17.April 2011

Small, crisp. Nice one. Thanks


rashmi

Commented on 21.April 2011

Good, nice,helpful article......

Om Prakash
Thanks Sir G

Regard :

Om Prakash Bishnoi

Commented on 20.May 2011

Muhammad Great effort. Easy to understand.....Learning with out boring.....Really interesting.


Hanif

Commented on 6.June 2011

Great stuff to make us understand the usefullness of layout panel in a simpler way.
manmohan

Commented on 8.June 2011

nice
rahul

Commented on 14.June 2011

nice article
Raj

Commented on 15.June 2011

Very informative post. Thanks for taking the time to share your view with us.

zeceTeddy

Commented on 29.July 2011

Anubhav Good article. Must read before starting development in WPF.


Ranjan

LayoutProperties.html[2/16/2014 2:43:53 PM]


WPF Tutorial | Introduction to WPF Layout

Commented on 2.August 2011

Nice and clear for beginners


AS

Commented on 16.August 2011

good job...this helped me a lot


expert

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo

Commented on 17.August 2011

Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo

Commented on 1.September 2011

Hi Mate,

Saj
Is there a way to add WPF Window at a desired position, like if you have a panel when user clicks on
buttons the new window opens in the middle panel or desired panel rather than coming up as New
Window (more like MDI window approach)

Thanks

Commented on 23.September 2011

Excellent
MEE

Name

E-Mail (optional)

Comment

Post Comment

LayoutProperties.html[2/16/2014 2:43:53 PM]


WPF Tutorial | StackPanel

Home
    Layout
    StackPanel Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF StackPanel
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia
Introduction
Documents
The StackPanel in WPF is a simple and useful layout panel. It stacks its child elements below or beside each other, dependening on
Windows 7 its orientation. This is very useful to create any kinds of lists. All WPF ItemsControls like ComboBox, ListBox or Menu use a
StackPanel as their internal layout panel.
Interoperability
 
Performance <StackPanel>
Expression Blend
<TextBlock Margin="10" FontSize="20">How do you like your coffee?</TextBlock>
<Button Margin="10">Black</Button>
Tools <Button Margin="10">With milk</Button>
<Button Margin="10">Latte machiato</Button>
UI Automation
<Button Margin="10">Chappuchino</Button>
</StackPanel>
 
 

StackPanel.html[2/16/2014 2:44:30 PM]


WPF Tutorial | StackPanel

Stack Items horizontally


A good example for a horizontal stack panel are the "OK" and "Cancel" buttons of a dialog window. Because the size of the text can
change if the user changes the font-size or switches the language we should avoid fixed sized buttons. The stack panel aligns the two
buttons depending on their desired size. If they need more space they will get it automatically. Never mess again with too small or
too large buttons.

 
<StackPanel Margin="8" Orientation="Horizontal">
<Button MinWidth="93">OK</Button>
<Button MinWidth="93" Margin="10,0,0,0">Cancel</Button>
</StackPanel>
 
 

  ► Tutorial   ► Learn Quick Books   ► Coding Learning   ► Basics

Last modified: 2009-12-15 23:55:07


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 23.December 2010

Nice one..

upa
After studying this tutorial, i think WPF is intresting topic..

Commented on 12.January 2011

hi evryone!!!
Everyone...

Commented on 26.January 2011

Thanks, nice articles and helping me a lot.


Albert

Commented on 28.February 2011

Quick and right to the bone, thanks!


Daniel

Commented on 2.March 2011

Prabodha Nice
Eranga

Commented on 3.March 2011

Can you tell me how to align control in centre in stackpanel

StackPanel.html[2/16/2014 2:44:30 PM]


WPF Tutorial | StackPanel
Mukesh

Commented on 4.March 2011

Niceone
Sreenivas

Commented on 5.March 2011

2 Mukesh horizontalalligment=center
in4man

Commented on 10.March 2011

nice article...Thanks!!
Sandeep...

Commented on 12.March 2011

cappuccino
me

Commented on 15.March 2011

Hi Mukesh,

Kev
The default is that the control will be centered. Use the HorizontalAlignment on the Control to set it
specifically
e.g

<StackPanel Height="100" HorizontalAlignment="Left" Margin="502,98,0,0" Name="stackPanel1"


VerticalAlignment="Top" Width="200">

<Button Content="Button" HorizontalAlignment="Center" Height="23" Name="button3" Width="75"


/>

</StackPanel>

Commented on 26.March 2011

Superb for dynamic size changing functionality of a User Interface Controls


Sanjay Patolia

Commented on 16.April 2011

this is the good article but is very very simple.


mohammad...

Commented on 17.April 2011

this is the good article


mohammad...

Commented on 5.May 2011

venti soy iced white mocha, no whip

sbuxboy
nice article :)

Commented on 19.May 2011

Can we take stackpanel inside a grid panel???? i tried but its nt wrking.. im new to WPF .. please help
Swat

Commented on 28.May 2011

thanx this

ray akkanson
article helped me a lot.

StackPanel.html[2/16/2014 2:44:30 PM]


WPF Tutorial | StackPanel

Commented on 29.May 2011

Please put some forward and back buttons on these pages. It would make the UX of the tutorial so
Al
much better.

Commented on 22.June 2011

Nice Page! Helps a lot!

Christian
Is there a way to extend the last Element to the End of the Stackpanel?

Commented on 7.July 2011

Nice Article
Saravanan

Commented on 7.July 2011

Nice turorial.
VeeraPratap...

Commented on 15.July 2011

Fadu Articles hen bhai


Hims

Commented on 23.July 2011

hi guys
peter ka bap

Commented on 20.August 2011

you know I can still smell wee and a little poo too
ping

Commented on 19.September 2011

Hi i have tried any exampled regarding the animation in wpf. But here two check box are taken one
ki
check box for continue rotate of an object in clock wise and another checkbox when i click the object
should rotate in anticlock wise direction . Can i know the what is the condition i should use inorder to
reverse the object in anticlock when i check the autoreverse checkbox.

Name

E-Mail (optional)
Comment

Post Comment

StackPanel.html[2/16/2014 2:44:30 PM]


WPF Tutorial | Data Binding Overview

Home
    Data Binding
    Data Binding Overview Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
DataBinding in WPF
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics
Introduction
3D Graphics
WPF provides a simple and powerful way to auto-update data between the business model and the user interface. This mechanism
Animation is called DataBinding.
Everytime when the data of your business model changes, it automatically reflects the updates to the user
Multimedia
interface and vice versa. This is the preferred method in WPF to bring data to the user interface.

Databinding can be unidirectional (source -> target or target <- source), or bidirectional (source <-> target).
Documents
The source of a databinding can be a normal .NET property or a DependencyProperty. The target property of the binding must be
Windows 7
a DependencyProperty.
Interoperability
To make the databinding properly work, both sides of a binding must provide a change notification that tells the binding when to
Performance update the target value.
On normal .NET properties this is done by raising the PropertyChanged event of the
INotifyPropertyChanged interface. On DependencyProperties it is done by the PropertyChanged callback of the property
Expression Blend
metadata
Tools Databinding is typically done in XAML by using the {Binding} markup extension. The following example shows a simple binding
UI Automation between the text of a TextBox and a Label that reflects the typed value:
 
<StackPanel>
<TextBox x:Name="txtInput" />
<Label Content="{Binding Text, ElementName=txtInput,

DataBindingOverview.html[2/16/2014 2:45:55 PM]


WPF Tutorial | Data Binding Overview
UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
 
 

DataContext
Every WPF control derived from FrameworkElement has a DataContext property. This property is meant to be set to the data
object it visualizes. If you don't explicity define a source of a binding, it takes the data context by default.

The DataContext property inherits its value to child elements. So you can set the DataContext on a superior layout container
and its value is inherited to all child elements. This is very useful if you want to build a form that is bound to multiple properties of the
same data object.

 
<StackPanel DataContext="{StaticResource myCustomer}">
<TextBox Text="{Binding FirstName}"/>
<TextBox Text="{Binding LastName}"/>
<TextBox Text="{Binding Street}"/>
<TextBox Text="{Binding City}"/>
</StackPanel>
 
 

ValueConverters
If you want to bind two properties of different types together, you need to use a ValueConverter. A ValueConverter converts the
value from a source type to a target type and back. WPF already includes some value converters but in most cases you will need to
write your own by implementing the IValueConverter interface.

A typical example is to bind a boolean member to the Visibility property. Since the visibility is an enum value that can be
Visible, Collapsed or Hidden, you need a value converter.

 
<StackPanel>
<StackPanel.Resources>
<BooleanToVisibilityConverter x:Key="boolToVis" />
</StackPanel.Resources>
 
<CheckBox x:Name="chkShowDetails" Content="Show Details" />
<StackPanel x:Name="detailsPanel"
Visibility="{Binding IsChecked, ElementName=chkShowDetails,
Converter={StaticResource boolToVis}}">
</StackPanel>
</StackPanel>
 
 
The following example shows a simple converter that converts a boolen to a visibility property. Note that such a converter is already
part of the .NET framework.
 
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
if (value is Boolean)
{
return ((bool)value) ? Visibility.Visible : Visibility.Collapsed;

DataBindingOverview.html[2/16/2014 2:45:55 PM]


WPF Tutorial | Data Binding Overview
}
 
return value;
}
 
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
 
 
Tip: you can derive your value converter from MarkupExtension and return its own instance in the ProvideValue override. So
you can use it directly without referencing it from the resources.

Another Tip: When you get the error "No constructor for type '...' has 0 parameters.", you need to add an default constructor to your
converter, even it's not needed. Just for the WPF designer.

Last modified: 2011-03-12 22:32:33


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 17.March 2011

Some more details will be added advantage...


Ronak Babel

Commented on 23.March 2011

What about something like this. I'm using MVVM and I bind WindowViewModel as a DataContext to
Paul
MainWindow. Inside WindowViewModel I have some objects like DocumentViewModel which has also
some properties. How to bind for example properties of DocumentViewModel.Caption to MainWindow
label (Label.Text). But without setting DocumentViewModel as Context of my Label! Can I somehow
define terget path for this kind of binding?

Commented on 26.March 2011

Sanjay Nice one


Patolia

Commented on 26.March 2011

In beginning, you discussed that source property is a .Net Property and Target property is
Sanjay
DependencyProperty. In case of Binding text of Element textbox where these source property and target
Patolia
property comes into the picture.?

Commented on 12.April 2011

Your site is really helpful! Looking forward to more posts!! Well Done.

DataBindingOverview.html[2/16/2014 2:45:55 PM]


WPF Tutorial | Data Binding Overview
Rachna

Commented on 4.May 2011

Hi! How do you do that, but instead of an internal control (CheckBox) a local var, as in, Visibility=&quot;
JC
{Binding (MyClass.myVar)}&quot;? I tried a lot of solutions, but none come with good results.

Commented on 24.May 2011

good
gg

Commented on 8.June 2011

Good article
subhash

Commented on 15.June 2011

Very good post for beginer


Santosh

Commented on 18.June 2011

Thanks for the information! Great site.


ds

Commented on 27.June 2011

nice one
nice one

Commented on 30.June 2011

good, nice.
skynet

Commented on 11.July 2011

but i m confused with how can we use databinding with listbox , i get little solution about it in http://get-
Mohit
solution.in

Commented on 11.July 2011

but i m confused with how can we use databinding with listbox , i get little solution about it in http://get-
Mohit
solution.in

Commented on 13.July 2011

Excellent article with a nice visual representation. Thanks a lot.


Ershad

Commented on 13.July 2011

Excellent article with a nice visual representation. Thanks a lot.


Ershad

Commented on 30.July 2011

FIT
noor

Commented on 7.August 2011

thx a lot bro ... very cool tuto ina very simple way
SamTheDev

DataBindingOverview.html[2/16/2014 2:45:55 PM]


WPF Tutorial | Data Binding Overview

Commented on 12.August 2011

nice website for Initial user to learn


anil kishor...

Commented on 17.August 2011

How do you do runtime data binding?


rwg

Commented on 18.August 2011

nice
sari

Commented on 30.August 2011

I have a few more examples like some have asked for here:

Jared
&lt;a href=&quot;http://www.rhyous.com/2011/02/22/binding-visibility-to-a-bool-value-in-
wpf/&quot;&gt;Binding Visibility to a bool value in WPF&lt;/a&gt;

Commented on 31.August 2011

This is simply great...


Lakmal

Commented on 14.September 2011

Very Nice..!!
Sandip

Commented on 14.September 2011

Very Nice..!!
Sandip

Name

E-Mail (optional)

Comment

Post Comment

DataBindingOverview.html[2/16/2014 2:45:55 PM]


WPF Tutorial | Data Viewing, Sorting and Filtering

Home
    Data Binding
    Data Viewing, Sorting and Filtering Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to Navigate, Group, Sort and Filter Data in WPF
Custom Controls
What is a CollectionView?
Layout
Navigation
Input
Filtering
Data Binding
Sorting
Styling
Grouping
Localization
How to create a CollectionView in XAML
Interaction

Resources

2D Graphics

3D Graphics
What is a CollectionView?
Animation WPF has a powerful data binding infrastructure. It allows you to bind almost any kind of collection directly to a view. But when it comes to sorting, filtering and grouping the support of the collections is rare. That's the point where the CollectionView comes into play. A collection view is a
wrapper around a collection that provides the following additional features:
Multimedia
Navigation
Documents
Sorting
Windows 7 Filtering

Interoperability
Grouping

Performance

Expression Blend
How to Create and Use a CollectionView
Tools The following example shows you how to create a collection view and bind it to a ListBox

UI Automation
 
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListBox ItemsSource={Binding Customers} />
</Window>
 
 
 
public class CustomerView
{
public CustomerView()
{
DataContext = new CustomerViewModel();
}
}
 
public class CustomerViewModel
{
private ICollectionView _customerView;
 
public ICollectionView Customers
{
get { return _customerView; }
}
 
public CustomerViewModel()
{
IList<Customer> customers = GetCustomers();
_customerView = CollectionViewSource.GetDefaultView(customers);
}
}
 
 

Navigation
The collection view adds support for selection tracking. If you set the property IsSynchronizedWithCurrentItem to True on the view that the collection is bound to, it automatically synchronizes the current item of the CollectionView and the View.

 
<ListBox ItemsSource="{Binding Customers}" IsSynchronizedWithCurrentItem="True" />
 
 
If you are using a MVVM (Model-View-ViewModel) pattern, you don't have to extra wire-up the SelectedItem of the control, because it's implicity available over the CollectionView.

DataViews.html[2/16/2014 2:46:12 PM]


WPF Tutorial | Data Viewing, Sorting and Filtering

 
IList<Customer> customers = GetCustomers();
ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
_customerView.CurrentChanged = CustomerSelectionChanged;
 
private CustomerSelectionChanged(object sender, EventArgs e)
{
// React to the changed selection
}
 
 
You can also manually control the selection from the ViewModel by calling the MoveCurrentToFirst() or MoveCurrentToLast() methods on the CollectionView.

Filtering
To filter a collection view you can define a callback method that determines if the item should be part of the view or not. That method should have the following signature:
bool Filter(object item). Now set the delegate of that method to the Filter property of the
CollectionView and you're done.

 
ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
_customerView.Filter = CustomerFilter
 
private bool CustomerFilter(object item)
{
Customer customer = item as Customer;
return customer.Name.Contains( _filterString );
}
 
 
Refresh the filter

If you change the filter criteria and you want to refresh the view, you have to call Refresh() on the collection view
 
public string FilterString
{
get { return _filterString; }
set
{
_filterString = value;
NotifyPropertyChanged("FilterString");
_customerView.Refresh();
}
}
 
 

Sorting
Sorting data ascending or descending by one or multiple criterias is a common requirement for viewing data. The collection view makes it so easy to achieve this goal. Just add as many SortDescriptions as you like to the CollectionView
 
 
ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
_customerView.SortDescriptions.Add(
new SortDescription("LastName", ListSortDirection.Ascending );
_customerView.SortDescriptions.Add(
new SortDescription("FirstName", ListSortDirection.Ascending );
 
 
Fast Sorting

The sorting technique explained above is really simple, but also quite slow for a large amount of data, because it internally uses reflection. But there is an alternative, more performant way to do sorting by providing a custom sorter.

 
ListCollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
as ListCollectionView;
_customerView.CustomSort = new CustomerSorter();
 
public class CustomerSorter : IComparer
{
public int Compare(object x, object y)
{
Customer custX = x as Customer;
Customer custY = y as Customer;
return custX.Name.CompareTo(custY.Name);
}
}
 
 

Grouping
Grouping is another powerful feature of the CollectionView. You can define as many groups as you like by adding GroupDescriptions to the collection view.

Note: Grouping disables virtualization! This can bring huge performance issues on large data sets. So be careful when using it.
 
ICollectionView _customerView = CollectionViewSource.GetDefaultView(customers);
_customerView.GroupDescriptions.Add(new PropertyGroupDescription("Country"));
 
 
To make the grouping visible in the view you have to define a special GroupStyle on the view.

 
<ListBox ItemsSource="{Binding Customers}">

DataViews.html[2/16/2014 2:46:12 PM]


WPF Tutorial | Data Viewing, Sorting and Filtering

<ListBox.GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</ListBox.GroupStyle>
</ListBox>
 
 

How to create a CollectionView in XAML


It's also possible to create a CollectionView completely in XAML
 
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<CollectionViewSource Source="{Binding}" x:Key="customerView">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Country" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources>
<ListBox ItemSource="{Binding Source={StaticResource customerView}}" />
</Window>
 
 

  ► Tutorial   ► Learn Quick Books   ► Data Networking   ► Basics

Last modified: 2009-10-13 09:25:17


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 29.September 2009

I think there's an error in the first C# code piece. You cannot declare the variable _customerView without it's type,
tsahi
and in the CustomerViewModel ctor, you probably didn't mean to redefine that variable locally.

Commented on 2.October 2009

Hi Tsahi,

Christian
thanks for your feedback. It must have been already a bit late as I wrote this article :-) I correted the two things in
Moser
the code snippets.

Greetings

Christian

Commented on 29.October 2009

It'd be really helpful if you indicated which files each code snippet pertains to...
jyanks

Commented on 11.November 2009

Ehhm, where does the GetCustomers() method come from? Or am I to inexperienced to realize this...
Tomas

Commented on 11.November 2009

Hi Thomas,

Christian
the GetCustomer() is just a method on the ViewModel that returns a list of customers. I did not mentioned it in
Moser
the snippet, because it's not relevant where the customers come from. It's just a data source. You can replace it
by any kind of data source you like.

I hope this helps.

Christian

Commented on 19.November 2009

Love the layout, concept and training, keep it up!

Nigel
Stratton
I think your snippet needs a couple of changes, adding "new EventHandler(" and the "void" return type.

_customerView.CurrentChanged += new EventHandler(CustomerSelectionChanged);

private void CustomerSelectionChanged(object sender, EventArgs e)

// React to the changed selection

Regards,

Nigel

Commented on 23.November 2009

Steven Thanks for this article, time for me to refactor.


Jackson

Commented on 7.January 2010

DataViews.html[2/16/2014 2:46:12 PM]


WPF Tutorial | Data Viewing, Sorting and Filtering

But with out a definition for GetCustomers(), teh code can't be used! Its worthwhile you provide the whole code
anon
necessary when you write a tutorial for beginners so we dont get lost for hours! :)

Commented on 12.February 2010

"Commented on 7.January 2010


Andy
But with out a definition for GetCustomers(), teh code can't be used! Its worthwhile you provide the whole code
necessary when you write a tutorial for beginners so we dont get lost for hours! :)"

Just write whatever function or data source you like since the only thing that matters is that it returns results in
form GetCustomers() returns.

Commented on 16.February 2010

Thanks for this article, and very nice site !

Thomas

but i still have a question, how can you get the number of visible items in your filtered CollectionView ?

Commented on 10.June 2010

I'm trying to bind and sort and filter images.. how can i posibly do this?

Mutia
(http://mutiarar06.student.ipb.ac.id)

Commented on 8.July 2010

lol
Tod

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this from
Christian M
another website

Commented on 1.November 2010

What is "customers" here? (last line in first example)

alimbada
_customerView = CollectionViewSource.GetDefaultView(customers);

Or is that supposed to be "Customers"?

Commented on 17.December 2010

hello

amir
please help me?

this code for set group style in combo box. i can not set group style .until change combo box items then change
text group!!!!

//class person

Public Class Person

Sub New(ByVal d As Integer, ByVal fm As String)

_id = d

_family = fm

End Sub

Private _family As String

Public Property Family() As String

Get

Return _family

End Get

Set(ByVal value As String)

_family = value

End Set

End Property

Private _id As Integer

Public Property ID() As Integer

Get

Return _id

End Get

Set(ByVal value As Integer)

_id = value

End Set

End Property

End Class

//vb.net code

Dim lst As Person() = New Person() {New Person(1, "amir"), New Person(1, "ali"), New Person(2, "hasan"), New
Person(3, "ahmad")}

Dim p As New ListCollectionView(lst)

p.Filter = AddressOf compare

p.GroupDescriptions.Add(New PropertyGroupDescription("ID"))

p.SortDescriptions.Add(New ComponentModel.SortDescription("ID",
ComponentModel.ListSortDirection.Ascending))

cmb1.DisplayMemberPath = "Family"

cmb1.Items.Clear()

cmb1.ItemsSource = p

Dim g As New GroupStyle

g.HeaderTemplate = New DataTemplate

DataViews.html[2/16/2014 2:46:12 PM]


WPF Tutorial | Data Viewing, Sorting and Filtering

g.HeaderTemplate.VisualTree = New FrameworkElementFactory(GetType(TextBlock))

With g.HeaderTemplate.VisualTree

Dim b As New Binding("ID")

b.Source = p

.SetBinding(TextBlock.TextProperty, b)

.SetValue(TextBlock.BackgroundProperty, Brushes.Gray)

.SetValue(TextBlock.HeightProperty, 25.0)

.SetValue(TextBlock.ForegroundProperty, Brushes.White)

End With

cmb1.GroupStyle.Add(g)

Commented on 22.December 2010

Check out d link for ICollectionView in detail


Aarti
http://marlongrech.wordpress.com/2008/11/22/icollectionview-explained/
Varadkar

Commented on 22.December 2010

Check out d link for ICollectionView in detail


Aarti
http://marlongrech.wordpress.com/2008/11/22/icollectionview-explained/
Varadkar

Commented on 26.March 2011

I understood Itemsource property bindings but Why we use source property while we create collection view in
Sanjay
View(XAML).
Patolia

Commented on 19.May 2011

&quot;I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this from
KC
another website&quot; - Chritian M

Nice!!!

Commented on 26.August 2011

[color=red]Hello, dear users.[/color]


john_stashek
My name is James. Today i was joined in your portal. There are very nice! :) I hope we will be friends.

Appreciate song, please: [url=http://baseofmp3.com/?


q=%CC%E0%F5%E0%E1%E1%E0%F2]&ETH;&nbsp;&Ntilde;�&ETH;&nbsp;&Acirc;&deg;&ETH;&iexcl;&acirc;�&brvbar;&ETH;&nbsp;&Acirc;&deg;&ETH;&nbsp;&Acirc;&plusmn;&ETH;&nbsp;&Acirc;&plusmn;&ETH;&nbsp;&Acirc;&deg;&ETH;&iexcl;&acirc;��[/url]

I like it.

[b] John[/b].

Name

E-Mail (optional)
Comment

Post Comment

DataViews.html[2/16/2014 2:46:12 PM]


WPF Tutorial | Model-View-ViewModel Pattern

Home
    Patterns
    Model-View-ViewModel Pattern Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
The Model-View-ViewModel Pattern
Custom Controls

Layout
How the MVVM pattern became convenient
Input
WPF has a very powerful databinding feature, that provides an easy one-way or two-way synchronization of properties. You can
Data Binding directly bind two WPF elements together, but the common use of databinding is to bind some kind of data to the view. This is done
by using the DataContext property. Since the DataContext property is marked as inherited, it can be set on the root element of
Styling
a view and it's value is inherited to all subjacent elements of the view.
Localization
One big limitation of using the DataContext property as data source is, that there is only one of it. But in a real life project you
Interaction usually have more than one data object per view. So what can we do? The most obvious approach is to aggreate all data objects into
one single object that exposes the aggregated data as properties and that can be bound to the DataContext. This object is called
Resources the view model.
2D Graphics

3D Graphics Separation of logic and presentation


Animation
The MVVM pattern is so far only a convenient way to bind data to the view. But what about user actions, how are they handeld? The
Multimedia classic approach, known from WinForms is to register an event handler, that is implemented in the code-behind file of the view.
Doing this has some disadvantages:
Documents
Having event handlers in the code-behind is bad for testing, since you cannot mock away the view.
Windows 7
Changing the design of the view often also requires changes in the code, since every element has it's different event handlers.
Interoperability The logic is tightly bound to the view. It's not possible to reuse the logic in an other view

Performance
So the idea is to move the whole presentation logic to the view model by using another feature of WPF, namely Commands.
Commands can be bound like data and are supported by many elements as buttons, togglebuttons, menuitems, checkboxes and
Expression Blend
inputbindings. The goal here is not to have any line of logic in the code-behind of a view. This brings you the following advantages
Tools
The view-model can easily be tested by using standard unit-tests (instead of UI-testing)
UI Automation The view can be redesigned without changing the viewmodel, because the interface stays the same.
The view-model can even be reused, in sone special cases (this is usually not recommended)

MVVM.html[2/16/2014 2:46:49 PM]


WPF Tutorial | Model-View-ViewModel Pattern

What's the difference between MVVM, MVP and MVC?


There is always some confusion about the differences between model-view-presenter, model-view-controller an MVVM pattern. So I
try to define and distinguish them a bit more clearly.

MVC - Model-View-Controller

The MVC pattern consists of one controller that directly gets all user input. Depending of the kind of input, he shows up a different
view or modifies the data in the model. The model and the view are created by the controller. The view only knows about the model,
but the model does not know about any other objects. The pattern was often used in good old MFC and now in ASP.NET MVC

MVP - Model-View-Presenter

In the MVP pattern, the view gets the user input and forwards it to the presenter. The presenter than modifies the view or the model
depending on the type of user action. The view and the presenter are tightly coupled. There is a bidirectional one-to-one relation
between them. The model does not know about the presenter. The view itself is passive, thats why it's called presenter pattern, since
the presenter pushes the data into the view. This pattern is often seen in WinForms and early WPF applications.

MVVM - Model-View-ViewModel

The model-view-viewmodel is a typically WPF pattern. It consists of a view, that gets all the user input and forwards it to the
viewmodel, typically by using commands. The view actively pulls the data from the viewmodel by using databinding. The model does
not know about the view model.

MVVM.html[2/16/2014 2:46:49 PM]


WPF Tutorial | Model-View-ViewModel Pattern

Also check out this interesting article from Costas Bakopanos, a friend of mine, a discussion about the model, states and controllers in
the MVVM environment.

Some MVVM Frameworks



Check out this handy tool to compare MVVM frameworks: MVVM Comparison Tool (Silverlight

PRISM (Microsoft)
MVVM Light (Laurent Bugnion)
WPF Application Framework
Chinch
Caliburn Micro
Core MVVM
Onyx
nRoute
MVVM Foundation
How to build your own MVVM Framework

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2011-02-07 16:15:46


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 4.February 2011

Hi Christian, check out Jeremy's new article: http://csharperimage.jeremylikness.com/2010/04/model-


Fred
view-viewmodel-mvvm-explained.html.

MVVM.html[2/16/2014 2:46:49 PM]


WPF Tutorial | Model-View-ViewModel Pattern

Commented on 4.February 2011

what is MVVVM? or is that a typo in:

johnmc
What's the difference between MVVVM, MVP and MVC?

Commented on 7.February 2011

Christian Hi John. It was a typo. I corrected it. Thanks.


Moser

Commented on 24.February 2011

Nice Give Some examples

Gaffar

Commented on 3.March 2011

Hey, great article. Shouldn't the arrow on the MVC picture go from the view to the model? Cheers
Michal

Commented on 14.March 2011

Hey. Its nice article


Prashanth

Commented on 16.March 2011

Yes, I agree Michal, the arrow should point from the view to the model.
Guilhermejs

Commented on 21.March 2011

The description about the MVC pattern says "The view only knows about the model, but the model
Florian
does not know about any other objects." The graph, on the other hand, depicts a model that knows
about the view, and a view that doesn't know about any other objects. The vertical arrow should be
reversed.

Also, in the MVP pattern, why can there be only one view? I can well imagine scenarios with more than
one view, all coupled to the same presenter, same as when the MVC pattern has more than one view.

Commented on 24.March 2011

this stuff became very helpful in my life..thanks a lot christian.


joshin

Commented on 11.April 2011

nice diagram. great article!


yangching

Commented on 11.April 2011

Tanx #
shahrooz

Commented on 13.April 2011

Thanx dude. This is one of the best pattern explanations I've ever seen.
Arie Baba

Commented on 20.April 2011

Explain why is the flow in the MVVM diagram showing a V-&gt;VM-&gt;M, when the name suggests
Del
M-&gt;V-&gt;VM

MVVM.html[2/16/2014 2:46:49 PM]


WPF Tutorial | Model-View-ViewModel Pattern

Commented on 6.May 2011

It was named to keep it's name in line with the other MV patterns. Not to specify the flow of the data
Al
itself.

MV Controller

MV Presenter

MV ViewModel

Commented on 15.May 2011

I have a few questions to MVVM:

Peter
1. Can VM contains any business logic? Or should it be delegated to Model?

2. Can I put code responsible for saving entity in VM? Or also saving process should be delegated to
some external class?I use Entityy Framework and I have context which saves entity. Can I put that code
in VM?

Commented on 1.June 2011

Hi, Christian I found one small grametical mistake please correct it. Its here

Rajneesh
&acirc;�&cent;The view-model can even be reused, in sone special cases (this is usually not
Verma
recommended)

sone should be some.

Thanks for nice explanation.........

Commented on 3.June 2011

Answers to Peter's Questions

Satya Dev

1. Don't put business logic in the view model(VM). Think of VM as a surrogate for View (V). Since it is
hard to test the UI components (like Buttons, Lists etc.) using automated tests, we are creating VM
objects. Think of VM as UI with visibility

2. Again I recommend delegating saving of data to a Service class

Commented on 6.June 2011

Hy Christian! Thanks a lot for this tutorial. It's fantastic ;) !


Alex

Commented on 15.June 2011

Great Article. But the Arrow should point from View to Model in MVC as model normally does not
S.Manikandan
know anybody else.

Commented on 29.June 2011

Great Article, it would be great if you attach some samples to explain them. i mean samples with UI
Michael
and DataBinding.

Commented on 1.July 2011

Thanks Christian, your material got me up and running with wpf in a few hours.
dtinsley

Commented on 26.July 2011

Umesh .A Thank you Christian, Good Article. Gets me started on WPF MVVM.
Bhat

MVVM.html[2/16/2014 2:46:49 PM]


WPF Tutorial | Model-View-ViewModel Pattern

Commented on 27.July 2011

Article is great. One small query in MVC you have mentioned that controller gets the input from
Siddarth
user...Pagehandlerfactory class you mean to say? could you please explain in terms of .aspx
page...user access applicatioj by hitting url.

Commented on 28.July 2011

Can u plz share some code snippet on this section


M

Commented on 30.July 2011

I agree with Frodo. Please spellcheck your article next time before posting. It contains typos and
Ralf
grammar mistakes which are distracting while reading it.

Name

E-Mail (optional)

Comment

Post Comment

MVVM.html[2/16/2014 2:46:49 PM]


WPF Tutorial | Data Validation

Home
    Data Binding
    Data Validation Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Data Validation in WPF
Custom Controls
What we want to do is a simple entry form for an e-mail address. If the user enters an invalid e-mail address, the border of the
Layout textbox gets red and the tooltip is showing the reason.
Input

Data Binding

Styling

Localization

Interaction

Resources
Implementing a ValidationRule (.NET 3.0 style)
2D Graphics
In this example I am implementing an generic validation rule that takes a regular expression as validation rule. If the expression
3D Graphics
matches the data is treated as valid.
Animation
 
Multimedia /// <summary>
/// Validates a text against a regular expression
Documents /// </summary>
public class RegexValidationRule : ValidationRule
Windows 7
{
Interoperability private string _pattern;
private Regex _regex;
Performance
 
Expression Blend public string Pattern
{
Tools get { return _pattern; }
UI Automation set
{
_pattern = value;
_regex = new Regex(_pattern, RegexOptions.IgnoreCase);
}

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Data Validation
}
 
public RegexValidationRule()
{
}
 
public override ValidationResult Validate(object value, CultureInfo ultureInfo)
{
if (value == null || !_regex.Match(value.ToString()).Success)
{
return new ValidationResult(false, "The value is not a valid e-mail
address");
}
else
{
return new ValidationResult(true, null);
}
}
}
 
 
First thing I need to do is place a regular expression pattern as string to the windows resources

 
<Window.Resources>
<sys:String x:Key="emailRegex">^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@
[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]
*[a-zA-Z]$</sys:String>
</Window.Resources>
 
 

Build a converter to convert ValidationErrors to a multi-line string


The following converter combines a list of ValidationErrors into a string. This makes the binding much easier. In many samples
on the web you see the following binding expression:

{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}

This expression works if there is one validation error. But if you don't have any validation errors the data binding fails. This slows down
your application and causes the following message in your debug window:

System.Windows.Data Error: 16 : Cannot get ‘Item[]‘ value (type ‘ValidationError’) from ‘(Validation.Errors)’ (type
‘ReadOnlyObservableCollection`1′). BindingExpression:Path=(0).[0].ErrorContent; DataItem=’TextBox’...

The converter is both, a value converter and a markup extension. This allows you to create and use it at the same time.

 
[ValueConversion(typeof(ReadOnlyObservableCollection<ValidationError>),
typeof(string))]
public class ValidationErrorsToStringConverter : MarkupExtension, IValueConverter
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new ValidationErrorsToStringConverter();
}
 
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Data Validation
{
ReadOnlyObservableCollection<ValidationError> errors =
value as ReadOnlyObservableCollection<ValidationError>;
 
if (errors == null)
{
return string.Empty;
}
 
return string.Join("\n", (from e in errors
select e.ErrorContent as string).ToArray());
}
 
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
 
 

Create an ErrorTemplate for the TextBox


Next thing is to create an error template for the text box.

 
<ControlTemplate x:Key="TextBoxErrorTemplate" TargetType="Control">
<Grid ClipToBounds="False" >
<Image HorizontalAlignment="Right" VerticalAlignment="Top"
Width="16" Height="16" Margin="0,-8,-8,0"
Source="{StaticResource ErrorImage}"
ToolTip="{Binding ElementName=adornedElement,
Path=AdornedElement.(Validation.Errors),
Converter={k:ValidationErrorsToStringConverter}}"/>
<Border BorderBrush="Red" BorderThickness="1" Margin="-1">
<AdornedElementPlaceholder Name="adornedElement" />
</Border>
</Grid>
</ControlTemplate>
 

The ValidationRule and the ErrorTemplate in Action


Finally we can add the validation rule to our binding expression that binds the Text property of a textbox to a EMail property of our
business object.

 
<TextBox x:Name="txtEMail" Template={StaticResource TextBoxErrorTemplate}>
<TextBox.Text>
<Binding Path="EMail" UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<local:RegexValidationRule Pattern="{StaticResource emailRegex}"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Data Validation
 
 

How to manually force a Validation


If you want to force a data validation you can manually call UpdateSource() on the binding expression. A useful scenario could be
to validate on LostFocus() even when the value is empty or to initially mark all required fields. In this case you cann call
ForceValidation() in the Loaded event of the window. That is the time, when the databinding is established.

The following code shows how to get the binding expression from a property of a control.
 
private void ForceValidation()
{
txtName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
 
 

  ► Tutorial   ► ASP Net Tutorial   ► Photoshop CS4   ► Photoshop Action

Last modified: 2009-07-06 13:53:43


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 15.January 2010

For those of you who can't get get this example to work...try this link
Ceri
http://www.switchonthecode.com/tutorials/wpf-tutorial-binding-validation-rules. It will help fill in the
missing bits.

Commented on 15.January 2010

For those of you who can't get get this example to work...try this link
Ceri
http://www.switchonthecode.com/tutorials/wpf-tutorial-binding-validation-rules. It will help fill in the
missing bits.

Commented on 27.January 2010

Thanks Ceri, that was a better example and with source code and solution file to understand
Sandy

Commented on 8.February 2010

is the tooltip supposed to open when there is an error. When I do this, the tooltip has the message but
jd
only opens when I hover the mouse over.

Commented on 8.February 2010

is the tooltip supposed to open when there is an error. When I do this, the tooltip has the message but
jd
only opens when I hover the mouse over.

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Data Validation

Commented on 8.February 2010

is the tooltip supposed to open when there is an error. When I do this, the tooltip has the message but
jd
only opens when I hover the mouse over.

Commented on 26.February 2010

This is a good article but I agree with others who requested a project download... when you're new to
Mike
WPF it's not obvious sometimes what goes where or what references are needed etc. Remember, not
everyone's a guru!!

Commented on 17.March 2010

Plz post the complete Window1.xaml content... Important things are missing.
kap

Commented on 17.March 2010

Error:

Error
This is wrong: Template={StaticResource TextBoxErrorTemplate}>

It must be: <TextBox x:Name="txtEMail" Validation.ErrorTemplate="{StaticResource


TextBoxErrorTemplate>

Now it works!

Commented on 29.March 2010

Is it possible to use DataAnnotations with xaml and if so, any chance of a short example code?
Klara

Commented on 18.May 2010

Hello, Everyone thanks for your comment, i m looking forward to publish my new site which is on WCF it
Christian...
might help you please go through www.wcf.ru

Commented on 18.May 2010

OK?!?!?!, I did Hello World, worked fine, but am I missing step in between to be able to achieved this
Alex
puzzle, or I am going too quick. What goes where?!!??!?

Nice web site, but you should add steps to know what to try first, second,...

Commented on 2.July 2010

Excellent Article. Got it working easily. Helped me alot!


GaaTy

Commented on 20.September 2010

How will you stop user from going to next page till user clears all validations on this page? Just like it
WPFPupil
used to happen in aspx pages. As soon as user will click submit button, all client side validators will
validate and of any of them fails then user remains on the same page.

Please help...

Commented on 14.October 2010

I have a little problem in this validation process. I don't wan't to show user the validation errors (red
Vipin M
border on controls) before they try to save the form. Is there any way I can disable this validation errors
on controls till user tries to submit the form?

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Data Validation

Commented on 18.October 2010

Using StringBuilder() is more memory-efficient than using Strings.


Gorked

Commented on 28.October 2010

good , but why there is no simpler way as in winforms for a common thing like validation
sudheer...

Commented on 4.November 2010

I can't get the image to show, but at lease here's the syntax for the image.... <BitmapImage
luke
x:Key="ErrorImage" UriSource="Resources\Key.png" />

Commented on 22.December 2010

its nice
venky

Commented on 13.January 2011

Thanks a lot for this series!!


Raja

Commented on 19.January 2011

Except that the error will not necessarily be correct if there's more than one error. Where you have your
Louis
(Validation.Errors)[0].ErrorContent, you can add ,BindsDirectlyToSource="True" and it will always show
Nardozi
the first error and won't "lie to you" about errors that have already been corrected.

Alternatively, you could replace your ValidationToolTipTemplate with the following:

<ControlTemplate x:Key="ValidationToolTipTemplate" >

<Grid x:Name="root" Margin="5,0" RenderTransformOrigin="0,0" Opacity="0" >

<Grid.RenderTransform>

<TranslateTransform x:Name="xform" X="-25"/>

</Grid.RenderTransform>

<VisualStateManager.VisualStateGroups>

<VisualStateGroup Name="OpenStates">

<VisualStateGroup.Transitions>

<VisualTransition GeneratedDuration="0"/>

<VisualTransition To="Open" GeneratedDuration="0:0:0.2">

<Storyboard>

<DoubleAnimation Storyboard.TargetName="xform" Storyboard.TargetProperty="X" To="0"


Duration="0:0:0.2">

<DoubleAnimation.EasingFunction>

<BackEase Amplitude=".3" EasingMode="EaseOut"/>

</DoubleAnimation.EasingFunction>

</DoubleAnimation>

<DoubleAnimation Storyboard.TargetName="root" Storyboard.TargetProperty="Opacity" To="1"


Duration="0:0:0.2"/>

</Storyboard>

</VisualTransition>

</VisualStateGroup.Transitions>

<VisualState x:Name="Closed">

<Storyboard>

<DoubleAnimation Storyboard.TargetName="root" Storyboard.TargetProperty="Opacity" To="0"


Duration="0"/>

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Data Validation
</Storyboard>

</VisualState>

<VisualState x:Name="Open">

<Storyboard>

<DoubleAnimation Storyboard.TargetName="xform" Storyboard.TargetProperty="X" To="0"


Duration="0"/>

<DoubleAnimation Storyboard.TargetName="root" Storyboard.TargetProperty="Opacity" To="1"


Duration="0"/>

</Storyboard>

</VisualState>

</VisualStateGroup>

</VisualStateManager.VisualStateGroups>

<Border Margin="4,4,-4,-4" Background="#052A2E31" CornerRadius="5"/>

<Border Margin="3,3,-3,-3" Background="#152A2E31" CornerRadius="4"/>

<Border Margin="2,2,-2,-2" Background="#252A2E31" CornerRadius="3"/>

<Border Margin="1,1,-1,-1" Background="#352A2E31" CornerRadius="2"/>

<Border Background="#FFDC000C" CornerRadius="2"/>

<Border CornerRadius="2">

<ListBox MaxHeight="450" ScrollViewer.VerticalScrollBarVisibility="Auto"


ScrollViewer.HorizontalScrollBarVisibility="Disabled"

UseLayoutRounding="True"
Foreground="White" Background="Transparent" Margin="8,4,8,4" ItemsSource="{Binding
(Validation.Errors),BindsDirectlyToSource=True}" >

<ListBox.ItemTemplate>

<DataTemplate>

<TextBlock IsHitTestVisible="False" MaxWidth="240" Text="{Binding ErrorContent}"


TextWrapping="Wrap"/>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</Border>

</Grid>

</ControlTemplate>

Commented on 8.August 2011

To learn wpf this was a very helpful site for me.


Priya
Thanks a lot

Commented on 13.September 2011

Thanks for your nice tutorial.


Beauty
The disadvantage is that you don't tell the needed namespaces. So I propose that you insert the list to
the begin of the tutorial.

Here are all needed namespaces:

---------------------

using System;

using System.Collections.Generic;

using System.Linq;

using System.Globalization;

using System.Text.RegularExpressions;

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Data Validation
using System.Windows.Controls;

using System.Windows.Data;

using System.Collections.ObjectModel;

using System.Windows.Markup;

---------------------

Commented on 13.September 2011

Hidden note:

Beauty
You have a mistype in the last parameter of this line:

---------------------

public override ValidationResult Validate(object value, CultureInfo ultureInfo)

---------------------

It's &quot;cultureInfo&quot; with &quot;C&quot; instead of &quot;ultureInfo&quot;.

Commented on 14.September 2011

Problem:

Beauty
I tried to define &lt;sys:String x:Key=&quot;emailRegex&quot;&gt;
but got the error that the TYPE &quot;sys:String&quot; NOT FOUND.
After a while I found the solution:

---&gt; ADD THIS to the &lt;Window&gt; tag:

xmlns:sys=&quot;clr-namespace:System;assembly=mscorlib&quot;

Name

E-Mail (optional)

Comment

Post Comment

DataValidation.html[2/16/2014 2:47:03 PM]


WPF Tutorial | Value Converters

Home
    Data Binding
    Value Converters Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
ValueConverters
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction
Introduction
Resources

2D Graphics If you want to databind two properties that have incompatible types, you need a piece of code in between, that converts the value
from source to target type and back.
This piece of code is called ValueConverter. A value converter is a class, that implements the
3D Graphics simple interface IValueConverter with the two methods object Convert(object value) and object
ConvertBack(object value).
Animation

Multimedia
How to implement a ValueConverter
Documents

Windows 7
WPF already provides a few value converts, but you will soon need to implement your own converts. To do this, add a class to your
project and call it [SourceType]To[TargetType]Converter. This is a common naming for value converters. Make it public
Interoperability and implement the IValueConverter interface. That's all you need to do.

Performance  
public class BoolToVisibilityConverter : IValueConverter
Expression Blend
{
Tools public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
UI Automation {
// Do the conversion from bool to visibility
}
 
public object ConvertBack(object value, Type targetType,

ValueConverters.html[2/16/2014 2:47:39 PM]


WPF Tutorial | Value Converters

object parameter, CultureInfo culture)


{
// Do the conversion from visibility to bool
}
}
 
 

How to use a ValueConverter in XAML


First thing you need to do is to map the namespace of your converter to a XAML namespace. Then you can create an instance of a
value converter in the resources of the view and give it a name. Then you can reference it by using {StaticResource}
 
<Window x:Class="VirtualControlDemo.Window1"
...
xmlns:l="clr-namespace:VirtualControlDemo"
...>
<Window.Resources>
<l:BoolToVisibilityConverter x:Key="converter" />
</Window.Resources>
<Grid>
<Button Visibility="{Binding HasFunction,
Converter={StaticResource converter}}" />
</Grid>
</Window>
 
 

Simplify the usage of ValueConvers


If you want to use a normal ValueConverter in XAML, you have to add an instance of it to the resources and reference it by using a
key. This is cumbersome, because and the key is typically just the name of the converter.

A simple and cool trick is to derive value converters from MarkupExtension. This way you can create and use it in the binding like
this: Text={Binding Time, Converter={x:MyConverter}}, and that is quite cool!

 
public abstract class BaseConverter : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
 
 

StringFormat Converter
The StringFormatConverter is a useful converter to control the format of an implicit string conversion of an object (e.g. if you bind a
DateTime to a TextBlock ).

 
[ValueConversion(typeof(object), typeof(string))]
public class StringFormatConverter : BaseConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter,

ValueConverters.html[2/16/2014 2:47:39 PM]


WPF Tutorial | Value Converters
System.Globalization.CultureInfo culture)
{
string format = parameter as string;
if (!string.IsNullOrEmpty(format))
{
return string.Format(culture, format, value);
}
else
{
return value.ToString();
}
 
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return null;
}
}
 
 
 

  ► Tutorial   ► Converters   ► Photoshop CS4   ► Photoshop Action

Last modified: 2010-02-19 07:56:23


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 6.November 2009

Thanks for these cool examples. It would help a lot if you would add the namespaces one has to add in order
Anon
to use your examples. Would save a lot of time

Commented on 12.November 2009

Great article

Farzad

just a typo:

valueConverter instead of ValueConvers

Commented on 25.November 2009

Maybe useful to mention how to use the parameter:

Ralph

ToolTip="{Binding Path=Hostname, Converter={x:StringFormatConverter}, ConverterParameter=Connected to


{0}}"

correct?

Commented on 25.March 2010

ValueConverters.html[2/16/2014 2:47:39 PM]


WPF Tutorial | Value Converters

It would be helpful to mention that this converter already exists in System.Windows.Controls namespace in the
Gishu
Presentation assembly and can be directly used in XAML as

<BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"/>

The fact that you used this as an example kind of lead me to believe that it doesn't exist as part of the
framework. It was the converter naming convention (that was new to me) helped me to find it in the Object
browser window.

Great post. Thanks!

Commented on 22.June 2010

How do I use the MarkupExtension, when the Converter is in another NameSpace than the consumer code?

Patrik

Thanks for sharing the Converter!

Commented on 8.July 2010

owsome
Bill

Commented on 15.April 2011

How to use Validators along with converters?


Bill1

Commented on 27.June 2011

Esto esta bien cabron


Jorge

Name

E-Mail (optional)

Comment

Post Comment

ValueConverters.html[2/16/2014 2:47:39 PM]


WPF Tutorial | Behaviors

Home
    Interaction
    Behaviors Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Behaviors
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics A simple Border can be dragged by mouse - because of an attached drag behavior.

3D Graphics

Animation
Introduction
Multimedia Behaviors are a new concept, introduced with Expression Blend in Version 3, to encapsulate pieces of functionality into a reusable
component. These components than can be attached to controls to give them an additional behavior.
Documents
The ideas behind behaviors are to give the interaction designer more flexibility to design complex user interactions without writing any
Windows 7
code.
Interoperability Example of a behaviors are drag&drop, input validation, pan and zoom, re-position of elements, etc... The list of possible behaviors is
Performance
very long.

Imaging an application that has a list of customers and the user can add some of them to subscriber lists. This interaction can be
Expression Blend
designed by providing an "Add" button next to each subscriber list. But if the interaction designer wants to add drag&drop
Tools functionality, he needs to discuss it with the developer and wait until the implementation is done. With behaviors he just drags a drag
and drop behavior on each list and we are done.
UI Automation

How to use behaviors in Expression Blend 3

Behaviors.html[2/16/2014 2:47:52 PM]


WPF Tutorial | Behaviors
Using behaviors in Expression Blend is as simple as adding an element to the design surface. In the asset library you find a new secion
called "Behaviors". It lists all behaviors available within your project. Just grab one of these and drag it onto the element you want to
add this behavior and thats it.

The behavior appears as an child element in the visual tree. By clicking on it you can configure the properties of the behavior.

How does it work


To add behaviors to an element you need some kind of an extension point. This is an attached property called
Interaction.Behaviors.

This attached property holds the list of behaviors for that element and pass a reference to the element into the behavior. The
behavior than can register itself to events and property changes and so extend the functionality of the element.

The idea is simple, but very clever. They don't need any new infrastructure, they just reuse the existing one.

 
<Border Background="LightBlue" >
<e:Interaction.Behaviors>
<b:DragBehavior/>
</e:Interaction.Behaviors>
<TextBlock Text="Drag me around!" />
</Border>
 
 

Behaviors.html[2/16/2014 2:47:52 PM]


WPF Tutorial | Behaviors

How to implement your own behavior


The following example shows the implementation of the drag behavior we used above. Just derive from Behavior<T;gt; and
override the OnAttached() method.

 
public class DragBehavior : Behavior<UIElement>
{
private Point elementStartPosition;
private Point mouseStartPosition;
private TranslateTransform transform = new TranslateTransform();
 
protected override void OnAttached()
{
Window parent = Application.Current.MainWindow;
AssociatedObject.RenderTransform = transform;
 
AssociatedObject.MouseLeftButtonDown += (sender, e) =>
{
elementStartPosition = AssociatedObject.TranslatePoint( new Point(), parent
);
mouseStartPosition = e.GetPosition(parent);
AssociatedObject.CaptureMouse();
};
 
AssociatedObject.MouseLeftButtonUp += (sender, e) =>
{
AssociatedObject.ReleaseMouseCapture();
};
 
AssociatedObject.MouseMove += (sender, e) =>
{
Vector diff = e.GetPosition( parent ) - mouseStartPosition;
if (AssociatedObject.IsMouseCaptured)
{
transform.X = diff.X;
transform.Y = diff.Y;
}
};
}
}
 
 

List of some popular behaviors


Since its so cool and easy to create your own pice of interactivity, I am sure that we will find hunderts of behaviors available soon. I
tried to make a list of some popular ones.

Zoom Behavior
Glass Behavior
Shake Behavior
Transparency Behavior

Behaviors.html[2/16/2014 2:47:52 PM]


WPF Tutorial | Behaviors
  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Web Design Books

Last modified: 2009-04-20 21:07:27


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 3.January 2010

SWEET!!

Martin Ortiz
Learning WPF, and heard about behaviors.

Nice short / concise article..plus good list of additional behaviours.

Commented on 3.January 2010

SWEET!!

Martin Ortiz
Learning WPF, and heard about behaviors.

Nice short / concise article..plus good list of additional behaviours.

Commented on 3.January 2010

SWEET!!

Martin Ortiz
Learning WPF, and heard about behaviors.

Nice short / concise article..plus good list of additional behaviours.

Commented on 5.January 2010

hi..can u tellme how i can add additional behavoiurs like glass behaviour into my project.....
pooja

Commented on 14.May 2010

it works fine the first time I drag and drop the attached control. The other times it translates when the
Ever
mouse is down, before dragging.
(Spanish)

Commented on 7.June 2010

yep, what Ever said. some please explain how to solve this, was not able to figure that out yet. thanks in
martin
advance

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
C-MOSEY
from another website

Commented on 4.October 2010

Well I can. In this code, the transformation is set to the movement vector of the mouse cursor but
Edvald
should be set to (previous translation) + (movement vector):

<code>

Behaviors.html[2/16/2014 2:47:52 PM]


WPF Tutorial | Behaviors
Window parent = Application.Current.MainWindow;

AssociatedObject.RenderTransform = transform;

AssociatedObject.MouseLeftButtonDown += (sender, e) =>

mouseStartPosition = parent.PointToScreen(e.GetPosition(parent));

AssociatedObject.CaptureMouse();

(AssociatedObject as TextBlock).Text = mouseStartPosition.ToString();

};

AssociatedObject.MouseLeftButtonUp += (sender, e) =>

AssociatedObject.ReleaseMouseCapture();

elementStartPosition.X = transform.X;

elementStartPosition.Y = transform.Y;

};

AssociatedObject.MouseMove += (sender, e) =>

var parentPos = parent.PointToScreen(e.GetPosition(parent));

Vector diff = (parentPos - mouseStartPosition);

if (AssociatedObject.IsMouseCaptured)

transform.X = elementStartPosition.X + diff.X;

transform.Y = elementStartPosition.Y + diff.Y;

(AssociatedObject as TextBlock).Text = diff.ToString();


}

};

</code>

Commented on 4.October 2010

Also, remove the "(AssociatedObject as TextBlock).Text = ..." lines as they are only for debugging :)
Edvald

Commented on 4.October 2010

Sorry about the spam, please delete the comments above, here's a cleaned up version:

Edvald

protected override void OnAttached()

Window parent = Application.Current.MainWindow;

AssociatedObject.RenderTransform = transform;

AssociatedObject.MouseLeftButtonDown += (sender, e) =>

mouseStartPosition = e.GetPosition(parent);

AssociatedObject.CaptureMouse();

};

AssociatedObject.MouseLeftButtonUp += (sender, e) =>

AssociatedObject.ReleaseMouseCapture();

elementStartPosition.X = transform.X;

elementStartPosition.Y = transform.Y;

Behaviors.html[2/16/2014 2:47:52 PM]


WPF Tutorial | Behaviors
};

AssociatedObject.MouseMove += (sender, e) =>

var mousePos = e.GetPosition(parent);

Vector diff = (mousePos - mouseStartPosition);

if (AssociatedObject.IsMouseCaptured)

transform.X = elementStartPosition.X + diff.X;

transform.Y = elementStartPosition.Y + diff.Y;

};

Commented on 19.August 2011

Great Article
RItty

Commented on 19.August 2011

Great Article
RItty

Name

E-Mail (optional)

Comment

Post Comment

Behaviors.html[2/16/2014 2:47:52 PM]


WPF Tutorial | Styles

Home
    Styling
    Styles Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Introduction to Styles in WPF
Custom Controls

Layout
Introduction
Input
Imagine you want to create an application with a unique design. All your buttons should have an orange background and an italic
Data Binding font. Doing this the conventional way means that you have to set the Background and the FontStyle property on every single
button.
Styling

Localization

Interaction

Resources  
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
2D Graphics
<Button Background="Orange" FontStyle="Italic"
3D Graphics Padding="8,4" Margin="4">Styles</Button>
<Button Background="Orange" FontStyle="Italic"
Animation Padding="8,4" Margin="4">are</Button>
<Button Background="Orange" FontStyle="Italic"
Multimedia
Padding="8,4" Margin="4">cool</Button>
Documents </StackPanel>
 
Windows 7  
Interoperability
This code is neither maintainable nor short and clear. The solution for this problem are styles.
Performance
The concept of styles let you remove all properties values from the individual user interface elements and combine them into a style.
Expression Blend A style consists of a list of setters. If you apply this style to an element it sets all properties with the specified values. The idea is quite
similar to Cascading Styles Sheets (CSS) that we know from web development.
Tools
To make the style accessible to your controls you need to add it to the resources. Any control in WPF have a list of resources that is
UI Automation inherited to all controls beneath the visual tree. That's the reason why we need to specify a x:Key="myStyle" property that
defines a unique resource identifier.

To apply the style to a control we set the Style property to our style. To get it from the resources we use the {StaticResource
[resourceKey]} markup extension.

Styles.html[2/16/2014 2:48:06 PM]


WPF Tutorial | Styles
 
<Window>
<Window.Resources>
<Style x:Key="myStyle" TargetType="Button">
<Setter Property="Background" Value="Orange" />
<Setter Property="FontStyle" Value="Italic" />
<Setter Property="Padding" Value="8,4" />
<Setter Property="Margin" Value="4" />
</Style>
</Window.Resources>
 
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<Button Style="{StaticResource myStyle}">Styles</Button>
<Button Style="{StaticResource myStyle}">are</Button>
<Button Style="{StaticResource myStyle}">cool</Button>
</StackPanel>
</Window>
 
 

What we have achieved now is

A maintainable code base


Removed the redundancy
Change the appearance of a set of controls from a single point
Possibility to swap the styles at runtime.

Style inheritance
A style in WPF can base on another style. This allows you to specify a base style that sets common properties and derive from it for
specialized controls.
 
<Style x:Key="baseStyle">
<Setter Property="FontSize" Value="12" />
<Setter Property="Background" Value="Orange" />
</Style>
 
 
<Style x:Key="boldStyle" BasedOn="{StaticResource baseStyle}">
<Setter Property="FontWeight" Value="Bold" />
</Style>
 
 

  ► Tutorial   ► Adobe InDesign   ► Photoshop CS4   ► InDesign CS3

Last modified: 2010-02-08 17:55:54


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Styles.html[2/16/2014 2:48:06 PM]


WPF Tutorial | Styles

Commented on 9.July 2010

Graciassss!
Ricardo

Commented on 16.July 2010

What a complete tutorial.. one stop reference for WPF..


joe
GREAT JOB... thx.

Commented on 30.July 2010

<Window.Resources>

Ashish J
<Style x:Key="myStyle" TargetType="Button">

<Setter Property="Background" Value="Red" />

<Setter Property="FontStyle" Value="Italic" />

<Setter Property="FontWeight" Value="Bold" />

<Setter Property="Padding" Value="8,4" />

<Setter Property="Margin" Value="4" />

</Style>

<Style x:Key="btnStyle" TargetType="Button">

<Setter Property="Background" Value="White" />

<Setter Property="FontStyle" Value="Italic" />


<Setter Property="Height" Value="50" />

<Setter Property="Width" Value="60"/>

</Style>

<Style x:Key="btnLast" TargetType="Button">

<Setter Property="Background" Value="Yellow"/>

<Setter Property="FontStyle" Value="Italic"/>

<Setter Property="Width" Value="100" />

</Style>

</Window.Resources>

<StackPanel Orientation="Horizontal" VerticalAlignment="Top">

<Button Style="{StaticResource myStyle}">Styles</Button>

<Button Style="{StaticResource btnStyle}">are</Button>

<Button Style="{StaticResource btnLast}" >cool</Button>

</StackPanel>

Commented on 30.July 2010

<Window.Resources>

Ashish J
<Style x:Key="myStyle" TargetType="Button">

<Setter Property="Background" Value="Red" />

<Setter Property="FontStyle" Value="Italic" />

<Setter Property="FontWeight" Value="Bold" />

<Setter Property="Padding" Value="8,4" />

<Setter Property="Margin" Value="4" />

</Style>

<Style x:Key="btnStyle" TargetType="Button">

<Setter Property="Background" Value="White" />

<Setter Property="FontStyle" Value="Italic" />


<Setter Property="Height" Value="50" />

<Setter Property="Width" Value="60"/>

</Style>

<Style x:Key="btnLast" TargetType="Button">

<Setter Property="Background" Value="Yellow"/>

Styles.html[2/16/2014 2:48:06 PM]


WPF Tutorial | Styles
<Setter Property="FontStyle" Value="Italic"/>

<Setter Property="Width" Value="100" />

</Style>

</Window.Resources>

<StackPanel Orientation="Horizontal" VerticalAlignment="Top">

<Button Style="{StaticResource myStyle}">Styles</Button>

<Button Style="{StaticResource btnStyle}">are</Button>

<Button Style="{StaticResource btnLast}" >cool</Button>

</StackPanel>

Commented on 29.August 2010

Superb tutorial..
Ravikumar...

Commented on 12.October 2010

I like this tutorial, by this only i came to know how to use style in the WPF application. Thanks a lot
Asha.MP

Commented on 16.November 2010

hello,

sanindra...
i have studied your whole artical,due to your artical today i can say this i can deevelop WPF application
also.i am very -very thanks full to you.I have just develop one application in WPF(just like one inventory
manegment system) and i need to deploy that application to client,can u help me out to make installer
of this application.I have database in sql server 2005, and also i am generating Crystal reports.

thanks

Commented on 3.December 2010

Hi sir, i have small doubt.Can i add css to wpf applications? and can i add styles for windows. means in
shankar
ResourcesDictionary?

Commented on 10.January 2011

Very nice
Rajesh

Commented on 22.January 2011

Wonderful straight forward and easy tutorial. And previous comments assisted me as well to get it
ShoneenJvV
working first time!

Thank you so much!

Commented on 19.February 2011

How to make themes and make them selected at runtime?

Sajjad...
is it possible to only change the name of theme and styles get applied?

Commented on 13.May 2011

@Ashsish, How you created buttons in the comments?

Rajesh

Commented on 16.May 2011

Hi, I have applied Styles to all buttons to have a certain heights, margins, but buttons inside my
YH

Styles.html[2/16/2014 2:48:06 PM]


WPF Tutorial | Styles
dateTimePicker and Datagrid are displaced, is there a way to exclude buttons that are inside such
controls ?

Thanks

Commented on 21.May 2011

Really good explanation .keep it up.


A

Commented on 3.June 2011

Thanks!
Anon

Commented on 21.June 2011

&lt;StackPanel Orientation=\&quot;Horizontal\&quot; VerticalAlignment=\&quot;Top\&quot;&gt;

avi
&lt;Button Background=\&quot;Orange\&quot; FontStyle=\&quot;Italic\&quot;
Padding=\&quot;8,4\&quot; Margin=\&quot;4\&quot;&gt;Styles&lt;/Button&gt;

&lt;Button Background=\&quot;Orange\&quot; FontStyle=\&quot;Italic\&quot;


Padding=\&quot;8,4\&quot; Margin=\&quot;4\&quot;&gt;are&lt;/Button&gt;

&lt;Button Background=\&quot;Orange\&quot; FontStyle=\&quot;Italic\&quot;


Padding=\&quot;8,4\&quot; Margin=\&quot;4\&quot;&gt;cool&lt;/Button&gt;

&lt;/StackPanel&gt;

Commented on 7.July 2011

The disadvantage is that you cannot make a style if you don't know what style it is based on (if it is
a
dynamic). Maybe you could set it in code.

&lt;Window&gt;

&lt;Window.Resources&gt;

&lt;Style x:Key=&quot;myStyle&quot; TargetType=&quot;Button&quot;&gt;

&lt;Setter Property=&quot;Background&quot; Value=&quot;Orange&quot; /&gt;

&lt;Setter Property=&quot;FontStyle&quot; Value=&quot;Italic&quot; /&gt;

&lt;Setter Property=&quot;Padding&quot; Value=&quot;8,4&quot; /&gt;

&lt;Setter Property=&quot;Margin&quot; Value=&quot;4&quot; /&gt;

&lt;/Style&gt;

&lt;/Window.Resources&gt;

&lt;StackPanel Orientation=&quot;Horizontal&quot; VerticalAlignment=&quot;Top&quot;&gt;

&lt;Button Style=&quot;{StaticResource myStyle}&quot;&gt;Styles&lt;/Button&gt;

&lt;Button Style=&quot;{StaticResource myStyle}&quot;&gt;are&lt;/Button&gt;

&lt;Button Style=&quot;{StaticResource myStyle}&quot;&gt;cool&lt;/Button&gt;

&lt;/StackPanel&gt;

&lt;/Window&gt;

Commented on 20.July 2011

&lt;input type=button onclick='Styles are great' value='WoW' /&gt;


Atif

Commented on 20.July 2011

&lt;StackPanel Orientation=&quot;Horizontal&quot; VerticalAlignment=&quot;Top&quot;&gt;

fsfsfdfdgd
&lt;Button Background=&quot;Orange&quot; FontStyle=&quot;Italic&quot;
Padding=&quot;8,4&quot; Margin=&quot;4&quot;&gt;Styles&lt;/Button&gt;

&lt;Button Background=&quot;Orange&quot; FontStyle=&quot;Italic&quot;


Padding=&quot;8,4&quot; Margin=&quot;4&quot;&gt;are&lt;/Button&gt;

Styles.html[2/16/2014 2:48:06 PM]


WPF Tutorial | Styles
&lt;Button Background=&quot;Orange&quot; FontStyle=&quot;Italic&quot;
Padding=&quot;8,4&quot; Margin=&quot;4&quot;&gt;cool&lt;/Button&gt;

&lt;/StackPanel&gt;

Commented on 22.July 2011

Just amazing! Thanks!


Vasu

Commented on 26.July 2011

Clear and helpfull. Thank you.


Aykut

Commented on 26.July 2011

Clear and helpfull. Thank you.


Aykut

Commented on 24.August 2011

&lt;StackPanel Orientation=&quot;Horizontal&quot; VerticalAlignment=&quot;Top&quot;&gt;

bri
&lt;Button Background=&quot;Orange&quot; FontStyle=&quot;Italic&quot;
Padding=&quot;8,4&quot; Margin=&quot;4&quot;&gt;Styles&lt;/Button&gt;

&lt;Button Background=&quot;Orange&quot; FontStyle=&quot;Italic&quot;


Padding=&quot;8,4&quot; Margin=&quot;4&quot;&gt;are&lt;/Button&gt;

&lt;Button Background=&quot;Orange&quot; FontStyle=&quot;Italic&quot;


Padding=&quot;8,4&quot; Margin=&quot;4&quot;&gt;cool&lt;/Button&gt;

&lt;/StackPanel&gt;

Commented on 28.August 2011

&lt;strong&gt;How to use styles defined in App.xaml ?&lt;/strong&gt;


asd

Commented on 13.September 2011

Aly Thank's..Great... :)
Sangadji

Name

E-Mail (optional)

Comment

Post Comment

Styles.html[2/16/2014 2:48:06 PM]


WPF Tutorial | Control Templates

Home
    Styling
    Control Templates Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Control Templates
Custom Controls

Layout
Introduction
Input
Controls in WPF are separated into logic, that defines the states, events and properties and template, that defines the visual
Data Binding appearance of the control. The wireup between the logic and the template is done by DataBinding.

Styling Each control has a default template. This gives the control a basic appearance. The default template is typically shipped together with
the control and available for all common windows themes. It is by convention wrapped into a style, that is identified by value of the
Localization
DefaultStyleKey property that every control has.
Interaction
The template is defined by a dependency property called Template. By setting this property to another instance of a control
Resources template, you can completely replace the appearance (visual tree) of a control.

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

The control template is often included in a style that contains other property settings. The following code sample shows a simple
control template for a button with an ellipse shape.

Templates.html[2/16/2014 2:48:43 PM]


WPF Tutorial | Control Templates
 
<Style x:Key="DialogButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Ellipse Fill="{TemplateBinding Background}"
Stroke="{TemplateBinding BorderBrush}"/>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
 
 
 
<Button Style="{StaticResource DialogButtonStyle}" />
 
 

A Button without and with a custom control template

ContentPresenter
When you create a custom control template and you want to define a placeholder that renders the content, you can use the
ContentPresenter. By default it adds the content of the Content property to the visual tree of the template. To display the
content of another property you can set the ContentSource to the name of the property you like.

Triggers

{RelativeSource TemplatedParent} not working in DataTriggers of a ControlTemplate

If you want to bind to a property of a property on your control like Data.IsLoaded you cannot use a normal Trigger, since it does
not support this notation, you have to use a DataTrigger.

But when you are using a DataTrigger, with {RelativeSource TemplatedParent} it will not work. The reason is, that
TemplatedParent can only be used within the ControlTemplate. It is not working in the Trigger section. You have to use the
{RelativeSource Self} instead.

Templates.html[2/16/2014 2:48:43 PM]


WPF Tutorial | Control Templates

What if a Binding working or a Setter is not applied when using a control template
There is something you need to know when setting a value of an element within a control template: The value does have a lower
precendence as the local value! So if you are setting the local value in the constructor of the contained element, you cannot override
it within the controltemplate. But if you use the element directly in your view, it will work. So be aware of this behavior!.


Here you can find more information about DependencyProperty value precendence: Dependency Property Value Precedence

  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Design Templates

Last modified: 2010-04-27 16:48:31


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 29.July 2010

you people I really not getting why you are congrat this guy ! This site is uglying explaning WPF ! just
ouais
good to run away and find real explanation from programmer !

Commented on 3.September 2010

seems really interesting thanks for your efforts to make this material available for us
i

Commented on 3.September 2010

Nice one
Arjun

Commented on 12.October 2010

Fill="{TemplateBinding Background}" Stroke="{TemplateBinding BorderBrush}"

Asha.MP
in the above properties we can specify the colors also, what is the meaning of TemplateBinding in the
above property??

Commented on 19.October 2010

nice...

siva

Commented on 22.November 2010

Great Article , thanks for your efforts :)


Praveen

Commented on 24.January 2011

very nice.
bala

Commented on 21.February 2011

good one

Templates.html[2/16/2014 2:48:43 PM]


WPF Tutorial | Control Templates
sri

Commented on 24.March 2011

if u dont mind , can u thrown some light on visualstatemanager as well.. ?


prassanth

Commented on 17.April 2011

Many many thanks for this article...


Ankit

Commented on 21.April 2011

Gurpreet Great explaination ! thanks


Singh

Commented on 23.April 2011

Thanks buddy good articles

Tejas

Commented on 26.April 2011

Janynne Great explanation and i liked the figure, so clear!


Gomes

Commented on 4.May 2011

These comments are laughably fake.


anon

Commented on 18.May 2011

Thanks, Nice explanation


Paras

Commented on 24.May 2011

Great. And where do i have to write the style-tag down, now?


Anon

Commented on 1.June 2011

So Clear very nicely explained


Mayank

Commented on 14.June 2011

please show, how to focus and enable the elliptic button


jones

Commented on 9.July 2011

So Clear nice
bm

Commented on 12.July 2011

Thank you! This tutorial is awesome!


Dmitry

Commented on 13.July 2011

I want to create Template for TextBox. How can I aceess RelativeSource TEXT property.
Alibaba

Templates.html[2/16/2014 2:48:43 PM]


WPF Tutorial | Control Templates

Commented on 18.July 2011

@Alibaba: If I am understanding you correctly, you would not use RelativeSource to bind to the text
stigma
property. You would use &quot;{TemplateBinding Text}&quot;. For example:

&lt;TextBlock Text=&quot;{TemplateBinding Text}&quot;/&gt;

Using a TextBox inside a TextBox ControlTemplate, however, I have found to be very unhelpful. Try
using: &lt;ScrollViewer x:Name=&quot;PART_ContentHost&quot;/&gt; If you name the ScrollViewer
exactly as I have here, the text will be bound to it. No other work required.

Commented on 22.August 2011

Life Saver :)
Ziad

Commented on 5.September 2011

Machi awesome article...Thanks !!!


johnson

Commented on 20.September 2011

Viva linux!!
Gonzalo

Name

E-Mail (optional)

Comment

Post Comment

Templates.html[2/16/2014 2:48:43 PM]


WPF Tutorial | Data Templates

Home
    Styling
    Data Templates Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Data Templates
Custom Controls

Layout
Introduction
Input
Data Template are a similar concept as Control Templates. They give you a very flexible and powerful solution to replace the visual
Data Binding appearance of a data item in a control like ListBox, ComboBox or ListView. In my opinion this is one of the key success factory of
WPF.
Styling
If you don't specify a data template, WPF takes the default template that is just a TextBlock. If you bind complex objects to the control,
Localization
it just calls ToString() on it. Within a DataTemplate, the DataContext is set the data object. So you can easily bind against the data
Interaction context to display various members of your data object

Resources

2D Graphics
DataTemplates in Action: Building a simple PropertyGrid
3D Graphics Whereas it was really hard to display complex data in a ListBox with WinForms, its super easy with WPF. The following example shows
a ListBox with a list of DependencyPropertyInfo instances bound to it. Without a DataTemplate you just see the result of calling
Animation
ToString() on the object. With the data template we see the name of the property and a TextBox that even allows us to edit the
Multimedia value.

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

DataTemplates.html[2/16/2014 2:48:58 PM]


WPF Tutorial | Data Templates

 
<!-- Without DataTemplate -->
<ListBox ItemsSource="{Binding}" />
 
<!-- With DataTemplate -->
<ListBox ItemsSource="{Binding}" BorderBrush="Transparent"
Grid.IsSharedSizeScope="True"
HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
<TextBox Grid.Column="1" Text="{Binding Value }" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
 

How to use a DataTemplateSelector to switch the Template depending on the data


Our property grid looks nice so far, but it would be much more usable if we could switch the editor depending on the type of the
property.

The simplest way to do this is to use a DataTemplateSelector. The DataTemplateSelector has a single method to override:
SelectTemplate(object item, DependencyObject container). In this method we decide on the provided item
which DataTemplate to choose.

The following exmple shows an DataTemplateSelector that decides between tree data templates:

 
public class PropertyDataTemplateSelector : DataTemplateSelector
{
public DataTemplate DefaultnDataTemplate { get; set; }
public DataTemplate BooleanDataTemplate { get; set; }
public DataTemplate EnumDataTemplate { get; set; }
 
public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
DependencyPropertyInfo dpi = item as DependencyPropertyInfo;
if (dpi.PropertyType == typeof(bool))
{
return BooleanDataTemplate;
}
if (dpi.PropertyType.IsEnum)
{
return EnumDataTemplate;
}
 
return DefaultnDataTemplate;
}

DataTemplates.html[2/16/2014 2:48:58 PM]


WPF Tutorial | Data Templates
}
 
 
 
<Window x:Class="DataTemplates.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:DataTemplates"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
 
<Window.Resources>
 
<!-- Default DataTemplate -->
<DataTemplate x:Key="DefaultDataTemplate">
...
</DataTemplate>
 
<!-- DataTemplate for Booleans -->
<DataTemplate x:Key="BooleanDataTemplate">
...
</DataTemplate>
 
<!-- DataTemplate for Enums -->
<DataTemplate x:Key="EnumDataTemplate">
...
</DataTemplate>
 
<!-- DataTemplate Selector -->
<l:PropertyDataTemplateSelector x:Key="templateSelector"
DefaultnDataTemplate="{StaticResource DefaultDataTemplate}"
BooleanDataTemplate="{StaticResource BooleanDataTemplate}"
EnumDataTemplate="{StaticResource EnumDataTemplate}"/>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding}" Grid.IsSharedSizeScope="True"
HorizontalContentAlignment="Stretch"
ItemTemplateSelector="{StaticResource templateSelector}"/>
</Grid>
</Window>
 
 

How to react to IsSelected in the DataTemplate


If you want to change the appearance of a ListBoxItem when it is selected, you have to bind the IsSelected property of the
ListBoxItem. But this is a bit tricky, you have to use a relative source with FindAcestor to navigate up the visual tree until you reach the
ListBoxItem.

 
<DataTemplate x:Key="DefaultDataTemplate">
<Border x:Name="border" Height="50">
...
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource=
{RelativeSource Mode=FindAncestor, AncestorType=
{x:Type ListBoxItem}},Path=IsSelected}" Value="True">
<Setter TargetName="border" Property="Height" Value="100"/>
DataTemplates.html[2/16/2014 2:48:58 PM]
WPF Tutorial | Data Templates

</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
 
 

  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Design Templates

Last modified: 2009-10-08 16:50:58


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 15.December 2009

I think I just decided to learn WPF...


Stephen

Commented on 11.February 2010

Hi Christian,

sathya
Thank you very much, i got very good basics of WPF, it is really helpfull, i really appreciate your
work.Thank you, could you give me guideline how to study WCF bascis, you can send to my mail id
sathyajan1@gmail.com. thank you again, i appreciate your work.

Commented on 11.March 2010

Very helpful article and I would further appreciate if you give the UI prinout before and after the
Yadav
application of the template. Thank you.

Commented on 20.April 2010

how can i use TreeView control to show SQL-database data in hierarchical view using c sharp.. please
ward
help me here because am working on windows from application project . iit's my graduation project.

Commented on 21.June 2010

This is a poor example. Where is the code behind? Where is the binding? What is this magic data you are
Confused
adding to the list view?

Commented on 22.June 2010

This is a poor example. Where is the code behind? Where is the binding? What is this magic data you are
Confused
adding to the list view?

Commented on 22.June 2010

This is a poor example. Where is the code behind? Where is the binding? What is this magic data you are
Confused
adding to the list view?

DataTemplates.html[2/16/2014 2:48:58 PM]


WPF Tutorial | Data Templates

Commented on 28.June 2010

WOW
tim

Commented on 23.July 2010

Mr Confused,
danielwu

Before you make conclusion, you'd better finish the whole article and then you will find sample solution
for download in the end...

Commented on 24.August 2010

Its really very good information about data templates.


Shankarnag

Commented on 1.October 2010

Great article, just what I was looking for. Great web site.
Nikola

Commented on 9.November 2010

Nice
Bala

Commented on 9.November 2010

Worst discussion...lost interest in WPF


Hemanath

Commented on 9.November 2010

No Hemanath...It is not like that...It is really worth reading...WPF rocks...


Bala

Commented on 27.November 2010

Thank you, this really saved me a lot of time plowing though Hubers WPF Handbook. It is a worthy read,
Salem5
but I need a few results now.

Commented on 15.December 2010

I downloaded the sample and all it has it a bunch of checkboxes and textbox, i don't see any
KMC
datatemplaing in the working...did you upload the wrote source codes?

Commented on 10.February 2011

Wow, I worked for a very long time on how to put together a dynamic property editor, and you make it
Jamie
look so easy. The key was Grid.IsSharedSizeScope and ColumnDefinition.SharedSizeGroup. Well done
and thanks!

Commented on 3.March 2011

good chaka...
jhon

Commented on 30.March 2011

truely awesome, I have been looking for this functionality for a long time, I will put it into test and come
unruledboy
back to you

DataTemplates.html[2/16/2014 2:48:58 PM]


WPF Tutorial | Data Templates

Commented on 30.March 2011

Hi, I tried you method, all the text content are not rendered(the TextBlock showing nothing, even I place a
unruledboy
button and bind Name for the content, still nothing). I am sure there is data, and before using data
template, it's showing.

&lt;DataTemplate x:Key=&quot;DefaultDataTemplate&quot;&gt;

&lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;

&lt;tree:RowExpander /&gt;

&lt;CheckBox IsChecked=&quot;{Binding Selected}&quot; /&gt;

&lt;Image Height=&quot;16&quot; Margin=&quot;2, 0, 5, 0&quot; Source=&quot;{Binding Converter=


{StaticResource TaskImageConverter}}&quot; Width=&quot;16&quot; /&gt;

&lt;TextBlock Style=&quot;{StaticResource TaskItemStyle}&quot; Text=&quot;{Binding Name}&quot; /&gt;

&lt;/StackPanel&gt;

&lt;/DataTemplate&gt;

&lt;my:ResultCellTemplateSelector x:Key=&quot;templateSelector&quot;

DefaultDataTemplate=&quot;{StaticResource DefaultDataTemplate}&quot;/&gt;

&lt;Grid&gt;

&lt;tree:TreeList x:Name=&quot;tlResults&quot;&gt;

&lt;tree:TreeList.View&gt;

&lt;GridView&gt;

&lt;GridView.Columns&gt;

&lt;GridViewColumn Width=&quot;500&quot; Header=&quot;Name&quot;


CellTemplateSelector=&quot;{StaticResource templateSelector}&quot;&gt;

&lt;/GridViewColumn&gt;

&lt;GridViewColumn Header=&quot;Size&quot; Width=&quot;90&quot; DisplayMemberBinding=&quot;


{Binding Converter={StaticResource FileSizeConverter}}&quot; /&gt;

&lt;/GridView.Columns&gt;

&lt;/GridView&gt;

&lt;/tree:TreeList.View&gt;

&lt;/tree:TreeList&gt;

&lt;/Grid&gt;

Commented on 30.March 2011

sorry, it's my mistake, I used the template from another control. It's working fine now, thank you very
unruledboy
much!

Commented on 15.April 2011

Hi,
Wes
This is the best PropertyGrid Tutorial I found. The best part is,
it also have code to select DataTemplate depend on DataType of each class property: bool use
BooleanDataTemplate which is a checkbox; Enum use EnumDataTemplate which is a combobox.
I also like go a little further, add custom type: lookup, which will show as dropdown list, but the value list
come from database. e.g.

property name: car manufacturere, value come from &quot;SELECT LOOKUP_VALUE FROM LOOKUP
WHERE LOOKUP_KEY = 'CAR_MFG'&quot;, which will return a list like: Toyota, Ford, Nissan, Honda, VW,
BMW, ...
If I have &gt; 1 lookup properties, how I can speciafy them? LookupDataTemplate1,
LookupDataTemplate2, ..., then how to specify them in XAML Resources. and all DataTemplate are pre-
DataTemplates.html[2/16/2014 2:48:58 PM]
WPF Tutorial | Data Templates

defined in XAML, how I can do it in this case.

similar to EnumToListConverter, How I can create LookupmToListConverter1, LookupmToListConverter2?

Thank you,

Commented on 21.April 2011

I run example solution with VS 2010 and .NET 4. It starts but when scrolling I am getting following error:

Mikhail

'' is not a valid value for property 'ClickMode'.

Same for 'FlowDirection', 'HorizontalAlignment, ecc.

Commented on 14.June 2011

@Mikhail: I get this Error while starting.

jones
Try this with the Property DependencyPropertyInfo.Value in DependencyPropertyInfo.cs:

set { try { _element.SetValue (_descriptor.DependencyProperty, value); } catch { } }

I suppose the error occures, because the Comboboxes have no item selected...

Commented on 15.June 2011

Really nice articles


Ajay

Name

E-Mail (optional)

Comment

Post Comment

DataTemplates.html[2/16/2014 2:48:58 PM]


WPF Tutorial |

Home Share... Feed About Christian Moser


   
     

Home

WPF Inspector Article not found!


Getting started

Fundamentals

User Experience

Patterns

Controls

Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

404.html[2/16/2014 2:49:10 PM]


WPF Tutorial | WPF Inspector

Home
    WPF Inspector Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Inspector
Custom Controls

Layout
NEW: XAML Inspector - cross platform visual Debugging
Input
Have a look at XAML inspector. The successor of WPF Inspector. It brings all the features of WPF Inspector to all XAML platofrms
Data Binding (WPF, Silveright, WinRT and Windows Phone).

Styling Visit project page: www.xamlinspector.com

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend WPF Inspector is a utility that attaches to a running WPF application to troubleshoot common problems with layouting, databinding or
styling. WPF Inspector allows you to explore a live view of the logical- and visual tree, read and edit property values of elements,
Tools
watch the data context, debug triggers, trace styles and much more. Since March 2011, WPF Inspector is open source and available
UI Automation on CodePlex.

Download WPF Inspector from CodePlex

inspector-2.html[2/16/2014 2:49:46 PM]


WPF Tutorial | WPF Inspector

Last modified: 2013-10-17 13:47:17


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 3.January 2011

Christian,

Vins
I can't get it to work.. Version 0.9.5 gives me error "Object Reference Not Set" when I click Inspect
after selecting my wpf application.

Any clue?

Thanks!

Commented on 10.January 2011

Would be very appreciated to see it working on WPF 4.0 coz we haven't been using 3.5 for a long
xusan
and may be would not work on that version soon, any ways thank you for sharing this wonderfull tool

Commented on 17.January 2011

same as the one above me. i get this error.


shemesh

Commented on 18.January 2011

Very usefull tool I used under Windows 7 x64 and Visual Studio 2008

Tony
since I work with Visual Studio 2010, it's no longer working

if you release the source code, we could help you improve this great tool

(note : Snoop is also a good tool but it doesn't work too)

Commented on 29.January 2011

Agree with the above. We could really help you improve this great tool (and probably make it work
Mel
for a wider audience).

I've been trying to use it in my win7 VS2010 box to no avail. it works on my winxp VS2008 though.

Commented on 10.February 2011

@Tony:

Cory Plotts
Snoop does work for WPF 3.5/4.0 and x86/x64 ... just make sure that you have the latest version at
http://snoopwpf.codeplex.com.

If you have grabbed the version from Pete Blois' site ... that one ONLY works for WPF 3.5 and x86.

Commented on 24.February 2011

@Cory Plotts

Tony
The latest version works... sometimes... (many times I can't snoop into the application, the "Snoop this
application" button doesn't do anything, the "Magnify" button is working)

and when I successfully Snoop the application, Snoop is stuck at the ContentPresenter of the main

inspector-2.html[2/16/2014 2:49:46 PM]


WPF Tutorial | WPF Inspector
window, I can't "snoop" into my injected view (my project use CAB/SCSF)

Commented on 3.March 2011

hallo,,,,i jhon IT student, can u pls help me to develop my thesis,

jhon
using wpf, pls view me some sample or give me some sites that can
help me in developing may programm..thanks..

Commented on 11.March 2011

nice work
Rohatash

Commented on 11.March 2011

Great work with this new release!

Borislav Ivanov
I hit a small problem:

I have two running 2 WPF applicaions and choose to attach to one of them, but WPF Inspector
attaches to the other one:

- .NET 4.0 64-bit (this is Metro Twit)

- .NET 3.0 32-bit (this is my app, that I cannot attach to)

If I stop the Metro Twit, I can succesfully attach to my app.

Commented on 17.March 2011

I just realized that if I put a disabled button to register the application unless you enter a valid serial,
edgar
you can enable that button easy. 0_o

Great application!

Commented on 23.March 2011

It is very usefull for me..

suresh
I learn wpf basic easily..this is great.
ramasamy

Commented on 23.March 2011

Hi Borislav,

Christian
the problem has been fixed in version 0.9.8. You can download it directly from codeplex.
Moser

Commented on 23.March 2011

Really a gud site for WPF learners..


Aly

Commented on 29.March 2011

It's great site who are working on WPF for the first time .
Debashish...

Commented on 13.April 2011

It's good site for Beginner who are working on WPF


Girish K

Commented on 14.April 2011

Mole is another great way to visualize WPF apps, they just put out Mole 2010 and it's really awesome
Jane
for what I'm doing with WPF at work.

inspector-2.html[2/16/2014 2:49:46 PM]


WPF Tutorial | WPF Inspector
www.molosoft.com

Commented on 16.April 2011

Very handy tool ,,, more features than snoop....


tauqir

One Suggestion : The Main Inspector should not exit when we close the application we are inspecting.
We have to rerun inspector every time we want to inspect.
Hope to see this in future release.

Commented on 18.April 2011

Hello Christian.

Tobias
your Tool is very nice.

But, it is not possible to read complete Text of Errors, if they are very long. It is not possible to scroll,
or rightclick to copy text to clipboard.

It would be very nice and good to have this feature.

Greets

Tobi

Commented on 29.April 2011

Hi,

Rohit

WPF Inspector is an awesome stuff for a wpf developer. But i'm facing an issue with it.

can you provide any work around for this - http://stackoverflow.com/questions/5831354/cannot-add-


geometrydrawing-to-drawinggroup

Thanks,

Commented on 3.May 2011

Sir please give demo video how to work on this? i am not able to know this one.Its showing empty.
shankar

Commented on 17.June 2011

Very promissins concept, I've been looking for something like this for some time.
Thomaz
But I'm having trouble attaching it to my application. Seems like no matter which application I select in
the Attach box WPF inspector always attaches to itself.

Commented on 19.July 2011

Good
Sai Govind.N.K

Commented on 14.August 2011

... Show de Bola!!


Rodrigo

Commented on 26.September 2011

Really helpful resource


Tamas

inspector-2.html[2/16/2014 2:49:46 PM]


WPF Tutorial | WPF Inspector
Name

E-Mail (optional)

Comment

Post Comment

inspector-2.html[2/16/2014 2:49:46 PM]


WPF Tutorial | Instruction Videos

Home
    Getting started
    Instruction Videos Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Videos about WPF
Custom Controls

Layout
General
Input
WPF Roadmap (PDC 2008)
Data Binding Windows Presentation Foundation 4 Plumbing and Internals
Styling

Localization Multimedia
Interaction
How to use text-to-speech in WPF
Resources

2D Graphics
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes
3D Graphics

Animation
Last modified: 2010-04-06 17:28:20
Multimedia Copyright (c) by Christian Moser, 2011.

Documents

Windows 7
 Comments on this article
Interoperability
Show all comments
Performance
Commented on 11.June 2010
Expression Blend
it's very simple to learn wpf. i like it.
Tools Vikas Rana

UI Automation
Commented on 25.September 2010

Merin Wow! Super presentations...WPF rocks...


Nakarmi

Videos.html[2/16/2014 2:49:56 PM]


WPF Tutorial | Instruction Videos

Commented on 6.January 2011

Nice..!
pradeep

Commented on 9.February 2011

I just start study wpf first time


sothea

Commented on 28.March 2011

very nice..
Naik

Commented on 13.May 2011

Great Videos............

uday

Commented on 26.May 2011

All those comments are fake. The wording is to obvious and besides... why should anyone rate a site
Andreas
which contains only two links rate as &quot;Super presentations...&quot;. Come on!

Commented on 10.June 2011

Nice article !

Ajay Jamwal

Commented on 10.August 2011

@Andreas have u watched the videos mentioned in the links. 2nd link contains a video that takes an
Salman
hour of presentation. :)

Name

E-Mail (optional)

Comment

Post Comment

Videos.html[2/16/2014 2:49:56 PM]


WPF Tutorial | What's new in XAML in .NET 4.0

Home
    Fundamentals
    What's new in XAML in .NET 4.0 Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
What's new in XAML of .NET 4.0
Custom Controls
Easy Object References with {x:Reference}
Layout
Built-in Types
Input
Generics in XAML with x:TypeArguments
Data Binding
Support for Arbitrary Dictionary Keys
Styling
Use of Non-Default Constructors with x:Arguments
Localization
Use of Static Factory Methods with x:FactoryMethod
Interaction

Resources
With .NET 4.0 Microsoft will bring up a improved version of XAML. This arcitle shows you the language enhancements they made.
2D Graphics

3D Graphics
Easy Object References with {x:Reference}
Animation
If you want to create an object reference today you need to do a databinding and declare the source with an ElementName. In XAML
Multimedia
2009 you can use the new {x:Reference} markup extension
Documents  
<!-- XAML 2006 -->
Windows 7
<Label Target="{Binding ElementName=firstName}">FirstName</Label>
Interoperability <TextBox x:Name="firstName" />
 
Performance
<!-- XAML 2009 -->
Expression Blend <Label Target="{x:Reference firstName}">FirstName</Label>
<TextBox x:Name="firstName" />
Tools  
 
UI Automation

Built-in Types
If you want to add objects of simple types like string or double to a resource dictionary today you need to map the needed clr-

XAML2009.html[2/16/2014 2:50:09 PM]


WPF Tutorial | What's new in XAML in .NET 4.0
namespaces to an XML namespaces. In XAML 2009 we a lot of simple types that are included in the XAML language.
 
<!-- XAML 2006 -->
<sys:String xmlns:sys="clr-namespace:System;assembly=mscorlib >Test</sys:String>
 
<!-- XAML 2009 -->
<x:String>Test</x:String>
 
 
The following types are included into the XAML language:

<x:Object/>
<x:Boolean/>
<x:Char/>
<x:String/>
<x:Decimal/>
<x:Single/>
<x:Double/>
<x:Int16/>
<x:Int32/>
<x:Int64/>
<x:TimeSpan/>
<x:Uri/>
<x:Byte/>
<x:Array/>
<x:List/>
<x:Dictionary/>

Generics in XAML with x:TypeArguments


If you want to use an ObservableCollection<Employee> in XAML you need to create a type that derives from
ObservableCollection because you cannot declare it in XAML. With XAML 2009 you can use the x:TypeArguments
attribute to define the type of a generic type.
 
<!-- XAML 2006 -->
class EmployeeCollection : ObservableCollection<Employee>
{
}
 
<l:EmployeeCollection>
<l:Employee FirstName="John" Name="Doe" />
<l:Employee FirstName="Tim" Name="Smith" />
</lEmployeeCollection>
 
<!-- XAML 2009 -->
<ObservableCollection x:TypeArguments="Employee">
<l:Employee FirstName="John" Name="Doe" />
<l:Employee FirstName="Tim" Name="Smith" />
</ObservableCollection />
 
 

Support for Arbitrary Dictionary Keys


XAML2009.html[2/16/2014 2:50:09 PM]
WPF Tutorial | What's new in XAML in .NET 4.0

In XAML 2006 all explicit x:Key value were threated as strings. In XAML 2009 you can define any type of key you like by writing the
key in ElementSyntax.

 
<!-- XAML 2006 -->
<StreamGeometry x:Key="CheckGeometry">M 0 0 L 12 8 l 9 12 z</StreamGeometry>
 
<!-- XAML 2009 -->
<StreamGeometry>M 0 0 L 12 8 l 9 12 z
<x:Key><x:Double>10.0</x:Double></x:Key>
</StreamGeometry>
 
 

Use of Non-Default Constructors with x:Arguments


In XAML 2006 objects must have a public default constructor to use them. In XAML 2009 you can pass constructor arguments by
using the x:Arguments syntax.
 
<!-- XAML 2006 -->
<DateTime>00:00:00.0000100</DateTime>
 
<!-- XAML 2009 -->
<DateTime>
<x:Arguments>
<x:Int64>100</x:Int64>
</x:Arguments>
</DateTime>
 
 

Use of Static Factory Methods with x:FactoryMethod


When you have a type that has no public constructor but a static factory method you had to create that type in code in XAML 2006.
With XAML 2009 you can use the x:FactoryMethodx:Arguments attribute to pass the argument values.

 
<!-- XAML 2006 -->
Guid id = Guid.NewGuid();
 
<!-- XAML 2009 -->
<Guid x:FactoryMethod="Guid.NewGuid" />
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2009-11-01 10:52:07


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

XAML2009.html[2/16/2014 2:50:09 PM]


WPF Tutorial | What's new in XAML in .NET 4.0

Commented on 22.September 2010

Commented on 5.October 2010

I also Didn't got the topic !!!! for what it is


Asif

Commented on 20.October 2010

Nice Article
pallavi

Commented on 20.October 2010

se

lll

Commented on 20.October 2010

yak................dirty
rahul

Commented on 9.November 2010

uper kiye gye sare comment bakwaas hain


sp

Commented on 10.November 2010

Hi Very nice article, i am using VS2010 C# expression Edition

Kiran
When i am using this markup
<Label Target="{x:Reference firstName}">FirstName</Label>

<TextBox x:Name="firstName" />

i got warning "Service Provider is Missing the INameResolver Service"

Any idea how to resolve this???

Commented on 18.November 2010

Here is the explanation from Adam Nathan's WPF 4 unleashed book:

John
"The x:Reference markup extension is often mistakenly associated with the XAML2009

features that can only be used from loose XAML at the time of this writing. Although

x:Reference is a new feature in WPF 4, it can be used from XAML2006 just fine as long as your project is
targeting version 4 or later of the .NET Framework.

One glitch is that the XAML designer in Visual Studio 2010 doesn�t properly handle x:Reference, so
it gives the following design-time error that you can safely ignore:

Service provider is missing the INameResolver service"

Commented on 15.December 2010

nice features...nice explanation


Harish

Commented on 22.December 2010

Above Example and Definition is very good & sort and sweet.
vishal

Commented on 14.January 2011

Really nice Explanations.....

basavaprasad

Commented on 1.February 2011

XAML2009.html[2/16/2014 2:50:09 PM]


WPF Tutorial | What's new in XAML in .NET 4.0

didnt understand any thing.please explain in detail with examples..


sohan

Commented on 25.February 2011

thank you for mentioning, but VS2010 doesnt offer a namespace url like
orhor
"http://schemas.microsoft.com/winfx/2009/xaml"

or where should I set the version?

Commented on 2.March 2011

Commented on 14.March 2011

This still does not work in WPF and VS 2010 !


DNM

Commented on 14.March 2011

This still does not work with WPF and VS 2010 !!!
DNM

Commented on 14.March 2011

mmmm
kkk

Commented on 1.April 2011

Good for beginer...


Anup

Commented on 11.April 2011

please provide the examples along with the syntax.you can provide the link to the example.
kamlendra

Commented on 20.June 2011

It's very nice feature.. Keep it up...It's very useful for beginer.
Mohit Jethva

Commented on 8.July 2011

Good one
Deepthi

Commented on 10.July 2011

Tim http://msdn.microsoft.com/en-us/library/ee792002.aspx
Valentine

Commented on 4.August 2011

Hi I think this site is useful, but it will be more useful if there are more examples to explain the
Raj
concepts,as we are beginners. Thanks in advance.

Commented on 19.September 2011

Rajeev I did not get the topic.Can you please explain it little bit more.
Kumar

XAML2009.html[2/16/2014 2:50:09 PM]


WPF Tutorial | What's new in XAML in .NET 4.0

Commented on 21.September 2011

hai... i need eg.,


anand

Name

E-Mail (optional)
Comment

Post Comment

XAML2009.html[2/16/2014 2:50:09 PM]


WPF Tutorial | Hard- and Softwarerequirements

Home
    Fundamentals
    Hard- and Softwarerequirements Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Minimal Hardware and Software Requirements for WPF
Custom Controls

Layout
Software Requirements
Input
To run WPF on your machine you need to have at least the following software installed:
Data Binding
Windows XP with Service Pack 2 or higher
Styling
.NET Framework 3.0 or higher
Localization

Interaction Hardware requirements


Resources
There are no minimum hardware requirements for WPF. All the requirements comes from the complexity and effects used in your
2D Graphics application.

3D Graphics You can take advantage of hardware acceleration when your graphics processor supports DirectX 9 or higher. I would recommend to
look for a graphicadapter for which the vendor supports a WDDM driver.
Animation
Please note that some effects cannot be done in hardware rendering under Windows XP. For exmaple Windows with
Multimedia AllowsTransparency set to True and the use of BitmapEffects.
Documents
How to specify minimal hardware requirements
Windows 7

A simple way to specify minimal hardware requirements to ensure that your client has a good experience is the Premium Ready label
Interoperability
from Microsoft. It ensures that the machine has at least the following equipment:
Performance
> 800MHz Prozessor
Expression Blend 512 MBytes RAM
Tools A DirectX 9 capable graphics adapter

UI Automation

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Requirements.html[2/16/2014 2:50:45 PM]


WPF Tutorial | Hard- and Softwarerequirements
Last modified: 2010-01-29 17:25:15
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 28.April 2010

itz fabricated
baba

Commented on 8.July 2010

you can't do anything with 800 MHz, 512 RAM....

Tom
Thats no way

Commented on 11.July 2010

@Tom

humanblade
actually you'd be surprised what you can do. in fact you'd be surprised what your grandmother could
do. people who aren't playing games and compiling 100K+ codebases tend to do fine with systems like
these. then again, i've known people to upgrade b/c they needed more memory in order for flash
plugins not to bog down, allowing them to play farmville and have 3 youtube pages open... :)

Commented on 5.August 2010

i think christian has mentioned such low requirements only for beginners who wsih to learn the
bindu
technology basics but not for real time implementations

Commented on 11.August 2010

nice
golden

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
CHRISTIAN
from another website

Commented on 10.March 2011

eeekkk, you really should reference any websites you copy from. Thats someones elses knowledge
Shane

Commented on 5.May 2011

Christian Why yu haven't put your picture


Raaa

Commented on 6.May 2011

Shane this is not some kind of knowledge. .

Rajesh
These are requirement recommended by seller.

Commented on 9.May 2011

The minimal hardware requirements for wpf application depends on the Media effects &amp; codings
Lahiru
.The application should test with the deployed environment
Jayalath

Requirements.html[2/16/2014 2:50:45 PM]


WPF Tutorial | Hard- and Softwarerequirements

Commented on 26.May 2011

nice article but mention the requirement for a more robust graphics and animations too....
Manvendra

Commented on 16.June 2011

Shane: also it's obvious that's some troll posting in the comment section.
Gunnar

Name

E-Mail (optional)

Comment

Post Comment

Requirements.html[2/16/2014 2:50:45 PM]


WPF Tutorial | WPF Troubleshooting

Home
    Fundamentals
    WPF Troubleshooting Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Troubleshooting
Custom Controls
During my time as a consultant I noticed, that there were typical traps in WPF, where developers can loose a lot of time. So I
Layout decided to make a hitlist of the most common mistakes and solutions how to resolve them. I hope this helps.
Input

Data Binding Layout


Styling
Scrollbar is not active or visible
Localization If your control is within a vertical stackpanel, it gives the control infinite height to layout. Consider replacing the
stackpanel by a dockpanel.
Interaction

Resources I created a data template and set HorizontalAlignment to Stretch but the item is not stretched
Set the HorizontalContentAlignment on the list to Stretch
2D Graphics

3D Graphics
DataBinding
Animation

Multimedia I changed a value, but the binding is not reflecting my changes


Check the output window in VisualStudio, if there are any binding errors.
Documents
Does your data support INotifyPropertyChanged?
Windows 7 Just firing a PropertyChanged event without changing the data does not work. Because the binding checks if
oldvalue!=newvalue
Interoperability

Performance
Performance
Expression Blend
My list of items takes too long to render
Tools
Your list is not virtualized. This means, all items will be generated, even if they are not visible. To avoid this check
UI Automation the following points:
ScrollViewer.CanContentScrol must be set to False
Grouping must be disabled
You replaced the ItemsPanel by one that does not support virtualization

Troubleshooter.html[2/16/2014 2:51:04 PM]


WPF Tutorial | WPF Troubleshooting
You are using a too complex data template.

Animations cause a high CPU load.


WPF cannot use hardware acceleration and does software rendering. This can be because of the following points:
You have set AllowTransparency to True on your window.
You are using legacy BitmapEffects instead of fast pixel shaders (Effects).
Your graphics adapter or driver does not support DirectX

Custom Controls
I created a custom control, but the template it not showing
Check if you have overriden the metadata of the DefaultStyleKeyProperty and set it to your type.
Check if your template is surrounded by a style and both have the right TargetType
Check if the resource dictionary that contains the default style is loaded

I use {TemplateBinding} in my ControlTemplate, but is not working


In most cases you have to replace {TemplateBinding Property} by {Binding Property
RelativeSource={RelativeSource TemplatedParent}}
You can only use TemplateBinding within the content of your control template. It will not work anywhere else!
If you want to access a parent property in the trigger, you have to use a normal binding, with relative source Self.
TemplateBinding works only within the VisualTree of the template. You cannot use it on items that are only in the
logical tree. Neighter on Freezables or to do two-way binding.

Last modified: 2011-03-23 07:02:53


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 13.December 2009

Awesome! Thanks a lot


Amit

Commented on 4.January 2010

Harendra Awesome! thanks for valuable article.


kumar

Commented on 5.March 2010

Hi , Thanks .. bat give me a picture of resulta


AbDoU-VB

Commented on 26.May 2010

Addressed the features in the simplest way - Great


James

Troubleshooter.html[2/16/2014 2:51:04 PM]


WPF Tutorial | WPF Troubleshooting

Commented on 8.July 2010

This is great stuff.. i will take a print out of this.


Tom

Commented on 19.July 2010

Good
Helix

Commented on 29.September 2010

how to work with wpf


vinoth kumar

Commented on 28.December 2010

Give more senario


Sushil

Commented on 18.March 2011

Great work...!
Qutub

Commented on 18.March 2011

Great work...!
Qutub

Commented on 18.March 2011

Great work...!
Qutub

Commented on 11.May 2011

Great work.!
subramani

Commented on 13.May 2011

THX!!!! u saved me HOURS!


sterennlt

Commented on 17.August 2011

Could u pls put more info in?


Dimas

Name

E-Mail (optional)

Comment

Post Comment

Troubleshooter.html[2/16/2014 2:51:04 PM]


WPF Tutorial | Dependency Injection

Home
    Patterns
    Dependency Injection Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
A reference architecture for large WPF projects
Custom Controls

Layout
Introduction
Input
Choosing an adequate architecture is crucial for the success of a software project. You can have the best concepts, if your architecture
Data Binding does not perform, the user will have bad experiences while waiting for the application to load. Also aspects like it's robustness,
maintainability or testability are important to address.
Styling
WPF provides a powerful databinding framework. If we could take advantage of this by using the MVVM pattern and decouple our
Localization
views by dependency injection, we can build a powerful scaleable architecture.
Interaction
These are the key components or patterns we want to use:
Resources
WPF DataBinding
2D Graphics Model-View-ViewModel pattern
Dependency Container (e.g. Unity)
3D Graphics
Actions from the System.Windows.Interactivity library
Animation

Multimedia
How it works
Documents
The basic idea is to have a dependency container that builds up a view. The view has a viewmodel injected, that is bound to the
Windows 7 DataContext. The viewmodel concentrates and provides data and commands for the view that it gets from services, that are injected
by the constructor. The services live as singletons within the container.
Interoperability
Using this architecture allows you to build up loosely coupled views that interact magically together over common data coming from
Performance
services in the background. It's very simple to rearrange or replace views, since they have to dependencies among each other.
Expression Blend
Advantages of this architecture:
Tools
UI elements are easily replaced because of flexible databinding
UI Automation The views are loosely coupled and quickly composed together
The viewmodel can be tested with conventional unit testing
Each service has a single purpose. They are easy to develop and make the architecture scalable.

ReferenceArchitecture.html[2/16/2014 2:51:38 PM]


WPF Tutorial | Dependency Injection

Initializing the container and build up the main window


 
public class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<ICustomerService, CustomerService>();
container.RegisterType<IShoppingCartService, ShoppingCartService>();
 
MainWindow mainWindow = container.Resolve<MainWindow>();
mainWindow.Show();
}
}
 
 

Injecting the viewmodel to the view


By adding a [Dependency] attribute to the property, the dependency container resolves and injects the specified type after
creating the view. The injected viewmodel is directly set to the data context of the view. The view itself contains no other logic.

 
public class MainWindow : Window
{
[Dependency]
public MainWindowViewModel ViewModel
{

ReferenceArchitecture.html[2/16/2014 2:51:38 PM]


WPF Tutorial | Dependency Injection
set { DataContext = value; }
}
 
public MainWindow()
{
InitializeComponent();
}
}
 
 

Implementing the viewmodel


 
public class MainWindowViewModel
{
private ICustomerService _customerService;
 
public MainWindowViewModel(ICustomerService customerService)
{
_customerService = customerService;
Customers = new ListCollectionView(customerService.Customers);
}
 
public ICollectionView Customers { get; private set; }
}
 
 

Binding the data to the view


 
<Window x:Class="WpfTutorial.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListBox ItemsSource="{Binding Customers}" />
</Window>
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2010-02-10 10:34:15


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 13.January 2010

awesome !!
chinnappa

Commented on 26.January 2010

ReferenceArchitecture.html[2/16/2014 2:51:38 PM]


WPF Tutorial | Dependency Injection

Great post. One thing I would change is rather than having a write-only ViewModel property, pass it
Alec
as a parameter to the constructor of the window class.

WPF doesn't require parameterless constructors.

Commented on 4.February 2010

thanks..
mukesh

Commented on 23.February 2010

sagar This is think i m looking from long time. Architecture wise WPF make sense isn't it?
tambe

Commented on 18.March 2010

@Sagar

Jeremy

DI was around LONG before WPF. You should look at Martin Folwers articles from the beginning of
this decade.

Commented on 13.May 2010

great job...
rashmin

Commented on 5.June 2010

Can this be done with MEF? Gotta love MEF.


Chris Bellew

Commented on 19.July 2010

Doesn't Prism wrap this functionality?


Bill

Commented on 21.July 2010

Good Explanation

Manish K
can we have source code to download?

Commented on 23.July 2010

Downloadable source would be great!


StevenH77

Commented on 28.July 2010

we can make good ny having code , from where we can have this souce code
San

Commented on 28.July 2010

we can make good practice having code , from where we can have this souce code
San

Commented on 11.August 2010

What a great idea, palagarize other peoples material, have ads and make money.. who says crime
JIm
doesn't pay.

ReferenceArchitecture.html[2/16/2014 2:51:38 PM]


WPF Tutorial | Dependency Injection

Commented on 5.September 2010

better if you provide a Sample of this Explnation.


Jak

Commented on 8.September 2010

Great work...
Viral Dave

Commented on 16.October 2010

Why MainWindow knows about the view Model(have logical reference though property)
Gopal

Commented on 15.November 2010

Great posts, wanted to see PRISM in the works and how would start my project using it,this clears up a
Donny Brasco
lot of things. May you please provide source code so as to see it in code and study how this all ties
up together

Commented on 15.November 2010

Great posts, wanted to see PRISM in the works and how would start my project using it,this clears up a
Donny Brasco
lot of things. May you please provide source code so as to see it in code and study how this all ties
up together

Commented on 28.December 2010

Describe some thing more for new commers


Sushil

Commented on 11.February 2011

Thank you for your post. But, sorry, charts (modelling) and code doesent fit at all. There is no
Achim Koch
ShoppingCartService in your charts and there is no OrderService in your code. Can you please post
some more consistent stuff? It's a little hard to put all pieces togehter, otherwise.

Commented on 14.February 2011

I have coded it a little - not exactly the above modele but some of it.

Achim Koch
But I don't know where to put the code. Can you help me out?

Commented on 8.August 2011

these kinda articles ain't a tutorial. you have explained very short abour dependency injection and
pouyan
your code and diagrams are not useful at all. if you would uploaded a sample project for each article
that would helped a lot.

Commented on 9.August 2011

chala bagundhi....
nagarjunareddy

Commented on 30.August 2011

thanks my dear!
alireza

Name

E-Mail (optional)

ReferenceArchitecture.html[2/16/2014 2:51:38 PM]


WPF Tutorial | Dependency Injection
Comment

Post Comment

ReferenceArchitecture.html[2/16/2014 2:51:38 PM]


WPF Tutorial | DelegateCommand

Home
    Patterns
    DelegateCommand Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to implement a reusable ICommand
Custom Controls

Layout
Introduction
Input
If you are using the MVVM (model-view-viewmodel) pattern, one of the most used mechanism to bind actions to the view are
Data Binding commands. To provide a command, you have to implement the ICommand interface. This is quite simple, but you have to do it over
and over again. This is cumbersome.
Styling
The idea of this pattern build an universal command, that takes two delegates: One that is called, when
Localization
ICommand.Execute(object param) is invoked, and one that evalues the state of the command when
Interaction ICommand.CanExecute(object param) is called.

Resources In addition to this, we need a method, that triggers the CanExecuteChanged event. This causes the ui element to reevaluate the
CanExecute() of the commmand.
2D Graphics

3D Graphics
Sample implementation
Animation
 
Multimedia public class DelegateCommand : ICommand
{
Documents
private readonly Predicate<object> _canExecute;
Windows 7 private readonly Action<object> _execute;
 
Interoperability public event EventHandler CanExecuteChanged;
Performance
 
public DelegateCommand(Action<object> execute)
Expression Blend : this(execute, null)
{
Tools
}
UI Automation  
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;

DelegateCommand.html[2/16/2014 2:52:29 PM]


WPF Tutorial | DelegateCommand
_canExecute = canExecute;
}
 
public override bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
 
return _canExecute(parameter);
}
 
public override void Execute(object parameter)
{
_execute(parameter);
}
 
public void RaiseCanExecuteChanged()
{
if( CanExecuteChanged != null )
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
 
 
 
 

  ► Tutorial   ► Command   ► ActionScript   ► Flex


Last modified: 2010-02-22 22:57:52


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 19.April 2010

Good artical!
lan
If with an example is better

Commented on 12.May 2010

If you want an example, check http://www.codeproject.com/KB/WPF/MVVMForDummies.aspx

YJ
A lot simple, but it could help.

Commented on 20.August 2010

Good artical!
Ganesh

DelegateCommand.html[2/16/2014 2:52:29 PM]


WPF Tutorial | DelegateCommand

but no any example need eample for all property as like your wcf article

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
C-MOSE
from another website

Commented on 28.September 2010

This one the delegate command doesn't really make sense to me... here's why, if in a view we want to
Javaman
decouple a Buttom command to a Command Object why would we delegate it (in some cases) back
to view logic? Or is it that this command is a mediator to delegate to the implementation of the
command in another class?

Commented on 12.October 2010

=> Javaman, I guess you shouldnt go back to the view, usecase for Delegate/RelayCommands is in my
Henke
world to directly connect the command to the viewmodel. Without it you will have to delegate it in the
codebehind instead.

Commented on 23.November 2010

Hi,

dct
if you would like to use this class with WPF4 you have to remove the override keywords.

Take care

Commented on 24.November 2010

Hi,

Hitesh
Good article. Override keyword not needed.

Just curious to know how is RaiseCanExecuteChanged() method called or when is it called.

Thanks

Commented on 28.December 2010

Hi ,good representation but ovveride is not needed


Sushil

Commented on 10.January 2011

Hi Christian,
Catalin
Manoliu
A better example I suggest is this RelayCommand:

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030

The implementation of ICommand.CanExecuteChanged is relying on the wpf's


CommandManager.Requery suggested event. This will improve binding scenarios.

Regards,

Catalin

Commented on 9.March 2011

Hi

costas...
the override bool CanExecute and the override void Execute has no override...

DelegateCommand.html[2/16/2014 2:52:29 PM]


WPF Tutorial | DelegateCommand

Commented on 11.September 2011

THANK YOU FOR CODE OF DELEGATECOMMAND.


ali

Name

E-Mail (optional)
Comment

Post Comment

DelegateCommand.html[2/16/2014 2:52:29 PM]


WPF Tutorial | Calendar

Home
    Controls
    Calendar Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Calendar Control
Custom Controls

Layout

Input

Data Binding
Introduction
Styling

Localization Since WPF 4.0, Microsoft provides a full featured calendar control. It provides the following features:

Interaction Set the displayed date


Multiple selection modes
Resources
Blackout dates
2D Graphics Calendar Modes

3D Graphics

Animation Set the displayed date


Multimedia The calendar displays by default the current date. But you can specify any other date to be displayed by setting the DisplayDate
property.
Documents
 
Windows 7
<Calendar DisplayDate="01.01.2010" />
Interoperability  
 
Performance

Expression Blend
Selection Modes
Tools The calendar control provides multiple modes for selection. You can set the SelectionMode property to
SingleDateSingleRange, MultipleRanges or None.
UI Automation

Calendar.html[2/16/2014 2:52:43 PM]


WPF Tutorial | Calendar

 
<Calendar SelectionMode="MultipleRange" />
 
 

Blackout dates
The calendar control provides a feature to black out dates that are not valid for selection. You can define multiple ranges by setting
the BlackoutDates property to one or multiple CalendarDateRange.

 
<Calendar SelectionMode="{Binding SelectedItem, ElementName=selectionmode}" >
<Calendar.BlackoutDates>
<CalendarDateRange Start="01/01/2010" End="01/06/2010" />
<CalendarDateRange Start="05/01/2010" End="05/03/2010" />
</Calendar.BlackoutDates>
</Calendar>
 
 

Calendar Modes
The calendar supports three modes to display ranges of dates: Year, Month and Decade. You can control the mode by setting the
DisplayMode property.

Calendar.html[2/16/2014 2:52:43 PM]


WPF Tutorial | Calendar

 
<Calendar DisplayMode="Year" />
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2010-03-01 22:32:47


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 9.March 2010

How to make a google calendar like calendar? i.e. an interactive one tt I can add events or tasks to it...
z

Commented on 22.April 2010

that's a good one

smruti

Commented on 19.August 2010

that great.
morteza
good luck

Commented on 19.August 2010

Helpful.Thanks! How to blackout all weekend


ling

Commented on 14.September 2010

This control very nice.


Mahendar

Commented on 11.October 2010

Hi, There is not calendar control in vs2008. In this case how to create calendar control
Sachin

Commented on 10.November 2010

Calendar.html[2/16/2014 2:52:43 PM]


WPF Tutorial | Calendar
Hi christian.

Ganesh Kumar
I have a problem for you. My visual studio toolbox is not showing calender control.

gimme reply.

Thank You.

Commented on 10.November 2010

I'm using Visual Studio 2008 Professional Edition. Thanks


Ganesh Kumar

Commented on 15.November 2010

Do you get .NET 4.0?


iFirsT

Commented on 15.November 2010

I am using visual studio 2008 and i am not getting calendar control.how to import that calendar
Sateesh
control to my application.can anyone help me..

kumar.V

Thanks in advance.

Commented on 20.November 2010

I am using VS 2010 , Thanks a ton

veer.k

Commented on 14.December 2010

Hi christian,

Madhu Kumar
i do not know how to implement ajax for calender.plz give me reply
K.S

Commented on 21.December 2010

Helpful for beginners


Aarti Varadkar

Commented on 19.January 2011

how to add assembly reference for Calendar control? Please help.


Viks

Commented on 5.February 2011

I am getting an error as Error The name 'InitializeComponent' does not exist in the current context
Dorababu
could you please help me

Commented on 16.February 2011

Hi, can I disable years before 1900 ? just to restrict the user from entering date of birth which
MCShah
calculates his age more than 100 years..

Commented on 1.March 2011

Is there any option to go back instead of selection?


siva
Example: suppose if i click on 2010(on disply of january 2010) it will show year format. Now i want to
go back to previous with out selecting any year. Is it possible...

Thanks & Regards,

Siva

Calendar.html[2/16/2014 2:52:43 PM]


WPF Tutorial | Calendar

Commented on 7.March 2011

Could I style just the �Days of the month� in a CalendarDayButtonStyle? They are looking to
Christof
weightily compared the title (Januar 2010)?

Ammann
I figured out that I unfortunately just can Style the �Days of the Month� with the
�Numbers of the Days� like the size and the font.

Commented on 7.March 2011

Hi Christian

Christof
Ammann
Sorry for my question where I asked if I only could set the "Days of the month".

Of course I can. I always ment it would be in the CalendarDayButtonStyle, but it is the


CalendarItemStyle.

Greez Christof

Commented on 31.March 2011

Can you catch the event when the user selects a year (when in decade mode) or month (when in year
Tim
mode)? Or even disable the switch to month view?

Commented on 8.June 2011

Subscribe on the events provided by the Calendar Control. DisplayDateChanged,


MCP DEA
DisplayModeChanged or SelectedDatesChanged.

The event arguments passed by this control (Calendar Control) event has a property of what we need.

If you need further explanation, just post it here.

Commented on 1.July 2011

hi, thanks...

prem tiwary
it's very.........good

Commented on 13.September 2011

nice 1 i love dis site............


Sanjay kumar

Commented on 14.September 2011

how to remove ShowNextPrevMonth=false in wpf??


kamesh

Commented on 19.September 2011

I am using WPF in VS 2008 but i am not getting calender control in tool box.I also tried to add from
Rajeev Kumarr
component but its not there. Can you please help me.

Name

E-Mail (optional)

Comment

Calendar.html[2/16/2014 2:52:43 PM]


WPF Tutorial | Calendar

Post Comment

Calendar.html[2/16/2014 2:52:43 PM]


WPF Tutorial | ItemsControl

Home
    Controls
    ItemsControl Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
ItemsControl
Custom Controls

Layout
How to automatically scroll to the last item
Input
 
Data Binding <ListBox l:ItemsControlHelper.ScrollToLastItem="true" />
 
Styling  

Localization

Interaction  
public static class ItemsControlHelper
Resources
{
2D Graphics public static readonly DependencyProperty ScrollToLastItemProperty =
DependencyProperty.RegisterAttached("ScrollToLastItem",
3D Graphics
typeof(bool), typeof(ItemsControlHelper),
Animation new FrameworkPropertyMetadata(false, OnScrollToLastItemChanged));
 
Multimedia public static void SetScrollToLastItem(UIElement sender, bool value)
Documents {
sender.SetValue(ScrollToLastItemProperty, value);
Windows 7 }
 
Interoperability
public static bool GetScrollToLastItem(UIElement sender)
Performance {
return (bool)sender.GetValue(ScrollToLastItemProperty);
Expression Blend
}
Tools  
private static void OnScrollToLastItemChanged(DependencyObject sender,
UI Automation DependencyPropertyChangedEventArgs e)
{
var itemsControl = sender as ItemsControl;
 
if (itemsControl != null)
ItemsControl.html[2/16/2014 2:52:56 PM]
WPF Tutorial | ItemsControl

{
itemsControl.ItemContainerGenerator.StatusChanged +=
(s,a) => OnItemsChanged(itemsControl,s,a);
}
}
 
static void OnItemsChanged(ItemsControl itemsControl, object sender, EventArgs e)
{
var generator = sender as ItemContainerGenerator;
if( generator.Status == GeneratorStatus.ContainersGenerated )
{
if (itemsControl.Items.Count > 0)
{
ScrollIntoView(itemsControl,
itemsControl.Items[itemsControl.Items.Count - 1]);
}
}
}
 
private static void ScrollIntoView(ItemsControl itemsControl, object item)
{
if (itemsControl.ItemContainerGenerator.Status ==
GeneratorStatus.ContainersGenerated)
{
OnBringItemIntoView(itemsControl, item);
}
else
{
Func<object, object> onBringIntoView =
(o) => OnBringItemIntoView(itemsControl, item);
itemsControl.Dispatcher.BeginInvoke(DispatcherPriority.Loaded,
new DispatcherOperationCallback(onBringIntoView));
}
}
 
private static object OnBringItemIntoView(ItemsControl itemsControl, object item)
{
var element = itemsControl.ItemContainerGenerator.
ContainerFromItem(item) as FrameworkElement;
if (element != null)
{
element.BringIntoView();
}
return null;
}
}
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2010-02-03 14:58:42


Copyright (c) by Christian Moser, 2011.

ItemsControl.html[2/16/2014 2:52:56 PM]


WPF Tutorial | ItemsControl

 Comments on this article

Show all comments

Commented on 12.March 2010

Hello, I just found the coding error when I use this Dependency property tutorial in the .xaml page. I used
Kyaw
separate class for "ItemsControlHelper".

Wunna

These are as follow:

1. The property 'ItemsControlHelper.ScrollToLastItem' does not exist in XML namespace

2. Name 'l.ItemsControlHelper.ScrollToLastItem' is not a valid XAML name.

3. The attachable property 'ItemsControlHelper' was not found in type 'l'.

If possible, please let me know how to fix it. Thanks

Commented on 29.June 2010

it will not work with logical scrolling (VirtualizingStackPanel.IsVirtualizing="True")


Yuri

Commented on 1.July 2010

@Kyaw Wunna

chet
you must reference the namespace
xmlns:l="clr-namespace:[namespace of ItemsControlHelper]"

Commented on 1.July 2010

It can't scroll to the first item ever..cause of scroll the bar will fire
chet
itemsControl.ItemContainerGenerator.StatusChanged several times,one generator.Status ==
GeneratorStatus.ContainersGenerated...why?

Commented on 2.July 2010

Hello,im not able to set ItemsControlHelper.ScrollToLastItem="true"


chinni

Commented on 22.November 2010

hi, how to use AddText method in ItemControl


suji

Commented on 27.December 2010

I think, to make things work, the is a line like

Don
itemsControl.ItemContainerGenerator.StatusChanged = null
missing. Not the finest method to clear the events, but it works.

Nice Text to show the possibillities !

Commented on 12.May 2011

Doesn't work if last item equals to the first, because ContainerFromItem() finds the first item, not the last.

m.n
Using item index instead of item itself, solves the problem:

private static object OnBringItemIntoView(ItemsControl itemsControl, int index)

ItemsControl.html[2/16/2014 2:52:56 PM]


WPF Tutorial | ItemsControl
{

var element = itemsControl.ItemContainerGenerator.ContainerFromIndex(index) as FrameworkElement;

if (element != null)

element.BringIntoView();

return null;

Plus change &quot;object item&quot; to &quot;int index&quot; appropriately.

Name

E-Mail (optional)
Comment

Post Comment

ItemsControl.html[2/16/2014 2:52:56 PM]


WPF Tutorial | LivePreview ComboBox

Home
    Controls
    LivePreview ComboBox Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
ComboBox with Live Preview
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia The Live Preview Pattern


Documents If you are using Microsoft Office 2007 or later, you are familiar with the "live preview" concept. They are using it for all kind of
selections like color, fonttype or fontsize. The idea behind this pattern is to give the user an immediate feedback, how the object
Windows 7
would look like, if he does the selection, without actually doing it. So he can leave the combo and nothing has changed.
Interoperability

Performance
How to use the LivePreviewComboBox Control
Expression Blend
I encapsulated this functionality into a custom control called LivePreviewComboBox that provides an additional dependency
Tools property LivePreviewItem where you can bind to. The following code snipped explains how to use it:

UI Automation  
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:LivePreviewComboBox">
 

LivePreviewComboBox.html[2/16/2014 2:53:38 PM]


WPF Tutorial | LivePreview ComboBox
<StackPanel>
<TextBlock Text="Preview Value:" />
<TextBlock Text="{Binding LivePreviewItem, ElementName=liveBox}" />
<l:LivePreviewComboBox x:Name="liveBox"/>
</StackPanel>
 
</Window>
 
 

Download the LivePreviewCombo Control

  ► Tutorial   ► Flash Player 5   ► Flash SlideShow   ► Adobe Flash

Last modified: 2010-01-13 13:26:02


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 4.June 2010

Its so nice.
Ganesh

Commented on 27.December 2010

Nice!
Don
But i think, OnDropDownOpenChanged - Method is useless ?
If i comment it out, nothing changes

Commented on 7.June 2011

So good,,,

Zakia...
Can you help me?

I make my application by using the comboBox, but I want the items in the comboBox I get from richTextBox,
roughly, how?

Thank's,,,

Commented on 8.June 2011

To Good
Rita

Commented on 13.June 2011

jb
pradeep

Commented on 19.August 2011

LivePreviewComboBox.html[2/16/2014 2:53:38 PM]


WPF Tutorial | LivePreview ComboBox

Nice article. I noticed though, that if you set the IsEditable = true, then ComboBox selected value changes
Fonyuy
along as you select drop down items with the up/down arrow. Is there a way to have the behavior this
implementation currently have, while setting IsEditable = true ?

Name

E-Mail (optional)

Comment

Post Comment

LivePreviewComboBox.html[2/16/2014 2:53:38 PM]


WPF Tutorial | Dialogs

Home
    Controls
    Dialogs Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Dialogs in WPF
Custom Controls

Layout
OK and Cancel Buttons in a Dialog
Input
You have a modal dialog with several buttons on it and you want to automatically close it, when the user presses on some of them. To
Data Binding do this you have to set IsCancel="true" on all buttons that should close the dialog and return false. On one button you set
IsDefault="true" this will be executed when you press [Enter]. It closes the dialog and returns... also false. To return true here
Styling
you have to register a callback that sets the DialogResult to true
Localization
 
Interaction <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
Resources <StackPanel>
<Button Content="Cancel" IsCancel="True" />
2D Graphics
<Button Click="OkClick" Content="Ok" IsDefault="true" />
3D Graphics </StackPanel>
</Window>
Animation  
Multimedia
 
 
private void OkClick(object sender, RoutedEventArgs e)
Documents
{
Windows 7 this.DialogResult = true;
}
Interoperability
 
Performance  

Expression Blend
  ► Tutorial   ► Learn Quick Books   ► Coding Learning   ► Basics
Tools

UI Automation
Last modified: 2009-10-09 16:41:46
Copyright (c) by Christian Moser, 2011.

Dialogs.html[2/16/2014 2:53:51 PM]


WPF Tutorial | Dialogs

 Comments on this article

Show all comments

Commented on 4.February 2010

I got the same exception "DialogResult can be set only after Window is created and shown as dialog"
Doaa
while clicking OK button"

what 's wrong.

Commented on 5.February 2010

You need to call ShowDialog() method of this window class to show it.
Alex Che

Commented on 15.February 2010

While calling DiaLogWindow.ShowDialog()from App.xaml.cs in OnStartup method, when I set


nvs
this.DialogResult = true in OkButton_Click of DiaLogWindow, then complete application is going to
close. So Please let me know the isues here...

Commented on 18.March 2010

if you wanna execute this sample . firstly make other wpf window. secondly make new window
Yisangchol
object(involved this code) and use show() or showdialog() method. thx

Commented on 12.May 2010

You should make other wpf window which include the sample code, and then invoke this dialog in
Maggie
MianWindow.xaml.Just make sure that you've shown the dialog using ShowDialog() rather than Show()
method.

Commented on 3.June 2010

I working in wpf with vb.net , i used this code but a gives exception
rahul
so plz how to used
bhojane

Commented on 21.June 2010

getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
suma
clicking OK button :( ..What to Do

Commented on 1.July 2010

DialogResult:

chet
Gets or sets the dialog result value, which is the value that is returned from the
System.Windows.Window.ShowDialog() method.

So It only can use in the model window

Commented on 6.July 2010

getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
gopichandan
clicking OK button :( ..

Commented on 8.July 2010

Dialogs.html[2/16/2014 2:53:51 PM]


WPF Tutorial | Dialogs
getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
RP
clicking OK button any help

Commented on 19.July 2010

getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
Ramakanta
clicking OK button :( ..

Commented on 27.July 2010

getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
aadsd
clicking OK button :( ..

Commented on 10.August 2010

hey concept is really cool but the code is not working!!! getting an exception for OK and Cancel is not
bindu
working...guys u r true...pls suggest a way to crack this errors

Commented on 12.August 2010

In order to this sample will work,

yossharel
you have to remove the StartupUri="Window1.xaml" from App.xaml and to App.xaml.cs this:

Window1 w = new Window();

w.ShowDialog();

Commented on 12.August 2010

In order to this sample will work,


yossharel
you have to remove the StartupUri="Window1.xaml" from App.xaml and in App.xaml.cs add this:

protected override void OnStartup(StartupEventArgs e)

base.OnStartup(e);

Window1 w1 = new Window1();

w1.ShowDialog();

Commented on 24.October 2010

This dialog tutorial is incomplete. It assums that you have already coded and created a WPF dialog box.
felinis
This is not a simple task. Perform a web search on "WPF dialog" and you will be find plenty of sample
WPF dialogs.

I hope that the remainder of this WPF tutorial is not just a work in progress. So far, things are not
looking good...

Commented on 11.November 2010

Can anybody tell me how to use FolderBrowserDialog in WPF without using


ankita
System.Windows.Forms.FolderBrowserDialog??

Thanks.

Commented on 20.November 2010

Dialogs.html[2/16/2014 2:53:51 PM]


WPF Tutorial | Dialogs
It Is Really Fantastic! Which Gives More Idea About Designing
Minaj

Commented on 22.December 2010

getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
karthik
clicking OK button :(

Commented on 29.December 2010

WPF This site is a waste of time ....


Beginner

Commented on 16.January 2011

this is shite, either do it properly or don't bother


turd burglar

Commented on 19.January 2011

add another page and create the function dialogueresult(). call this function using the object of that
smera
where function defined.

Commented on 27.January 2011

Getting Errer -
Damitha
DialogResult can be set only after Window is created and shown as dialog.

Commented on 25.April 2011

What the code is doing cannot understand


Anurag

Commented on 12.May 2011

How can we handle ESC key. i.e if u press ESC dialog is getting close. how can we stop this.
raju

Name

E-Mail (optional)

Comment

Post Comment

Dialogs.html[2/16/2014 2:53:51 PM]


WPF Tutorial | Slider

Home
    Controls
    Slider Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Slider Control
Custom Controls

Layout
How to Make a Slider Snap to Integer Values
Input
If you just set the Minimum and Maximum of a slider and choose a value the result is determined by the pixel position of the thumb.
Data Binding The value is typically a high-precision value with many decimal places. To allow only integer values you have to set the
IsSnapToTickEnabled property to True.
Styling
<Slider Minimum="0"
Localization
Maximum="20"
Interaction IsSnapToTickEnabled="True"
TickFrequency="2"
Resources  

2D Graphics

3D Graphics

Animation
Last modified: 2009-08-05 13:39:36
Multimedia
Copyright (c) by Christian Moser, 2011.

Documents

Windows 7
 Comments on this article
Interoperability
Show all comments
Performance

Expression Blend Commented on 11.August 2009

This simply will not compile in eclipse. Waste of time.


Tools Rick Hard...

UI Automation
Commented on 12.August 2009

Rick, you could try using common sense and adding the missing '>' yourself, don't you think?
Mark

Slider.html[2/16/2014 2:54:29 PM]


WPF Tutorial | Slider

Commented on 13.August 2009

Ahem.. '/>' actually.. ;)


Nick

Commented on 27.August 2009

Why u people kidding a good guy...


Nithin

Commented on 17.November 2009

isn't this just a snippet anyways... This broke my cobol


Mick

Commented on 22.December 2009

rofl
David

Commented on 5.January 2010

Here, this should work:

su

<Slider Minimum="0" Maximum="20" IsSnapToTickEnabled="True" TickFrequency="2"> </Slider>

Commented on 1.February 2010

Dont u criticize people idiotic mark


Rushin

Commented on 1.February 2010

Dont u criticize people idiotic mark


Navneet

Commented on 10.March 2010

what r u doin man, this is rubbish


nash

Commented on 26.March 2010

Hai,if anybody can send me the tutorial of wpf for beginners


karthik

Commented on 6.May 2010

sure, go here: http://www.wpftutorial.net


Nithin

Commented on 11.August 2010

Im not agree with criticize people, but Im agree with Mark, this missing /> its a very simple error. If
Daniel
you read the previus topics of this tutorial you should correct it by yourself.

Commented on 4.November 2010

lets fuck letss fuckkkkkk


abab

Commented on 4.November 2010

sab indian chutiye


chut

Commented on 2.December 2010

Slider.html[2/16/2014 2:54:29 PM]


WPF Tutorial | Slider

lol
bbbbbbbbbbbb...

Commented on 8.December 2010

Good comments from Educated people


Suhasis

Commented on 16.December 2010

good site
Happy

Commented on 21.December 2010

Not satisfied with this example.

Aarti Varadkar
Check out this link for WPF Slider control:http://nayyeri.net/slider-control-in-windows-presentation-
foundation

Commented on 20.March 2011

If a developer needs to get each information in detail it is better to keep your hands of.
Martin
Thanks Christian to spend your time for us...

Commented on 21.March 2011

I think these are very minor errors, and they are not by his fault, this is because of that HTML Box on
Developer
which Overflow property is hidden. Try to concentrate on what he is going to teach you. Also, if you
are so perfect then buy a domain and make a website like him but with no errors in the code. But
you dont know anything so you are just making fun by these stupid things.

Commented on 15.April 2011

Please give the brief description about the SLIDER.


Kaushal

Commented on 8.June 2011

Doesn't work in IE8.


Rick

Commented on 18.August 2011

can u give more details about slider.. i searched it on the internet but does not found a good
Waseem
example

Name

E-Mail (optional)

Comment

Post Comment

Slider.html[2/16/2014 2:54:29 PM]


WPF Tutorial | Popup

Home
    Controls
    Popup Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Popup Control
Custom Controls
Introduction follows...
Layout

Input
How to make the popup close, when it loses focus
Data Binding
Just set the StaysOpen property to False. Unfortunately this is not the default behavior
Styling
 
Localization <Popup StaysOpen="False" />
 
Interaction
 
Resources

2D Graphics   ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

3D Graphics

Animation Last modified: 2011-03-07 17:50:02


Copyright (c) by Christian Moser, 2011.

Multimedia

Documents
 Comments on this article
Windows 7

Interoperability Show all comments

Performance Commented on 12.July 2009

Expression Blend To make a popup control visible, you need to set IsOpen property to true.

Sumit
IsOpen="True"

Tools

UI Automation
Covered in detail at : http://www.c-
sharpcorner.com/UploadFile/mahesh/WPFPopup08172008075339AM/WPFPopup.aspx

Commented on 20.July 2009

Popup.html[2/16/2014 2:54:42 PM]


WPF Tutorial | Popup
How to make the Popup control able to drag and drop like a window?
Eric

Commented on 12.September 2009

explain in detail please..................


pankaj

Commented on 18.September 2009

It's nice..

Kalpesh
Kalpesh

Vekaria
http://www.tatvasoft.com/

Commented on 10.December 2009

Not clear Staysopen is not available..

Anand

Commented on 31.December 2009

@_@ what is this? :|


name

Commented on 18.January 2010

it's great.

Elan...
http://www.elantechnologies.com

Commented on 28.May 2010

Dear All,

Nitin Sharma

http://www.c-sharpcorner.com/UploadFile/mahesh/WPFPopup08172008075339AM/WPFPopup.aspx

Visit this website to implement Popup.

Commented on 23.June 2010

Great Work and great stuff... Thanks

Ramu

dotnetwithexamples.blogspot.com

Commented on 21.July 2010

its good
Ebha

Commented on 17.February 2011

explain detail plz............


Naushad

Commented on 15.June 2011

EXPLAIN DETAILS WHY WE ARE GIVING TRUE AND FALSE...


Shreelakshmi

Commented on 21.June 2011

This is the most useful article i\'ve ever read.


Bob

Commented on 22.July 2011

Popup.html[2/16/2014 2:54:42 PM]


WPF Tutorial | Popup

If u set the property IsOpen = True then the popup will be Opened

sasi
and,if IsOpen = False then the Popup will be closed

Name

E-Mail (optional)

Comment

Post Comment

Popup.html[2/16/2014 2:54:42 PM]


WPF Tutorial | RadioButton

Home
    Controls
    RadioButton Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Radio Button
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia
Introduction
Documents The RadioButton control has its name from old analog radios which had a number of programmable station buttons. When you
pushed one in, the previosly selected poped out. So only one station can be selected at a time.
Windows 7
The RadioButton control has the same behavior. It lets the user choose one option out of a few. It the list of options gets longer,
Interoperability
you should prefer a combo or list box instead.
Performance To define which RadioButtons belong togehter, you have to set the GroupName to the same name.
Expression Blend To preselect one option set the IsChecked property to True.
Tools

UI Automation  
<StackPanel>
<RadioButton GroupName="Os" Content="Windows XP" IsChecked="True"/>
<RadioButton GroupName="Os" Content="Windows Vista" />
<RadioButton GroupName="Os" Content="Windows 7" />

RadioButton.html[2/16/2014 2:55:18 PM]


WPF Tutorial | RadioButton
<RadioButton GroupName="Office" Content="Microsoft Office 2007" IsChecked="True"/>
<RadioButton GroupName="Office" Content="Microsoft Office 2003"/>
<RadioButton GroupName="Office" Content="Open Office"/>
</StackPanel>
 
 

How to DataBind Radio Buttons in WPF


The radio button control has a known issue with data binding. If you bind the IsChecked property to a boolean and check the
RadioButton, the value gets True. But when you check another RadioButton, the databound value still remains true.

The reason for this is, that the Binding gets lost during the unchecking, because the controls internally calls ClearValue() on the
dependency property.
 
<Window.Resources>
<EnumMatchToBooleanConverter x:Key="enumConverter" />
</Window.Resources>
 
 
<RadioButton Content="Option 1" GroupName="Options1"
IsChecked="{Binding Path=CurrentOption, Mode=TwoWay,
Converter={StaticResource enumConverter},
ConverterParameter=Option1}" />
<RadioButton Content="Option 2" GroupName="Options2"
IsChecked="{Binding Path=CurrentOption, Mode=TwoWay,
Converter={StaticResource enumConverter},
ConverterParameter=Option2}" />
<RadioButton Content="Option 3" GroupName="Options3"
IsChecked="{Binding Path=CurrentOption, Mode=TwoWay,
Converter={StaticResource enumConverter},
ConverterParameter=Option3}" />
 
 
 
public class EnumMatchToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return false;
 
string checkValue = value.ToString();
string targetValue = parameter.ToString();
return checkValue.Equals(targetValue,
StringComparison.InvariantCultureIgnoreCase);
}
 
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return null;
 
bool useValue = (bool)value;

RadioButton.html[2/16/2014 2:55:18 PM]


WPF Tutorial | RadioButton
string targetValue = parameter.ToString();
if (useValue)
return Enum.Parse(targetType, targetValue);
 
return null;
}
}
 
 

  ► Tutorial   ► Flash Player 5   ► Flash SlideShow   ► Adobe Flash

Last modified: 2010-08-26 20:42:54


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 8.March 2010

Thank you, this example is just what I needed and nothing more. The people who don't understand
Carlos
need more background reading. Perhaps read about MVVM so the binding, converter make sense.

Commented on 18.March 2010

This tutorial is worth pure gold! Just what I needed.


Andreas

Commented on 2.April 2010

Very good! Just what I needed.


Olion242

Commented on 11.May 2010

Amazaed to see so many dumb People. They are reading this and they dont know what data binding is.

Praveen

It would have been better for lame user to understand if it had the solution/source code file with this in
zip.

Commented on 11.May 2010

Amazaed to see so many dumb People. They are reading this and they dont know what data binding is.

Praveen

It would have been better for lame user to understand if it had the solution/source code file with this in
zip.

Commented on 12.May 2010

Thanks Robert and Adam for making it work :)


Danube210

Commented on 3.June 2010

It's usefule. but not details explination

rahul
Great thanks

RadioButton.html[2/16/2014 2:55:18 PM]


WPF Tutorial | RadioButton
bhojane

Commented on 5.June 2010

Uh... to all the people saying "if people don't understand, too bad, figure it out yourself"

Caleb

This is a TUTORIAL. The purpose of which is to teach. If it doesn't fulfill it's purpose, whats the point? If
you're so smart, why are you looking up tutorials? Shouldn't you all "figure it out yourself"?

Commented on 14.June 2010

This worked well for me. You just have to remember to fire a PropChanged event in the set path of
Robert
CurrentOption property (which is of type enum and not string as suggested, above).

Commented on 16.June 2010

Hi can any one tell me how to enable/disable a button by select a checkbox. :)

atul

Commented on 24.June 2010

This was very useful.


Phill

Effectively the built-in radiobutton functionality is not used at all really (the radiobuttons are all in their
own group and the mutual exclusivity is an effect of the binding).

In the end I varied from the example a bit in that I found it safer to isolate each RadioButton from the
others by putting each within its own parent (ie each in its own StackPanel) and not setting a
GroupName at all. The use of GroupName was an issue for me when multiple copies of the same view
where shown within a docking window...ie the radiobuttons from different view instances were
interfering with each other.. this is not an issue when using a different parent for each radiobutton as a
means of seperating them into different groups...

Commented on 19.July 2010

I am terribly confused by this tutorial. I followed the instructions exactly, but my databound value is not
Alexander B
being updated when the radio buttons are clicked. Similarly, when I set all of the Group names to be
identical, the unselected radio buttons become red bordered.

Commented on 26.August 2010

I believe one issue with having to use multiple group names is that the tabbing behavior does not
Todd Fisher
operate correctly. If one of the radio buttons is set, the tab key should move you out of the group.
However, since we have mutiple group names, we move to the next radio button.

Commented on 30.August 2010

Hi,

swapnil

Got the things implemented in tutorial.

Can we pass the content of radio button to converter class some how?

My requirement is that i want to get text of radiobutton just checked in the view model

Please help me out with this.

Thanks in advance.

Swapnil

RadioButton.html[2/16/2014 2:55:18 PM]


WPF Tutorial | RadioButton

Commented on 30.August 2010

Hi,

swapnil

Got the things implemented in tutorial.

Can we pass the content of radio button to converter class some how?

My requirement is that i want to get text of radiobutton just checked in the view model

Please help me out with this.

Thanks in advance.

Swapnil

Commented on 5.September 2010

@Alexander B,

Lee D

The red border is appearing because the ConvertBack is [correctly] returning null - which I believe WPF
is interpreting as a validation error (trying to set an enum value i.e. the bound property, to null). After
fighting with this myself the last two days, I found that if you simply redefine the
Validation.ErrorTemplate for the RadioButton to be empty than you can remove the red border.

So, in a style that's applied to your RadioButtons:

<Setter Property="Validation.ErrorTemplate">

<Setter.Value>

<ControlTemplate>

</ControlTemplate>

</Setter.Value>

</Setter>

Lee.

Commented on 27.November 2010

"If you bind the IsChecked property to a boolean and check the RadioButton, the value gets True. But
starbros47
when you check another RadioButton, the databound value still remains true." I am using WPF 4.0 with
.net 4.0, this issue is fixed.

Commented on 15.January 2011

Hi, first thanks a lot. But I've got a little problem, I have a tabControl and each tabItem have a different
Enhakiel
opacity, on right click it open a context menu with radion button witch allow to change it, everything
goes right, on each tabControl radiobutton is set to the correct value, but as soon as I changed a value
(it's correctly set) if I click on another tabItem (the opacity is still ok) the context menu show the opacity
I've set the the last one... have you got a solution? Thank you in advance

Commented on 8.February 2011

I've tried this technique and it does not work at all. Instead it simply allows any radio button to be
Ristogod
checked, and it cannot be unchecked. So after clicking on each radio button, they all eventually get
checked with no way to undo it.

Also, the ConvertBack never occurs. This because the Binding on IsChecked mysteriously disappears.

RadioButton.html[2/16/2014 2:55:18 PM]


WPF Tutorial | RadioButton
I'm using version 4.0. And I've yet to find a working solution to this problem.

Commented on 28.March 2011

This is great article. You also need to elaborate that we need to implement INotifyPropertyChanged for
Tuan
the data source class in order to trigger other radio buttons to update themselves, so that the mutual
Nguyen
exclusivity is in effect.

Commented on 20.June 2011

Your example works to an extent, but now I am totally spooked with using RadioButton and databinding.
Dan
Even with .NET 4.0, I think Microsoft still has some bugs here. If your example is used in a UserControl
and more than one instance is created, it often fails to remember which radio button is supposed to be
checked as the usercontrols gain and lose focus. Really strange... I'm steering clear of using this control
with data binding in any form or fashion.

Commented on 21.June 2011

Your example works to an extent, but now I am totally spooked with using RadioButton and databinding.
Dan
Even with .NET 4.0, I think Microsoft still has some bugs here. If your example is used in a UserControl
and more than one instance is created, it often fails to remember which radio button is supposed to be
checked as the usercontrols gain and lose focus. Really strange... I'm steering clear of using this control
with data binding in any form or fashion.

Commented on 21.June 2011

Your example works to an extent, but now I am totally spooked with using RadioButton and databinding.
Dan
Even with .NET 4.0, I think Microsoft still has some bugs here. If your example is used in a UserControl
and more than one instance is created, it often fails to remember which radio button is supposed to be
checked as the usercontrols gain and lose focus. Really strange... I'm steering clear of using this control
with data binding in any form or fashion.

Commented on 29.June 2011

Thank you! That was awesome :)


Jamie

Commented on 18.September 2011

This is goodl example but I found a bug.

Shai
Let's say you have 3 different options in a Radio Button list. If you select option 1, then option 2, and
option 3, it works. But now if you go back and select option1, your view do not communicate with
ViewModel. Any suggestion on this issue?

Name

E-Mail (optional)

Comment

Post Comment

RadioButton.html[2/16/2014 2:55:18 PM]


WPF Tutorial | ToolTips

Home
    Controls
    ToolTips Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
ToolTips in WPF
Custom Controls

Layout

Input

Data Binding

Styling

Localization  
<Button Content="Submit">
Interaction <Button.ToolTip>
<ToolTip>
Resources
<StackPanel>
2D Graphics <TextBlock FontWeight="Bold">Submit Request</TextBlock>
<TextBlock>Submits the request to the server.</TextBlock>
3D Graphics
</StackPanel>
Animation </ToolTip>
</Button.ToolTip>
Multimedia </Button>
 
Documents
 
Windows 7
How to show ToolTips on disabled controls
Interoperability
When you disable a control with IsEnabled=False the tooltip does not show anymore. If you want to have the tooltip appear
Performance
anyway you have to set the attaached property ToolTipService.ShowOnDisabled to True.
Expression Blend
 
Tools <Button IsEnabled="False"
ToolTip="Saves the current document"
UI Automation ToolTipService.ShowOnDisabled="True"
Content="Save">
</Button>
 
 

ToolTip.html[2/16/2014 2:55:30 PM]


WPF Tutorial | ToolTips

How to change the show duration of a ToolTip


The static class ToolTipService allows you to modify the show duration of the tooltip

 
<Button ToolTip="Saves the current document"
ToolTipService.ShowDuration="20"
Content="Save">
</Button>
 
 

  ► Tutorial   ► ActionScript   ► Flash CS3   ► Flash 9


Last modified: 2009-06-27 18:48:48


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 18.June 2009

Hun too Yae baat hai


DON

Commented on 26.June 2009

Hi Christian, Can we modify the tooltip content and make like a content presenter, like office 2007
Tormentor
tooltips for an example(Header, Description, image, etc...)?

Commented on 12.July 2009

Nice tutorial , good that it includes tooltipservice : http://msdn.microsoft.com/en-


Sumit
us/library/system.windows.controls.tooltipservice(VS.95).aspx

Commented on 7.September 2009

Hi Christian

Bolshoi Booze

Is it possible to have something like below:

<Style TargetType="{x:Type ...}">

<MultiDataTrigger>

<MultiDataTrigger.Conditions>

<Condition .. />

<Condition .. />

</MultiDataTrigger.Conditions>

<Setter Property="ToolTip>

<Setter.Value>

<Grid>

...[Custom Content such as images, textblocks etc]...

</Grid>

ToolTip.html[2/16/2014 2:55:30 PM]


WPF Tutorial | ToolTips
</Setter.Value>

</Setter>

</MultiDataTrigger>

</Style>

When I do this I get a below exception:

Exception Cannot add content of type 'System.Windows.Controls.Grid' to an object of type


'System.Object'.

Thanks

Commented on 7.September 2009

Hi Christian

Bolshoi Booze

Is it possible to have something like below:

<Style TargetType="{x:Type ...}">

<MultiDataTrigger>

<MultiDataTrigger.Conditions>

<Condition .. />

<Condition .. />

</MultiDataTrigger.Conditions>

<Setter Property="ToolTip>

<Setter.Value>

<Grid>

...[Custom Content such as images, textblocks etc]...

</Grid>

</Setter.Value>

</Setter>

</MultiDataTrigger>

</Style>

When I do this I get a below exception:

Exception Cannot add content of type 'System.Windows.Controls.Grid' to an object of type


'System.Object'.

Thanks

Commented on 8.September 2009

Hi Bolshoi,

Christian
there are two problems in your approach. The property "tooltip" that you are trying to set requires an
Moser
object of type tooltip. So you need to warp your <Grid> into a <Tooltip> element.
The second problem is that a style is something like a singleton. It's only created once and applied
multiple times. This means that if you include wpf elements in a style you have to add the
x:Shared="False" attribute to the style.

I hope this helps you.

Greetings

Christian

ToolTip.html[2/16/2014 2:55:30 PM]


WPF Tutorial | ToolTips

Commented on 3.December 2009

simple and working


Rajagopal

Commented on 12.January 2010

Great Work !!!


M Islam

Commented on 16.January 2010

Great, its simple and easy to learn....


Jawahar

Commented on 17.February 2010

ToolTipService.ShowDuration is in Milliseconds, so "20" might not be the best example.


Heinzi

Commented on 9.April 2010

You are Man!


Victor

Commented on 20.May 2010

Suoerb Piece of Code


CoolDev

Commented on 12.August 2010

I dont have visual studio in this computer so I have to ask... Can I show an image inside the tooltip? If I
Daniel
add an Image tag inside the StackPanel should work??? The code should be like this:

<Button Content="Submit">

<Button.ToolTip>

<ToolTip>

<StackPanel>

<image ... />

<TextBlock FontWeight="Bold">Submit Request</TextBlock>

<TextBlock>Submits the request to the server.</TextBlock>

</StackPanel>

</ToolTip>

</Button.ToolTip>

</Button>

Im ok or is another way to have an image in the tooltip?

Commented on 21.August 2010

Hi

someone
How can I set this tooltip (with stackpanel etc) in style file?

I made my style for textbox

<Style x:Key="DefaultStyle" TargetType="{x:Type TextBox}">

<Setter Property="FontFamily" Value="Tahoma"/>

<Setter Property="FontSize" Value="15"/>

<Setter Property="VerticalContentAlignment" Value="Center"/>

<Setter Property="TextAlignment" Value="Center"/>

<Setter Property="TextWrapping" Value="Wrap"/>

<Setter Property="BorderBrush" Value="#A9C2DE"/>

<Setter Property="BorderThickness" Value="1"/>

ToolTip.html[2/16/2014 2:55:30 PM]


WPF Tutorial | ToolTips
<Setter Property="Background">

<Setter.Value>

<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1" >

<GradientStop Color="#CDE1F7" Offset="0.01"/>

<GradientStop Color="#DFECFA" Offset="0.8" />

</LinearGradientBrush>

</Setter.Value>

</Setter>

<Setter Property="ToolTip">

<Setter.Value>

<StackPanel>

<TextBlock Text="Nice toolbox"/>

<TextBlock Text="Nice tooltip"/>

</StackPanel>

</Setter.Value>

</Setter>

</Style>

But I get xaml parse exception error if I use this style. Is it possible to set this tooltip in style file?

Commented on 14.September 2010

Nice Explanation..
durga

Commented on 23.October 2010

Brevity is the soul of wit!! To the point and perfect sample


Girish Jain

Commented on 22.January 2011

I love this, great tip. Nice example. Thanks!


El Matador

Commented on 28.January 2011

I'm also interested in styled tooltips like commentator from "21.August 2010"
Alex

Commented on 29.January 2011

Aldha Nice article, simple and good sample for my project. AH


Qhurbaini

Commented on 24.March 2011

How to apply image to button.


Kaustubh...

Commented on 29.March 2011

Nice sample
Sanjay Patolia

Commented on 1.April 2011

Wonderful!
YuZhoufeng

Commented on 23.April 2011

ToolTip.html[2/16/2014 2:55:30 PM]


WPF Tutorial | ToolTips

Hey really grt ... Thanks a lot


Tejas

Commented on 4.May 2011

Hi Christian

Naren

All your examples are really great.I want to know whether there is any control to display text along
with images in between(images such as graphs and diagrams). If there is no control, then please mail
me how to create a control to satisfy this. If possible mail the code for creating such a control.

Thanks

Commented on 30.June 2011

Hi Christian, is it possible to put clickable button inside tooltip?

Terry
This xaml displays button but you can't click on it.

Thanks

Terry

Ex:

&lt;ComboBox.ToolTip&gt;

&lt;ToolTip Placement=&quot;Center&quot; Focusable=&quot;True&quot;


StaysOpen=&quot;True&quot;&gt;

&lt;Button Content=&quot;button inside tool tip&quot; Focusable=&quot;True&quot;


Click=&quot;Button_Click_1&quot; /&gt;

&lt;/ToolTip&gt;

&lt;/ComboBox.ToolTip&gt;

Name

E-Mail (optional)

Comment

Post Comment

ToolTip.html[2/16/2014 2:55:30 PM]


WPF Tutorial | TextBox

Home
    Controls
    TextBox Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF TextBox
Custom Controls

Layout
How to enable spell checking
Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7 TextBox and RichTextBox provide an out-of-the-box spell checking functionality. It is available for the following languages: English,
Spanish, German and French. It can be enabled by setting the attached property SpellCheck.IsEnabled to true.
Interoperability
 
Performance
<TextBox SpellCheck.IsEnabled="True" Language="en-US" />
Expression Blend  
 
Tools

UI Automation
How to validate input
By using a regular expression, you can easily limit and validate the input of the user. The following code snippet shows how to do it:

 
protected override void OnTextInput(TextCompositionEventArgs e)

TextBox.html[2/16/2014 2:55:46 PM]


WPF Tutorial | TextBox
{
string fullText = Text.Remove(SelectionStart, SelectionLength) + e.Text;
if (_regex != null && !_regex.IsMatch(fullText))
{
e.Handled = true;
}
else
{
base.OnTextInput(e);
}
}
 
 

Last modified: 2010-06-11 10:49:42


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 21.April 2010

i have loaded data from XML file to treeview.i want to get the id of selected treeview item when we click
Abhijiit...
on any treeview item.and it shold be displayed in testbox.

pls help me..

thnks

Commented on 21.April 2010

i have loaded data from XML file to treeview.i want to get the id of selected treeview item when we click
Abhijiit...
on any treeview item.and it shold be displayed in testbox.

pls help me..

thnks

Commented on 8.May 2010

this is good .
ebrahimi
thanks .

Commented on 23.August 2010

Its funny that you guys find my articles so helpful considering I just copy and pasted random shit from
MOSER
other random sites that I found. Its all good though because those google ads are making me cash!!!

ps. you can stop me

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
Christian
from another website

TextBox.html[2/16/2014 2:55:46 PM]


WPF Tutorial | TextBox

Commented on 8.September 2010

Give him a break. Even if some of it is copy and paste, it's laid out very nicely with nice graphics
andy
screenshots.

And what google ads?

Commented on 20.October 2010

hi! I need detect when user pulse intro, Someone knows how to do this? I'm using mvvm
Victor

Commented on 3.February 2011

shibasish its good.......


jena

Commented on 18.February 2011

I Heart fully,

Ayyappan
Thank you for your nice Material

warm regards,
Ayyappan,
Software Engineer ,

Chennai,
Tamil Nadu.

http://www.banyansoft.blogspot.com/

Commented on 2.May 2011

Nice articles for me.

Javed Khan
thanks

Commented on 10.May 2011

XML Content does not work at all.

Alexander
Regards

Commented on 28.May 2011

ray this is what I was needed thanx


akkanson

Commented on 3.August 2011

Useless! you should tell us how WPF controls are different from asp controls and should tell us that what
Monika
are there properties and how properties works. I always open this link when i have to check some
properties or how control is but never find anything. Please change the name of ths website &quot;WPF
Tutorial&quot;

Commented on 5.September 2011

I'm using VS-2008[Framework 3.5]. Spell checking functionality perfectly works for English language. But
Karthik
it&acirc;��s not working with Spanish, German and French language dictionaries. Please guide me
and where I&acirc;��m making the mistake. Following language code are used in my application.

TextBox.html[2/16/2014 2:55:46 PM]


WPF Tutorial | TextBox
English = &quot;en-US&quot; [Working]

German = &quot;de-DE&quot; [Not Working]

French = &quot;fr-FR&quot; [Not Working]

Name

E-Mail (optional)

Comment

Post Comment

TextBox.html[2/16/2014 2:55:46 PM]


WPF Tutorial | Menus

Home
    Controls
    Menus Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Menus in WPF
Custom Controls

Layout
Menu
Input
The Menu control derives from HeaderedItemsControl. It stacks it items horizontally and draws the typical gray background. The
Data Binding only property that the Menu adds to ItemsControl is the IsMainMenu property. This controls if the menu grabs the focus if the
user presses F10 or the ALT key.
Styling

Localization

Interaction
 
Resources
<Menu IsMainMenu="True">
2D Graphics <MenuItem Header="_File" />
<MenuItem Header="_Edit" />
3D Graphics <MenuItem Header="_View" />
<MenuItem Header="_Window" />
Animation
<MenuItem Header="_Help" />
Multimedia </Menu>
 
Documents  
Windows 7
MenuItem
Interoperability
The MenuItem is a HeaderedItemsControl. The content of the Header property is the caption of the menu. The Items of a
Performance
MenuItems are its sub menus. The Icon property renders a second content on the left of the caption. This is typically used to draw a
Expression Blend little image. But it can be used for type of content.

Tools
You can define a keyboard shortcut by adding an underscore in front of a character.

UI Automation

Menus.html[2/16/2014 2:56:21 PM]


WPF Tutorial | Menus

 
<MenuItem Header="_Edit">
<MenuItem Header="_Cut" Command="Cut">
<MenuItem.Icon>
<Image Source="Images/cut.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="_Copy" Command="Copy">
<MenuItem.Icon>
<Image Source="Images/copy.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="_Paste" Command="Paste">
<MenuItem.Icon>
<Image Source="Images/paste.png" />
</MenuItem.Icon>
</MenuItem>
</MenuItem>
 
 

Checkable MenuItems
You can make a menu item checkable by setting the IsCheckable property to true. The check state can be queried by the
IsChecked property. To get notified when the check state changes you can add a handler to the Checked and Unchecked
property.

 
<MenuItem Header="_Debug">
<MenuItem Header="Enable Debugging" IsCheckable="True" />
</MenuItem>
 
 

Separators
Separator is a simple control to group menu items. It's rendered as a horizontal line. It can also be used in ToolBar and
StatusBar.

Menus.html[2/16/2014 2:56:21 PM]


WPF Tutorial | Menus

 
<Menu>
<MenuItem Header="_File">
<MenuItem Header="_New..." />
<Separator />
<MenuItem Header="_Open..." />
<Separator />
<MenuItem Header="_Save" />
<MenuItem Header="_Save As..." />
<Separator />
<MenuItem Header="_Exit" />
</MenuItem>
</Menu>
 
 

Callbacks
You can register a callback to any menu item by adding a callback to the Click event.

 
<Menu>
<MenuItem Header="_File">
<MenuItem Header="_New..." Click="New_Click"/>
</MenuItem>
</Menu>
 
 
 
private void New_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("You clicked 'New...'");
}
 
 

How to bind MenuItems dynamically using MVVM


If you are using the model-view-viewmodel pattern, you probably want to define the available menu command dynamically in your
code and then bind them to a MenuItem control. The following sample shows you how to do this:

 
<Menu>
<Menu.Resources>
<Style x:Key="ThemeMenuItemStyle" TargetType="MenuItem">

Menus.html[2/16/2014 2:56:21 PM]


WPF Tutorial | Menus
<Setter Property="Header" Value="{Binding Name}"></Setter>
<Setter Property="Command" Value="{Binding ActivateCommand}"/>
<Setter Property="IsChecked" Value="{Binding IsActive}" />
<Setter Property="IsCheckable" Value="True"/>
</Style>
</Menu.Resources>
<MenuItem Header="Themes" ItemsSource="{Binding Themes}"
ItemContainerStyle="{StaticResource ThemeMenuItemStyle}" />
</Menu>
 
 

Keyboard Shortcuts
To add a keyboard shortcut to a menu item, add a underscode "_" in front of the caracter you want to use as your hot key. This
automatically sets the InputGestureText to an appropriate value. But you can also override the proposed text by setting this
property to a text of your choice.

  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Web Design Books

Last modified: 2010-07-21 10:14:30


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 13.December 2010

What do I need to do if I want the Help menu item on the right-hand side?
Victor

Commented on 15.December 2010

Thanks!!
bar

Commented on 1.January 2011

Awesome tutorial !!!!!!!!

Mehul
Very Helpful
Special Thanks !!!!!!!!!

Commented on 21.January 2011

Nice.. Thanks!
esha

Commented on 11.February 2011

Hey Christian,

Shweta Patel

There is one suggestion or i can say request to u.

Why dont u keep "Ask -- Reply" mechanism here instead of comments, or along with comments. So that
it becomes easy to find answers for doubts.

Menus.html[2/16/2014 2:56:21 PM]


WPF Tutorial | Menus
This was just a suggestion only.

Other wise everything is perfect.

Commented on 16.February 2011

Really very nice Articles

Jitendra

thanks

Commented on 16.February 2011

Really very nice Articles

Jitendra

thanks

Commented on 11.March 2011

Very nice article.


Kiransinh

Commented on 13.March 2011

thanks a lot! really helpful :)


mr e

Commented on 14.March 2011

@Tony, you can set up the menu item collection by going to the 'properties' of the control in design
DavidW
view, finding the 'Items' property which is a (Collection) and clicking on the [...] button.

Commented on 24.March 2011

Perfectly Explained. Well done. Thank you


Stephen

Commented on 18.April 2011

awesome Article man ....


Manish

Commented on 22.April 2011

Thanks because this is very good for learning to a beginner.

vinay
and there is define in both language XML and C#.

Again Thanks.

Commented on 11.May 2011

I don't know what I've missed, but all my subitems of a meny at run time are disabled besides the main
Alexander
menu. I've assigned everywhere IsEnabled proprty to &quot;True&quot;. But no success. Besides this,
the access to the code area from design mode to the subitems of menu is not possible, again access
available just to the main menu items

Commented on 8.June 2011

thanks, can you more write a use wcf with x509?


Mr.Truong

Commented on 1.July 2011

Menus.html[2/16/2014 2:56:21 PM]


WPF Tutorial | Menus
IMPORTANT! The following line and similar ones gave me an error...

Jesse B
&lt;MenuItem Header=&quot;_Copy&quot; Command=&quot;Copy&quot;&gt;

In Visual Studio 2008, it is actually:

&lt;MenuItem Header=&quot;_Copy&quot; Click=&quot;Paste_Click&quot;&gt;

You then right click on Paste_Click and select &quot;Navigate to Event Handler&quot;.

Commented on 9.July 2011

Thanks
Deepak

Commented on 11.July 2011

Greetings to all. I found very interesting this mini tutorial. I would suggest an idea. What do you think to
Felipe
create another tutorial on creating menus more stylized, like those that Word 2010 and Excel 2010 are
currently using?

Commented on 26.July 2011

Hola soy nueva en esto tengo una duda...Es posible llamar un MainWindow de un submenu como se
izel
isiera en un windownForm

Commented on 28.July 2011

Thamk you!
Designer_my

Commented on 20.August 2011

That's helpful, thanks.


Daniex

Commented on 30.August 2011

nice written
babu

Commented on 1.September 2011

Having spent 3 hours trying to attach an image to a MenuItem, discovered that there is a bug in VS
Peter Farrer
2008 and 2010, you simply need to close Visual Studio and reopen it.

The XAML error message you get is The file 'x' is not part of the project or its 'Build Action' property is
not set to 'Resource'

Commented on 8.September 2011

Awesome! Mega cool.


Awesomer

Commented on 27.September 2011

how to give the effective look for window in Wpf

saber

Name

E-Mail (optional)

Comment

Menus.html[2/16/2014 2:56:21 PM]


WPF Tutorial | Menus

Post Comment

Menus.html[2/16/2014 2:56:21 PM]


WPF Tutorial | Expander

Home
    Controls
    Expander Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Expander Control
Custom Controls

Layout
Introduction
Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics The Expander control is like a GroupBox but with the additional feature to collapse and expand its content. It derives from HeaderedContentControl
so it has a Header property to set the header content, and a Content property for the expandable content.
Animation
It has a IsExpanded property to get and set if the expander is in expanded or collapsed state.
Multimedia
In collapsed state the expander takes only the space needed by the header. In expanded state it takes the size of header and content together.
Documents
 
Windows 7 <Expander Header="More Options">
Interoperability
<StackPanel Margin="10,4,0,0">
<CheckBox Margin="4" Content="Option 1" />
Performance <CheckBox Margin="4" Content="Option 2" />
<CheckBox Margin="4" Content="Option 3" />
Expression Blend
</StackPanel>
Tools </Expander>
 
UI Automation  

Last modified: 2010-02-08 12:27:56


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Expander.html[2/16/2014 2:56:48 PM]


WPF Tutorial | Expander

Show all comments

Commented on 23.February 2010

this man "me" is Crazy!!!


Hey!!

Commented on 25.February 2010

Cool tutorial , really liked it.


Amit

Commented on 7.March 2010

The Tutorial was not a tutorial, but there were some interesting comments on what posters wanted and possible
mike c
solutions.

Commented on 6.April 2010

nice work
chintu

Commented on 12.April 2010

Nice Article. But how to make the expander to expand and close slowly. kindly help
Ismail

Commented on 11.May 2010

How does one make the the header a gray color so one can tell it apart from the other content?
Xarzu

Commented on 13.May 2010

I followed the tutorial as said but its still giving me problems.Instead of the expander when expanded to push other expanders
Bally
down, and closes the gap when collapsed.It expands but on others.Please how can i make it push other expanders down
when it expands and pull the expanders back to their position when it collapses. Are there any properties that can be modified
to make it work?

Here is my sample code using Expression Blend 3.

<Window

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"

mc:Ignorable="d" xmlns:chartingToolkit="clr-
namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

x:Class="WpfApplication1.MainWindow"

x:Name="Window"

Title="MainWindow" WindowStartupLocation="CenterScreen" WindowState="Maximized">

<Window.ContextMenu>

<ContextMenu/>

</Window.ContextMenu>

<Grid x:Name="LayoutRoot">

<StackPanel>

<Expander VerticalAlignment="Top" Header="Expander" Width="Auto" Height="Auto" ExpandDirection="Down"


HorizontalAlignment="Left">

<Canvas>

<Grid>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="0.342*"/>

<ColumnDefinition Width="0.658*"/>

Expander.html[2/16/2014 2:56:48 PM]


WPF Tutorial | Expander
</Grid.ColumnDefinitions>

<Label Margin="0,0,-0.001,0" Content="Label" d:LayoutOverrides="Width, Height"/>

<Button HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Content="Button" Margin="0,38,0,0"/>

<CheckBox HorizontalAlignment="Left" VerticalAlignment="Bottom" Content="CheckBox" Margin="0,0,0,-19.96"


d:LayoutOverrides="VerticalAlignment"/>

</Grid>

</Canvas>

</Expander>

<Expander VerticalAlignment="Top" Header="Expander" Width="Auto" Height="Auto" ExpandDirection="Down"


HorizontalAlignment="Left">

<Canvas>

<Grid>

<Grid.ColumnDefinitions>

<ColumnDefinition Width="0.342*"/>

<ColumnDefinition Width="0.658*"/>

</Grid.ColumnDefinitions>

<Label Margin="0,0,-0.001,0" Content="Label" d:LayoutOverrides="Width, Height"/>

<Button HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Content="Button" Margin="0,38,0,0"/>

<CheckBox HorizontalAlignment="Left" VerticalAlignment="Bottom" Content="CheckBox" Margin="0,0,0,-19.96"


d:LayoutOverrides="VerticalAlignment"/>

</Grid>

</Canvas>

</Expander>

</StackPanel>

</Grid>

</Window>

Commented on 10.June 2010

Gary, I came here looking to check that an Expander did what I thought it might do, and the syntax of how to use
Liz
it. Perfect. Thanks!

Commented on 8.July 2010

I want to know can we change the position of exapnder pointer without effecting the internal things in expander
Vishal Pandit

Commented on 31.August 2010

I, too, got what I needed.


Phil R

Commented on 21.December 2010

Aarti Nice One


Varadkar

Commented on 22.December 2010

I also found this useful, thank you!


Gmac

Commented on 29.December 2010

I want to create expander dynamically and want to add groupbox into it.

Yo

using expander.content = textbox is working fine. but wen i add group box it doesnot work,

Commented on 29.December 2010

Great Tutorial. Is it possible to have an expander bump other elements out of the way when it is expanded? for
Drew
instance if the collapsed expander is next to a listview, when you click to expand can it move the listview over?
probably isnt possible but thought id ask. thanks

Expander.html[2/16/2014 2:56:48 PM]


WPF Tutorial | Expander

Commented on 16.February 2011

bollocks
Bob

Commented on 2.March 2011

Like Expandable Panel...Very Impressive.


Rahul

Commented on 6.April 2011

This Site is very Helpful for me...Thanks


Chetan

Commented on 16.April 2011

this is the good article but not professional


mohammad...

Commented on 16.April 2011

this site is very very benefit. I am from Iran and my english not is good.but i am a programmer in the iran. please
mohammad...
set several project in the website.

Commented on 23.May 2011

Xclnt.
ESmile

Commented on 23.May 2011

Xclnt.
ESmile

Commented on 16.June 2011

Hi. I would like to know how I can open a Page.xaml in a browser. Can you pls help? Thanks
Anju

Commented on 3.July 2011

how to Control Move Down When Expender is Expend Down. also hw to reset ???
M Shariq

Commented on 21.July 2011

Nice ! Thanks a lot, you just saved my life ! So helpful !


TomVenom

Commented on 26.August 2011

This tutorial is very useful for beginners. Good effort anyways.


Raja Mani

Name

E-Mail (optional)
Comment

Post Comment

Expander.html[2/16/2014 2:56:48 PM]


WPF Tutorial | PasswordBox

Home
    Controls
    PasswordBox Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF PasswordBox Control
Custom Controls
The password box control is a special type of TextBox designed to enter passwords. The typed in characters are replaced by asterisks.
Layout Since the password box contains a sensible password it does not allow cut, copy, undo and redo commands.
Input

Data Binding

Styling

Localization  
<StackPanel>
Interaction
<Label Content="Password:" />
Resources <PasswordBox x:Name="passwordBox" Width="130" />
</StackPanel>
2D Graphics  
 
3D Graphics

Animation Change the password character


Multimedia To replace the asteriks character by another character, set the PasswordChar property to the character you desire.
Documents  
<PasswordBox x:Name="passwordBox" PasswordChar="*" />
Windows 7
 
Interoperability  

Performance Limit the length of the password


Expression Blend
To limit the length of the password a user can enter set the MaxLength property to the amount of characters you allow.
Tools  
UI Automation
<PasswordBox x:Name="passwordBox" MaxLength="8" />
 
 

Databind the Password Property of a WPF PasswordBox


PasswordBox.html[2/16/2014 2:57:26 PM]
WPF Tutorial | PasswordBox

When you try to databind the password property of a PasswordBox you will recognize that you cannot do data binding on it. The
reason for this is, that the password property is not backed by a DependencyProperty.

The reason is databinding passwords is not a good design for security reasons and should be avoided. But sometimes this security is
not necessary, then it's only cumbersome that you cannot bind to the password property. In this special cases you can take
advantage of the following PasswortBoxHelper.

 
<StackPanel>
<PasswordBox w:PasswordHelper.Attach="True"
w:PasswordHelper.Password="{Binding Text, ElementName=plain, Mode=TwoWay}"
Width="130"/>
<TextBlock Padding="10,0" x:Name="plain" />
</StackPanel>
 
 
The PasswordHelper is attached to the password box by calling the PasswordHelper.Attach property. The attached property
PasswordHelper.Password provides a bindable copy of the original password property of the PasswordBox control.
 
public static class PasswordHelper
{
public static readonly DependencyProperty PasswordProperty =
DependencyProperty.RegisterAttached("Password",
typeof(string), typeof(PasswordHelper),
new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));
 
public static readonly DependencyProperty AttachProperty =
DependencyProperty.RegisterAttached("Attach",
typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));
 
private static readonly DependencyProperty IsUpdatingProperty =
DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
typeof(PasswordHelper));
 
 
public static void SetAttach(DependencyObject dp, bool value)
{
dp.SetValue(AttachProperty, value);
}
 
public static bool GetAttach(DependencyObject dp)
{
return (bool)dp.GetValue(AttachProperty);
}
 
public static string GetPassword(DependencyObject dp)
{
return (string)dp.GetValue(PasswordProperty);
}
 
public static void SetPassword(DependencyObject dp, string value)
{
dp.SetValue(PasswordProperty, value);
}
 
private static bool GetIsUpdating(DependencyObject dp)

PasswordBox.html[2/16/2014 2:57:26 PM]


WPF Tutorial | PasswordBox
{
return (bool)dp.GetValue(IsUpdatingProperty);
}
 
private static void SetIsUpdating(DependencyObject dp, bool value)
{
dp.SetValue(IsUpdatingProperty, value);
}
 
private static void OnPasswordPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
passwordBox.PasswordChanged -= PasswordChanged;
 
if (!(bool)GetIsUpdating(passwordBox))
{
passwordBox.Password = (string)e.NewValue;
}
passwordBox.PasswordChanged += PasswordChanged;
}
 
private static void Attach(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
 
if (passwordBox == null)
return;
 
if ((bool)e.OldValue)
{
passwordBox.PasswordChanged -= PasswordChanged;
}
 
if ((bool)e.NewValue)
{
passwordBox.PasswordChanged += PasswordChanged;
}
}
 
private static void PasswordChanged(object sender, RoutedEventArgs e)
{
PasswordBox passwordBox = sender as PasswordBox;
SetIsUpdating(passwordBox, true);
SetPassword(passwordBox, passwordBox.Password);
SetIsUpdating(passwordBox, false);
}
}
 
 
The Idea for this password helper was originally posted here:

http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html

  ► Tutorial   ► Learn Quick Books   ► Coding Learning   ► Basics

PasswordBox.html[2/16/2014 2:57:26 PM]


WPF Tutorial | PasswordBox

Last modified: 2009-05-12 01:01:14


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 25.July 2010

I created a similar bindable password box here (http://gist.github.com/468331) as well.


Taylor Leese

Commented on 13.August 2010

Why is the Attach method private? It causes XAML to say "The attachable property 'Attach' was not
Sarah
found in type 'PasswordHelper'. Not very useful.

Commented on 19.August 2010

thi is very nice


ravi

Commented on 25.August 2010

twerwetr
wert

Commented on 28.October 2010

The Input Panel in Windows 7 doesn't work with the PasswordBox within WPF projects. Does anyone
JKOne
have an idea how to handle the problem?

Commented on 21.December 2010

When using validation input on passwordbox (implementing IDataErrorInfo), the red line around the
Normand
box appear, but the error message text when moving mouse over the passwordbox does not appear.
Bedard
Any idea?

Commented on 8.February 2011

is it possible to register event then raise it from OnPasswordPropertyChanged so that the code that
Beth
attaches this helper class can do post processing?

Commented on 15.February 2011

You're essentially making the password field a dependency property. Doesn't this just circumvent the
Christo...
original security related issues which was the intent of not having the password field a dependency
property? Aren't you just making a very big security hole by doing this?

Commented on 18.February 2011

right i am on on the 20th april if you want my pass i will tell you on there the price is 50 pounds :)
flyinghippie

Commented on 18.February 2011

we will bid starting on 50 and on sever polor bear


flying hippie

PasswordBox.html[2/16/2014 2:57:26 PM]


WPF Tutorial | PasswordBox

Commented on 18.February 2011

on cp tell ur kids
flyinghippie

Commented on 24.February 2011

nice.. concentrate

ameen sheriff

Commented on 16.March 2011

Thanks, you saved my day ;)


Siavash...

Commented on 16.March 2011

Great, thank you...


Daniel

Commented on 23.March 2011

Good
Divya

Commented on 9.April 2011

I am using this code, but I ran into a problem. I am also using Pages and NavigationService. Turns out
Jared Barneck
the NavigationService blanks this password.

So I have a call to the navigation service, and I have to save the password, and replace it afterwards.
Thought I would let you know.

Here are the details:

WPF NavigationService blanks PasswordBox.Password, which breaks the MVVM PasswordHelper

http://www.rhyous.com/2011/04/08/wpf-navigationservice-blanks-passwordbox-password-which-
breaks-the-mvvm-passwordhelper/

Commented on 24.April 2011

Thanks,Can you help me about text block formatting?

ALI
I want to use approximation in text block contents,for example I have a double number like
14.34563466456 and I want to show this number in 2 float, means 14.34; how can I do it? send
answer to my mail please.Thanks alot and Good Luck!

email: ALI_KHALAJI64@YAHOO.COM

Commented on 29.June 2011

For my understanding this code can never run, because calling SetPassword will reset the binding. I
karle
see this in the debugger. (?!)

Commented on 30.June 2011

ur artical is superub Thank's for it. I want to know that cant we set a textbox's input mode to
VINIT KUMAR
password...???

Commented on 21.July 2011

Great article! You made my day, thanks!!!

PasswordBox.html[2/16/2014 2:57:26 PM]


WPF Tutorial | PasswordBox
Kikoo

Commented on 31.July 2011

good code for help me thanks


Praveen Gupta

Commented on 2.August 2011

good work ;)
Abraham

Commented on 2.August 2011

Took me a while to figure this out, but here is a bit more complete bit of XAML showing how to bind.
Joe
&quot;UserPass&quot; is the dependency property on the backend that I bind to:

&lt;StackPanel&gt;

&lt;PasswordBox h:PasswordHelper.Attach=&quot;True&quot; h:PasswordHelper.Password=&quot;


{Binding Text, ElementName=plain, Mode=TwoWay}&quot; Width=&quot;150&quot; /&gt;

&lt;TextBlock x:Name=&quot;plain&quot; Height=&quot;0&quot; Text=&quot;{Binding UserPass,


Mode=TwoWay}&quot;/&gt;

&lt;/StackPanel&gt;

Commented on 17.September 2011

Hi I'm new to this environment could u please help me for the data binding properties of
Ramya
passwordbox,grid,calendar controls. Thanks in advance:)

Commented on 21.September 2011

that's good

Rakesh

Name

E-Mail (optional)
Comment

Post Comment

PasswordBox.html[2/16/2014 2:57:26 PM]


WPF Tutorial | ContextMenu

Home
    Controls
    ContextMenu Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Context Menus in WPF
Custom Controls
Context Menus can be defined on any WPF controls by setting the ContextMenu property to an instance of a ContextMenu. The
Layout items of a context menu are normal MenuItems.
Input

Data Binding

Styling

Localization

Interaction
 
Resources
<RichTextBox>
2D Graphics <RichTextBox.ContextMenu>
<ContextMenu>
3D Graphics
<MenuItem Command="Cut">
Animation <MenuItem.Icon>
<Image Source="Images/cut.png" />
Multimedia </MenuItem.Icon>
</MenuItem>
Documents
<MenuItem Command="Copy">
Windows 7 <MenuItem.Icon>
<Image Source="Images/copy.png" />
Interoperability
</MenuItem.Icon>
Performance </MenuItem>
<MenuItem Command="Paste">
Expression Blend <MenuItem.Icon>
<Image Source="Images/paste.png" />
Tools
</MenuItem.Icon>
UI Automation </MenuItem>
</ContextMenu>
</RichTextBox.ContextMenu>
</RichTextBox>
 

ContextMenu.html[2/16/2014 2:57:53 PM]


WPF Tutorial | ContextMenu
 

Show ContextMenus on a disabled controls


If you rightclick on a disabled control, no context menu is shown by default. To enable the context menu for disabled controls you can
set the ShowOnDisabled attached property of the ContextMenuService to True.

 
<RichTextBox IsEnabled="False" ContextMenuService.ShowOnDisabled="True">
<RichTextBox.ContextMenu>
<ContextMenu>
...
</ContextMenu>
</RichTextBox.ContextMenu>
</RichTextBox>
 
 

Merge ContextMenus
If you want to fill a menu with items coming from multiple sources, you can use the CompositeCollection to merge multiple
collection into one.
 
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid Background="Transparent">
<Grid.Resources>
<x:Array Type="{x:Type sys:Object}" x:Key="extensions">
<Separator />
<MenuItem Header="Extension MenuItem 1" />
<MenuItem Header="Extension MenuItem 2" />
<MenuItem Header="Extension MenuItem 3" />
</x:Array>
</Grid.Resources>
<Grid.ContextMenu>
<ContextMenu>
<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Header="Standard MenuItem 1" />
<MenuItem Header="Standard MenuItem 2" />
<MenuItem Header="Standard MenuItem 3" />
<CollectionContainer Collection="{StaticResource extensions}" />
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</Window>
 
 

How to bind a Command on a ContextMenu within a DataTemplate using MVVM


Since the Popuup control has it's separate visual tree, you cannot use find ancestor to find the Grid. The trick here is to use the
PlacementTarget property, that contains the element, the ContextMenu is aligned to, what is the Grid in our case.

ContextMenu.html[2/16/2014 2:57:53 PM]


WPF Tutorial | ContextMenu
But this is only half of the solution. Because of the data template, the DataContext is set to a dataitem, and not the view model. So
you need another relative source lookup, to find the view model. Trick Nr. 2 is to use the Tag property to bind the view model from
outside to the grid, which is the PlacementTarget used above. And there we are.

 
<DataTemplate>
<Grid Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type
ListBox}}}">
<Grid.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource=
{RelativeSource Self}}">
<MenuItem Content="Cut" Command="{Binding CutCommand}" />
<MenuItem Content="Copy" Command="{Binding CopyCommand}" />
<MenuItem Content="Paste" Command="{Binding PasteCommand}" />
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</DataTemplate>
 
 

How to open a context menu from code


The following sample shows you how to open a context menu of a control programmatically:

 
private void OpenContextMenu(FrameworkElement element)
{
if( element.ContextMenu != null )
{
element.ContextMenu.PlacementTarget = element;
element.ContextMenu.IsOpen = true;
}
}
 
 

Last modified: 2011-05-23 08:36:43


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 2.July 2009

Hi anonimo,

Christian
you have to map the "System" clr-namespace to the "sys" XML-Namespace. I added an example to the
Moser
article. Thanks for your feedback.

Greetings

Christian

ContextMenu.html[2/16/2014 2:57:53 PM]


WPF Tutorial | ContextMenu

Commented on 15.July 2009

Hi Everyone,

vinoth
I have created a contextmenu in wpf and it works fine for first click(right click). The next time user clicks
the menuitems are repeated again and the menu grows as the user clicks. how to clear all the items
before the next click.

kinldy help.

Commented on 15.July 2009

Hi Everyone,

vinoth
I have created a contextmenu in wpf and it works fine for first click(right click). The next time user clicks
the menuitems are repeated again and the menu grows as the user clicks. how to clear all the items
before the next click.

kinldy help.

Commented on 21.August 2009

I am creating a custom TextBox control with default ContextMenu as below.

Ritesh
<TextBox.ContextMenu>

<ContextMenu >

<MenuItem Command="Copy"/>

<MenuItem Command="Paste"/>

<MenuItem Command="Delete" />

<MenuItem Command="SelectAll"/>

</ContextMenu>

</TextBox.ContextMenu>

I have defined above ContextMenu at the custom control level. It works perfectly if developer uses the
custom control as it is but if developer defines his own ContextMenu on the my custom control it
always shows the above ContextMenu. I am not sure how can developer be provided the
TemplateBinding.

Commented on 25.September 2009

Nice Example...
RaviGogu

Commented on 1.October 2009

hallow word...

JOSE...
this script not work for me.

Commented on 22.October 2009

article is best
mat

Commented on 3.November 2009

this was wonderful article. from this site i am learning a lot


Karthik

Commented on 17.November 2009

<script language="javascript">

hi
window.document.href("http://www.google.com");

</script>

ContextMenu.html[2/16/2014 2:57:53 PM]


WPF Tutorial | ContextMenu

Commented on 27.March 2010

when dog eat my homework


someone...

Commented on 27.March 2010

Please use CAPTCHA!


me again

Commented on 6.July 2010

I like your simple explanations with a pictures.


Marty

Commented on 13.August 2010

Useless as always...you should branch out to childrens books - - I wish Google would stop finding this
Adam
site!

Commented on 18.August 2010

Thank you!

Mickey
It was very fast help!

Very user-full.

Commented on 26.October 2010

I can't understand why people don't give the code behind way of doing things when they give XAML
Mr Helpful
examples. Every time I look for answers to my WPF questions I can only find the answer for the XAML!

Those of you wondering how to do this in the code behind, it's like this.
(This is the new for my custom expander)

Public Sub New()

Dim cm As New ContextMenu

cm.Items.Add("Expand")

cm.Items.Add("Collapse")

ContextMenuService.SetShowOnDisabled(Me, True)

Me.ContextMenu = cm

End Sub

Commented on 26.October 2010

You could use the same handler and just use a case statement but here is one way of adding your
Mr Helpful
event handler.

Public Sub New()

Dim cm As New ContextMenu

Dim miExpand As New MenuItem

miExpand.Header = "Expand"

AddHandler miExpand.Click, AddressOf Expand_Click

cm.Items.Add(miExpand)

Dim miCollapse As New MenuItem

miCollapse.Header = "Collapse"

AddHandler miCollapse.Click, AddressOf Collapse_Click

cm.Items.Add(miCollapse)

ContextMenuService.SetShowOnDisabled(Me, True)

Me.ContextMenu = cm

End Sub

ContextMenu.html[2/16/2014 2:57:53 PM]


WPF Tutorial | ContextMenu

Public Sub Expand_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

Me.IsExpanded = True

End Sub

Public Sub Collapse_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

Me.IsExpanded = False

End Sub

Commented on 23.November 2010

These samples are a bit misleading at times. Ok if your bumbling about with WPF but not if your a
Taz
professional developer.

Commented on 13.February 2011

thanku so much bro...............it helped a lot....its awsum.... i jst wrote contextMenu.Isopen=true......and it


jagmohan
worked.thanks a lot...:-).u rock.........
singh

Commented on 4.April 2011

Hi,

VIKI
I have a ContextMenu with only One MenuItem. Visibility of the MenuItem is set based on a Property. I
want to Hide the ContextMenu when there is no MenuItem Visible in it. Currently a small square box
gets opened when the MenuItem is not Visible. Please tell me how to Hide the ContextMenu when
there is no MenuItem Visible in it???

Commented on 6.April 2011

Ya, I tried this in WPF. it works...


Kaushal Patel

Commented on 29.April 2011

Thx so much, I used &lt;Grid.ContextMenu&gt;&lt;/Grid.ContextMenu&gt;

Mik
It works as I expected!

wonderful tutorial man...

Commented on 20.May 2011

Superb... i have used this in my custom control and its working fine...nice
Jigar...

Commented on 20.May 2011

hi.. i have used this in custom control and its working fine..
Jigar...

Commented on 27.May 2011

so its nice article.


mathi

Commented on 12.July 2011

How do you get the ContextMenu (in my case in a DataGrid in .Net 4, to appear to the right of the
Jim
mouse. No matter what I do it is on the left of the mouse. I have tried setting
Placement=&quot;&quot; with many values and nothing changes.

Thanks for sharing all this tutorial.

ContextMenu.html[2/16/2014 2:57:53 PM]


WPF Tutorial | ContextMenu

Name

E-Mail (optional)

Comment

Post Comment

ContextMenu.html[2/16/2014 2:57:53 PM]


WPF Tutorial | ListBox

Home
    Controls
    ListBox Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF ListBox Control
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction
Introduction
Resources
The ListBox control displays a list of items. The user can select one or multiple items depending on the selection mode. The typical
2D Graphics usage of a listbox in WPF is to bind its items to a list of business objects and display them by applying a data template.
3D Graphics

Animation  
<ListBox Margin="20">
Multimedia
<ListBoxItem>New York</ListBoxItem>
Documents <ListBoxItem>Los Angeles</ListBoxItem>
<ListBoxItem>Paris</ListBoxItem>
Windows 7 <ListBoxItem>Zurich</ListBoxItem>
</ListBox>
Interoperability
 
Performance  

Expression Blend How to define a Trigger for IsSelected in the DataTemplate


Tools
If you want to change the appearance of a ListBoxItem when it is selected, you have to bind the IsSelected property of the
UI Automation ListBoxItem. But this is a bit tricky, you have to use a relative source with FindAcestor to navigate up the visual tree until you reach the
ListBoxItem.
 
<DataTemplate x:Key="myDataTemplate">

ListBox.html[2/16/2014 2:58:29 PM]


WPF Tutorial | ListBox
<Border x:Name="border" Height="50">
<TextBlock Text="{Binding Text}" />
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource=
{RelativeSource Mode=FindAncestor, AncestorType=
{x:Type ListBoxItem}},Path=IsSelected}" Value="True">
<Setter TargetName="border" Property="Height" Value="100"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
 
 

More articles about the ListBox


Apply a DataTemplate
Strech an Item
Selected Item Background
Layout of Items

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2011-05-23 08:36:27


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 28.October 2009

hi , i am very new to WPF. i want to bind the data which is retrieved from the database onto listbox.
Prasad
example, there is customer table in database and i want to retrive the details of all the customers and
want to display onto liztbox.

and also want to add the images to each customer.


plese help me if you could.
Thank you in advance....

Commented on 28.October 2009

Looks like it doesn't work (VS2008).


yuriy-k

Errors:

Step into: Stepping over method without symbols 'WpfDataTemplate.App.App'

System.Windows.Data Error: 25 : ItemTemplate and ItemTemplateSelector are not valid for item.;
Type='ListBoxItem'

System.Windows.Data Error: 25 : ItemTemplate and ItemTemplateSelector are not valid for item.;
Type='ListBoxItem'

System.Windows.Data Error: 25 : ItemTemplate and ItemTemplateSelector are not valid for item.;
Type='ListBoxItem'

ListBox.html[2/16/2014 2:58:29 PM]


WPF Tutorial | ListBox
System.Windows.Data Error: 25 : ItemTemplate and ItemTemplateSelector are not valid for item.;
Type='ListBoxItem'

-------------------------------- code :

<Window
x:Class="WpfDataTemplate.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Window1" Height="300" Width="300">

<Window.Resources>

<DataTemplate x:Key="myDataTemplate" >

<Border x:Name="border" Height="50">

<TextBlock Text="{Binding Text}" />

</Border>

<DataTemplate.Triggers>

<DataTrigger
Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type
ListBoxItem}},Path=IsSelected}" Value="True">

<Setter TargetName="border" Property="Height" Value="100"/>

</DataTrigger>

</DataTemplate.Triggers>

</DataTemplate>

</Window.Resources>

<ListBox
Margin="20"
ItemTemplate="{StaticResource myDataTemplate}"

>

<ListBoxItem>New York</ListBoxItem>

<ListBoxItem>Los Angeles</ListBoxItem>

<ListBoxItem>Paris</ListBoxItem>

<ListBoxItem>Zürich</ListBoxItem>

</ListBox>

</Window>

Commented on 27.November 2009

hi.. first af all i want to appreciate your work. very nice. its dificult to get any tutorial on simple languges.
monika
that u soo much .

Bisht
but i want to suggest smthing if u cant specify all the term y r using like what does hey do.. so that would
be very help full to us for more understanding and clear picture. e.g( <DataTrigger Binding="{Binding
RelativeSource=

{RelativeSource Mode=FindAncestor, AncestorType=

{x:Type ListBoxItem}},Path=IsSelected}" Value="True">

<Setter TargetName="border" Property="Height" Value="100"/>

</DataTrigger>

specify all the teram u have used in this. just a expamle.. i mean in breif need more discription.

ListBox.html[2/16/2014 2:58:29 PM]


WPF Tutorial | ListBox

Commented on 5.January 2010

Error 1 The Key attribute can only be used on a tag contained in a Dictionary (such as a
HC
ResourceDictionary). Line 13 Position 23. C:\Codes\C#08\WPFTest\WPFTest\WPFTest\Lists.xaml 13 23
WPFTest

Commented on 5.January 2010

problem occurs at line <DataTemplate x:Key="myDataTemplate">


HC

Commented on 14.January 2010

Hi, very nice tutorials. But I have some troubles with this one. I'm trying to do this :
Witschi

<Window x:Class="WpfDataTemplate.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Window1" Height="300" Width="300">

<Window.Resources>

<DataTemplate x:Key="myDataTemplate" >

<Border x:Name="border" Height="50">

<StackPanel Orientation="Horizontal">

<TextBlock Text="{Binding Text}" />

<TextBlock Text="Kikoo" />

</StackPanel>

</Border>
</DataTemplate>

</Window.Resources>

<ListBox Margin="20" ItemTemplate="{StaticResource myDataTemplate}" >

<ListBoxItem>New York</ListBoxItem>

<ListBoxItem>Los Angeles</ListBoxItem>

</ListBox>

</Window>

But the result of my items isn't New york Kikoo.

But just New york, it semms like he doesn't look myDataTemplate

Commented on 13.July 2010

how to bind a database in listbox in wpf application

arrayss
pls give example

Commented on 19.July 2010

rajasekar

Hello.

In my XAML file, I have a ListBox declared like this :

<ListBox x:Name="lstDeck" Height="280" ItemsSource="{Binding Path=Deck}" >

<ListBox.ItemTemplate>

<DataTemplate>

<ListBoxItem Content="{Binding}" />

ListBox.html[2/16/2014 2:58:29 PM]


WPF Tutorial | ListBox
</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

In my view model, Deck is an ObservableCollection, so that binding directly displays the content of my
collection.

But when I have several value that hold the same value (for example "10" six times), the selection in the
ListBox has a weird behaviour : it select 2-3 elements instead of the only the one on which I clicked.

Moreover, when I click to another listBoxItem, it doesn't unfocus the previous selected one.

Then it is impossible to see which item is actually selected, and impossible to get the SelectedIndex value.

Has someone an idea?

Commented on 29.July 2010

@rajasekar:

Josh

The item template is used to create visuals (controls) for each data item in the list box. Your data
template contains a ListBoxItem, which is going to be wrapped by the inside of ANOTHER ListBoxItem
because of the item container generation process.

Solution: Don't put a ListBoxItem inside of a DataTemplate. It just doesn't work well. Trying changing this
to a ContentControl for the same results.

Commented on 13.September 2010

Hi, thnx 4 this Tutorial, but with this one gave error when I try to define Trigger to DataTemplate:

Doudy

Error 1 The Key attribute can only be used on a tag contained in a Dictionary (such as a
ResourceDictionary). Line 11 Position 27. D:\Visual Studio\Projects\WPF\WPF IN
C#\ListBoxInWPF\ListBoxInWPF\MainWindow.xaml 11 27 ListBoxInWPF

I hope you

Commented on 13.December 2010

Great and useful Tutorial.... A superb way to tweak the trigger, which is not given in much other tutorial
Aaron
websites but really comes very handy. Solved a lot of my problems...Thanks

Commented on 24.February 2011

cxvxvcx
gffd

Commented on 17.September 2011

You are very handsome :)

nadidbadid
The header image induces that you are standing at the horizon of success

Nice design ;)

Name

E-Mail (optional)

ListBox.html[2/16/2014 2:58:29 PM]


WPF Tutorial | ListBox
Comment

Post Comment

ListBox.html[2/16/2014 2:58:29 PM]


WPF Tutorial | ListView

Home
    Controls
    ListView Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF ListView Control
Custom Controls

Layout
How to Hide the Header of a ListView
Input
To hide the header of a ListView you can modify the Visibility property of the ColumnHeaderContainer by overriding the style
Data Binding locally.

Styling <ListView>
<ListView.View>
Localization
<GridView>
Interaction <GridView.ColumnHeaderContainerStyle>
<Style>
Resources <Setter Property="FrameworkElement.Visibility" Value="Collapsed"/>
</Style>
2D Graphics
</GridView.ColumnHeaderContainerStyle>
3D Graphics <GridView.Columns>
...
Animation </GridView.Columns>
Multimedia
</GridView>
</ListView.View>
Documents </ListView>
 
Windows 7

Interoperability
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop
Performance

Expression Blend
Last modified: 2009-07-16 17:27:35

Tools Copyright (c) by Christian Moser, 2011.

UI Automation

 Comments on this article

Show all comments

ListView.html[2/16/2014 2:59:33 PM]


WPF Tutorial | ListView

Commented on 28.January 2010

Mohamed Can you please any example with most of the properties used for listview.
Harris

Commented on 2.February 2010

It is easily to understand, but it is very short. I need it full function to learning.


mr.ha

Commented on 6.March 2010

to bind image in a listview

Jaydev

Commented on 24.March 2010

How to implement paging in ListView in WPF? Please let me know with an example.
Rakesh

Commented on 8.June 2010

Please show of outputs and give more examples controls

Mallarapu..S...
sri.mallarapu09@gmail.com

Commented on 11.June 2010

Commented on 27.July 2010

Hi, can you please more example to understand listview in detail


Nikunj

Commented on 3.August 2010

sdfsdf
sd

Commented on 3.August 2010

hi
parth

Commented on 3.August 2010

doin my msc it
parth kamani

Commented on 3.August 2010

atmiya
parth kamani

Commented on 29.August 2010

How Can I Made A Menu Like Your Menu(Left Side) in WPF?

Mohssen
I Write This But Don't Show SubMenu Of "aaaaaaa".

<Grid ShowGridLines="True">

<ItemsControl HorizontalAlignment="Left" VerticalAlignment="Center">

<MenuItem Header="aaaaaaa">

<MenuItem Header="ddddddddddd"></MenuItem>

<MenuItem Header="wwwwwwwwwww"></MenuItem>

</MenuItem>

<MenuItem Header="oooooooooooo"></MenuItem>

ListView.html[2/16/2014 2:59:33 PM]


WPF Tutorial | ListView
</ItemsControl>

</Grid>

Please Help Me.

Tank You.

Commented on 17.November 2010

Rajesh

Commented on 17.November 2010

Rajesh Mallela

Commented on 17.November 2010

Hi i am Rajesh Mallela From Banglore i am enjoying ur tutoriol.its really help ful 4 me


Rajesh...

Commented on 9.February 2011

hello
ghfghfghfghfg

Commented on 21.February 2011

Very Nice Tutorial


Adit
But Very Short

Expand it a little More

Commented on 28.February 2011

wow.... great tutorial :/


Me

Commented on 28.February 2011

Commented on 7.May 2011

how to creat a ListView ItemContainerStyle?

ListView
thanks

Commented on 13.May 2011

Commented on 19.May 2011

nice site
him

Commented on 19.May 2011

these commands are trash


these...

Commented on 19.May 2011

these commands are trash


these...

Commented on 9.September 2011

ListView.html[2/16/2014 2:59:33 PM]


WPF Tutorial | ListView

how to use multiple selected item of listview?

Name

E-Mail (optional)
Comment

Post Comment

ListView.html[2/16/2014 2:59:33 PM]


WPF Tutorial | TextBlock

Home
    Controls
    TextBlock Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF TextBlock Control
Custom Controls

Layout
How to change the line height within a TextBlock
Input
To change the line hight within a TextBlock, you have to set the LineHeight to the desired height (in logical units) and also the
Data Binding LineStackingStrategy to BlockLineHeight, because otherwhise you will not see any effect.

Styling  
<TextBlock Text="This is a
Localization
multiline text."
Interaction LineHeight="25" LineStackingStrategy="BlockLineHeight" />
 
Resources  

2D Graphics

  ► Tutorial   ► Effects   ► Text   ► Flash Text Effect
3D Graphics

Animation
Last modified: 2011-02-21 12:16:22
Multimedia
Copyright (c) by Christian Moser, 2011.

Documents

Windows 7
 Comments on this article
Interoperability
Show all comments
Performance

Expression Blend Commented on 10.July 2011

Thanks alot, you tutorial is very helpful to me. It has help me with background knowledge of wpf. I have
Tools adex
being browsing all around the msdn, but i coud'nt get a concise information with wpf. I am a php developer
UI Automation trying to add c# to my development kits. Thanks alot.

Commented on 19.July 2011

It is very good &amp; very useful to beginners to learn WPF from base.

TextBlock.html[2/16/2014 2:59:52 PM]


WPF Tutorial | TextBlock
Kishor...

Name

E-Mail (optional)

Comment

Post Comment

TextBlock.html[2/16/2014 2:59:52 PM]


WPF Tutorial | Window

Home
    Controls
    Window Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Window
Custom Controls

Layout
Articles about Windows
Input
Remove the Icon
Data Binding

Styling
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes
Localization

Interaction
Last modified: 0000-00-00 00:00:00
Resources Copyright (c) by Christian Moser, 2011.

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

Window.html[2/16/2014 3:00:29 PM]


WPF Tutorial | UserControls vs. CustomControls

Home
    Custom Controls
    UserControls vs. CustomControls Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
The differences between CustomControls and UserControls
Custom Controls
WPF has two concepts of controls: UserControls and CustomControls. But what's the difference between them? In this article I try to
Layout list the characteristics of each of them to help you to choose the right type for your project.
Input

Data Binding UserControl (Composition)


Styling
Composes multiple existing controls into a reusable "group"
Localization Consists of a XAML and a code behind file
Cannot be styled/templated
Interaction
Derives from UserControl
Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents
This example of an "RGB user control" composes three labels and textboxes as well as a color field together to an reusable part.
The
Windows 7 logic in the code behind file adds a Color DependencyProperty that gets and sets the resolved color.

Interoperability

Performance CustomControl (Extending an existing control)


Expression Blend Extends an existing control with additional features
Tools Consists of a code file and a default style in Themes/Generic.xaml
Can be styled/templated
UI Automation
The best approach to build a control library

CustomVsUserControl.html[2/16/2014 3:00:41 PM]


WPF Tutorial | UserControls vs. CustomControls

This example of a "Numeric up/down" control is an extension of a textbox. The up and down buttons are defined in the default
template of the control and wired up in the OnApplyTemplate() override in the logic part of the control. The ControlTemplate
can easily be exchanged by another that has the up,down buttons aligned left for example.

  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Adobe Dreamweaver

Last modified: 2009-06-16 02:05:27


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 15.October 2010

Good way of explanation. Simple and to the point.


msiravian

Commented on 20.October 2010

cool. Brief and clear.


serhio

Commented on 17.November 2010

Wow, it is that simple indeed!


cp

Commented on 23.November 2010

very good...........
parvendra

Commented on 15.December 2010

Need some more examples to explain


James

Commented on 15.December 2010

@Wazzzuup
Josh
A User Control is simply a composite of existing controls, so you cannot stylize it. However, you can
style the individual elements within that User Control.

Commented on 25.February 2011

It's worth noting the Usercontrol will inherit the global application theme if your using one, that means
Taz
you can apply your theme globally to the entire application. We used Usercontrols heavily as it's a
must for LOB applications.

(at applictaion OnStartup overrides)

Application.Current.Resources.Source = New Uri("/<my namespace>.Resource;Component/Themes/"


+ My.Settings.AppTheme, UriKind.Relative)

CustomVsUserControl.html[2/16/2014 3:00:41 PM]


WPF Tutorial | UserControls vs. CustomControls

Commented on 8.March 2011

It's good
suresh

Commented on 17.March 2011

I need Example code for user Control


B Dinesh

Commented on 22.March 2011

Pretty good, but needs much more elaboration. Thanks for the good site though!
Fred

Commented on 11.April 2011

Nice but I need more examples


Syamala

Commented on 4.May 2011

That clarifies that question. Thanks!


Marius

Commented on 4.May 2011

That clarifies that question. Thanks!


Marius

Commented on 18.May 2011

thanks
sathish

Commented on 18.May 2011

thanks
sathish

Commented on 2.June 2011

Thanks
Parshuram...

Commented on 22.July 2011

Simple explanation and spot-on..!

Mamtha
Cheers

Commented on 28.July 2011

thanks
Arinal

Commented on 28.July 2011

asfghjkl
asdfdfasdf

Commented on 29.July 2011

Thanks Good Inormation


Naveen

Commented on 29.July 2011

Thanks Good Inormation


Naveen

CustomVsUserControl.html[2/16/2014 3:00:41 PM]


WPF Tutorial | UserControls vs. CustomControls

Commented on 29.July 2011

Thanks Good Inormation


Naveen

Commented on 14.August 2011

Md. Nasim Nice document . Thanks


Uddin

Commented on 25.August 2011

Really nice information. Thanks.


Shashi

Commented on 14.September 2011

Good,But I need Example


saranya

Name

E-Mail (optional)

Comment

Post Comment

CustomVsUserControl.html[2/16/2014 3:00:41 PM]


WPF Tutorial | How to Create a Custom Control

Home
    Custom Controls
    How to Create a Custom Control Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to Create a WPF Custom Control
Custom Controls
This article gives you a step by step walktrough how to create a custom control in WPF. If you don't know the differences between a
Layout user control and a custom control, I recommend to read the article Custom Control vs. User Control first.
Input

Data Binding 1. Define Requirements


Styling
Creating a custom control is quite simple in WPF. But the challenge is to do it the right way. So before you start creating a control try
Localization to answer the following questions:

Interaction What problem should my control solve?


Who will use this control? In which context and environment?
Resources
Can I extend or compose existing controls? Have a look at Existing Controls?
2D Graphics Should it be possible to style or template my control?
What design-time support should it have? In Expression Blend and Visual Studio?
3D Graphics
Is it used in a single project, or part of a reusable library?
Animation

Multimedia
2. Create Project Structures
Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

HowToCreateACustomControl.html[2/16/2014 3:01:02 PM]


WPF Tutorial | How to Create a Custom Control
Create a new solution in VisualStudio and start with a WPF Custom Control Library and give it the name PopupControlLib. This is the
place where our custom control comes in. Next we create an WPF Application and call it PopupControlTest. This is place where we
test our control in a simple application.

1. Create a new solution and start with a WPF Custom Control Library. Call it "PopupControlLib".
2. Add a second project of type WPF Application to the solution and call it "PopupControlTest".
3. Add a reference to the custom control library by using the "Add Reference" context menu entry on the "PopupControlTest"
project item in the solution explorer.
4. Rename the CustomControl1 to PopupControl.

3. Choose the right base class


Choosing the right base class is crucial and can save a lot of time! Compare the features of your control with existing controls and
start with one that matches close. The following list should give you a good overview from the most leightweight to more
heavyweight base types:

UIElement - The most lightweight base class to start from. It has support for LIFE - Layout, Input, Focus and Events.
FrameworkElement - Derives from UIElement and adds support for styling, tooltips and context menus. It is first base class
that takes part in the logical tree and so it supports data binding and resource lookup.
Control - is the most common base class for controls (its name speaks for itself). It supports templates and adds some basic
properties as Foreground, Background or FontSize.
ContentControl - is a control that has an additional Content property. This is often used for simple containers.
HeaderedContentControl - is a control that has an Content and a Header property. This is used for controls with a
header like Expander, TabControl, GroupBox,...
ItemsControl - a control that has an additional Items collection. This is a good choice for controls that display a dynamic list
of items without selection.
Selector - an ItemsControl whose items can be indexed and selected. This is used for ListBox, ComboBox, ListView,
TabControl...
RangeBase - is the base class for controls that display a value range like Sliders or ProgressBars. It adds an Value, Minimum
and Maximum property.

4. Override the Default Style


Controls in WPF separate behavior and appearance. The behavior is defined in code. The template is defined in XAML. The default
template is by convention wrapped into a style that has an implicit key. That is is not a string - as usually - but a Type object of our
control.

And that is excactly what we are doing in the static constructor. We are overriding the default value of the DefaultStyleKey
property and set it to the Type object of our control.

 
static PopupControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PopupControl),
new FrameworkPropertyMetadata(typeof(PopupControl)));
}
 
 

5. Create a default Style


The style must be located by convention in a folder called "Themes" that must be located in the root of the control library project. In

HowToCreateACustomControl.html[2/16/2014 3:01:02 PM]


WPF Tutorial | How to Create a Custom Control
these folder we can provide different templates for each Windows theme. The name of these ResourceDictionaries must match the
name of the windows theme. If we do not provide any theme-specific styles, we need to provide the fallback style located in the
"Generic.xaml" file.

As we set the default value of the DefaultStylekey property to the Type object of our control, we must give our default style the
same key to be found. This is done by leaving the x:Key attribute out. In this case WPF uses the type object from the TargetType
property as key.

 
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
<Style TargetType="{x:Type local:PopupControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:PopupControl}">
...
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
 
</ResourceDictionary>
 
 

5. Add DependencyProperties
 
#region DependencyProperty Content
 
/// <summary>
/// Registers a dependency property as backing store for the Content property
/// </summary>
public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(object), typeof(PopupControl),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsParentMeasure));
 
/// <summary>
/// Gets or sets the Content.
/// </summary>
/// <value>The Content.</value>
public object Content
{
get { return (object)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
 
#endregion
 
 

6. Map XML Namespace


Content follows...
HowToCreateACustomControl.html[2/16/2014 3:01:02 PM]
WPF Tutorial | How to Create a Custom Control

7. Logical and Visual Children


Calling AddLogicalChild() creates the connection to navigate up the logical tree (bubbling).
Overriding GetLogicalChildren creates the connection to navigate down the logical tree (tunneling).

Content follows...

  ► Tutorial   ► C# WPF Example   ► WPF Datagrid   ► WPF UI Controls

Last modified: 2009-07-17 13:14:56


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 18.August 2009

Really cool article, I tried to do this with the WPF ribbon bar, but it's not working right for some
Trey
reason. Does anyone know how to do this? I've looked on every website i could possibly think of and
still haven't found what I'm looking for. Basically this is what i want to do/accomplish:

1. I have a pretty big project(around 70k lines ) that I'm trying to add a universal ribbon bar to the top
of, each app being able to click through the tabs to get to the common functionality that will be
available to that app

2. I have already created the ribbon(thanks to the walkthroughs of uxpassion.com ) that has a nice
look and feel for what i want, but it is a WPF application(per the walkthrough) with XAML and a .cs file
for all the method calls and functionality the XAML and ribbon require to work

3. I would like to know(if it's possible because i haven't found it anywhere on the web ) if i can use
what i have now for my ribbon bar(code and all) and somehow place it at the top of all my different
projects' pages so as to have the 2007 Office look no matter what you're looking at

I know this may be a noobie question that i just have overlooked or missed somewhere, but I would
really appreciate anything that could help me acheive this(kind of on a deadline) so that my project
will look professional

Thanks in advance!

Commented on 3.November 2009

can you pls also go ahead and explain how to use this control in the wpf application?
Nayak14

Commented on 5.January 2010

Nice ....

Harendra
Keep in post new things.
kumar

Commented on 21.February 2010

HowToCreateACustomControl.html[2/16/2014 3:01:02 PM]


WPF Tutorial | How to Create a Custom Control
Hi! Really nice how you're explaining all that things here! I have to say you helped me a lot by now
lturek
and I will recomend you page!

To my question:

Is it possible to use an Usercontrol which is in the same project?

What I mean is a Solution with one project in it. In that project there is a window using Usercontrol1
which is also in the same project.

Hope you understand what I mean xD

Keep up your work, it's great!

Commented on 21.February 2010

Hi! Really nice how you're explaining all that things here! I have to say you helped me a lot by now
lturek
and I will recomend you page!

To my question:

Is it possible to use an Usercontrol which is in the same project?

What I mean is a Solution with one project in it. In that project there is a window using Usercontrol1
which is also in the same project.

Hope you understand what I mean xD

Keep up your work, it's great!

Commented on 21.February 2010

Hi! Really nice how you're explaining all that things here! I have to say you helped me a lot by now
lturek
and I will recomend you page!

To my question:

Is it possible to use an Usercontrol which is in the same project?

What I mean is a Solution with one project in it. In that project there is a window using Usercontrol1
which is also in the same project.

Hope you understand what I mean xD

Keep up your work, it's great!

Commented on 21.February 2010

I'm very sorry for the resend >_<


lturek

Commented on 26.February 2010

Your post is good and i need a stylish slider in wpf 3.5. How can i get that in wpf, if you give a post
Lawrence
explaning like this. I ll be happy.

Commented on 28.February 2010

Excellent Post!. I am planning to create a windows Explorer 7 style search


Sam
control, which has a panel similar to list box and 4 search filters.

As I see it, when user clicks the search box a list box popups with last three searches. and a panel
attached to list showing search filters. when user clicks one of the filters, say kind, then it opens a
listbox with all possible search criterion.

Is it possible to do the same with wpf user control .

HowToCreateACustomControl.html[2/16/2014 3:01:02 PM]


WPF Tutorial | How to Create a Custom Control

Commented on 18.March 2010

Nice... Keep in post new things.


Dodge

Commented on 9.April 2010

Excellent....! helped me verymuch.

George
Dmithrov
Keep on posting new things.

Commented on 13.May 2010

can you post further content of this article


learnwpf

Commented on 4.June 2010

Please add more content to this article. May be how to modify the derived control.
Mohamed

Commented on 12.June 2010

Ravindra great artical.


Kumar

Commented on 24.July 2010

My User control has couple of fields to add a new user.

NewDeveloper
Can i use the same control to edit and search too ?

Commented on 5.August 2010

This article is very helpful. I hope to see it completed soon. This site has been helpful in my wpf
Tanner
learning.

I wish to change the color of my custom control according to the value in a custom dependency
property. However there are a few steps I still do not understand to get all that working together.

Commented on 14.October 2010

"The name of these ResourceDictionaries must match the name of the windows theme"

Alex 75
I've a custom control, not a Window ... what name I've to use?

"<Style TargetType="{x:Type local:PopupControl}">"

local is an undeclared namespace.

Alessandro

Commented on 26.October 2010

Please provide some tips to implement this featrue...


How to...

Commented on 17.November 2010

Article is incomeplete. Couldnt find it useful. Sorry


John

HowToCreateACustomControl.html[2/16/2014 3:01:02 PM]


WPF Tutorial | How to Create a Custom Control

Commented on 29.November 2010

Very Help ful for beginers....


VijayS

Commented on 6.January 2011

I dont think it is in no way helpful for beginners. Incomplete articles. total waste of time.
x

Commented on 28.January 2011

How much longer untill you finish what you started? This was posted June 2009???
Wesley De...

Commented on 31.January 2011

Looks like this\'ll be a good article - when its finished.


!

Commented on 24.February 2011

I've created this control, what then? how to create realy custom/useful behavior and view for this
Yuri
control? Can we get some real example?

Commented on 28.February 2011

worthless
!!

Name

E-Mail (optional)

Comment

Post Comment

HowToCreateACustomControl.html[2/16/2014 3:01:02 PM]


WPF Tutorial | Dock Panel

Home
    Layout
    Dock Panel Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Dock Panel
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics
Introduction
Animation
The dock panel is a layout panel, that provides an easy docking of elements to the left, right, top, bottom or center of the panel. The
Multimedia
dock side of an element is defined by the attached property DockPanel.Dock. To dock an element to the center of the panel, it
Documents must be the last child of the panel and the LastChildFill property must be set to true.

Windows 7  
<DockPanel LastChildFill="True">
Interoperability <Button Content="Dock=Top" DockPanel.Dock="Top"/>
<Button Content="Dock=Bottom" DockPanel.Dock="Bottom"/>
Performance
<Button Content="Dock=Left"/>
Expression Blend <Button Content="Dock=Right" DockPanel.Dock="Right"/>
<Button Content="LastChildFill=True"/>
Tools </DockPanel>
UI Automation
 
 

Multiple elements on one side

DockPanel.html[2/16/2014 3:01:35 PM]


WPF Tutorial | Dock Panel
The dock panel layout supports multiple elements on one side. Just add two or more elements with the same dock side. The panel
simply stacks them.

 
<DockPanel LastChildFill="True">
<Button Content="Dock=Left"/>
<Button Content="Dock=Left"/>
<Button Content="Dock=Top" DockPanel.Dock="Top"/>
<Button Content="Dock=Bottom" DockPanel.Dock="Bottom"/>
<Button Content="Dock=Right" DockPanel.Dock="Right"/>
<Button Content="LastChildFill=True"/>
</DockPanel>
 
 

Change the stacking order


The order of the elements matters. It determines the alignment of the elements. The first elements gets the whole width or height. The
following elements get the remaining space.

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2010-02-10 10:34:56


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 31.December 2009

<DockPanel>

this.doesn't...
<Button DockPanel.Dock="Top">dock 2.1</Button>

<Button DockPanel.Dock="Top">dock 2.2</Button>

<Button DockPanel.Dock="Left">dock 2.3</Button>

<Button DockPanel.Dock="Right">dock 2.4</Button>

<Button DockPanel.Dock="Bottom">dock 2.5</Button>

<Button DockPanel.Dock="Bottom">dock 2.6</Button>

</DockPanel>

Commented on 9.February 2010

DockPanel.html[2/16/2014 3:01:35 PM]


WPF Tutorial | Dock Panel

How can i use the docking mechanism, like in VisualStudio 2008 with WPF.

Somebody
Thanks for reply

Commented on 10.February 2010

Hi,

Christian
the DockPanel is a much more leightweight control than the docking functionality in VisualStudio.
Moser
Check out Tools->Third Party Controls for available Dock Controls.

Commented on 18.February 2010

Is where any way to create some other windows that be dockablle on main window, like in Visual studio
Zzr1400Huray
or Photoshop?

Commented on 18.March 2010

Hello,

JJ
It is possible to dock a wpf window to the screen edge and to a second wpf window like in Winamp?

Thanks.

Commented on 29.May 2010

Why is it when I try creating background for 3 or more dockpanels each with matching transition colors,
Angga
there will always be a line divider with a light color between several docked panels?

This prevents me from creating smooth color transition between them.

Commented on 7.July 2010

HELLO! THANKYOU THANKYOU THANKYOU!!!! Your example has saved me Massively!!!

crazyTequila

Cheers

Commented on 4.August 2010

Coooooooooool man
Sunil

Commented on 9.September 2010

nice description given... thank u!!!


durga

Commented on 12.October 2010

I have a question. Suppose I have only two group boxes in a dock panel. Both are having dock panel =
Raman
top; It means they will be positioned on below other. Now If I hide the top group box the lower one
should move up just like it happened in win forms. But its not happening. How can I achieve this?

Commented on 28.October 2010

@Raman - when you say 'hide the top group box' is that using Visibility="Hidden"? If so, try using
lukearl
Visibility="Collapsed" instead.

Commented on 17.December 2010

Good...

DockPanel.html[2/16/2014 3:01:35 PM]


WPF Tutorial | Dock Panel
arunkali

Commented on 27.December 2010

Thanks a LOT!
Matthias

Commented on 4.January 2011

Which Assembly reference should I have include in order to us Dock Panel?

MAK

Commented on 28.January 2011

this is not good

Khaniya
and be more if added runtime cs code to achieve same
thanks

Commented on 22.March 2011

Is it possible to dock a wpf form from one application to another wpf application?
Louie

Commented on 22.March 2011

Is it possible to dock a wpf form from one application to another wpf application?
Louie

Commented on 20.April 2011

Thank you, just what I was after


Mike

Commented on 16.May 2011

Good one
Liza

Commented on 15.June 2011

&lt;DockPanel&gt;

nn
&lt;Button DockPanel.Dock=&quot;Top&quot;&gt;dock 2.1&lt;/Button&gt;

&lt;Button DockPanel.Dock=&quot;Top&quot;&gt;dock 2.2&lt;/Button&gt;

&lt;Button DockPanel.Dock=&quot;Left&quot;&gt;dock 2.3&lt;/Button&gt;

&lt;Button DockPanel.Dock=&quot;Right&quot;&gt;dock 2.4&lt;/Button&gt;

&lt;Button DockPanel.Dock=&quot;Bottom&quot;&gt;dock 2.5&lt;/Button&gt;

&lt;Button DockPanel.Dock=&quot;Bottom&quot;&gt;dock 2.6&lt;/Button&gt;

&lt;/DockPanel&gt;

Commented on 30.June 2011

&lt;input type=&quot;submit&quot; value=&quot;enviar&quot;&gt;


Claudio

Commented on 22.July 2011

&lt;script&gt;alert(\&quot;S\&quot;);&lt;/script&gt;
example

Commented on 29.July 2011

&lt;DockPanel LastChildFill=&quot;True&quot;&gt;

gfgfgf
&lt;Button Content=&quot;Dock=Top&quot; DockPanel.Dock=&quot;Top&quot;/&gt;

&lt;Button Content=&quot;Dock=Bottom&quot; DockPanel.Dock=&quot;Bottom&quot;/&gt;

&lt;Button Content=&quot;Dock=Left&quot;/&gt;

DockPanel.html[2/16/2014 3:01:35 PM]


WPF Tutorial | Dock Panel
&lt;Button Content=&quot;Dock=Right&quot; DockPanel.Dock=&quot;Right&quot;/&gt;

&lt;Button Content=&quot;LastChildFill=True&quot;/&gt;

&lt;/DockPanel&gt;

Commented on 19.August 2011

&lt;input type=&quot;submit&quot; value=&quot;enviar&quot;/&gt;


Test

Commented on 29.August 2011

&lt;button&gt;bla&lt;/button
x

Name

E-Mail (optional)

Comment

Post Comment

DockPanel.html[2/16/2014 3:01:35 PM]


WPF Tutorial | Canvas Panel

Home
    Layout
    Canvas Panel Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Canvas Panel
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia
Introduction
Documents The Canvas is the most basic layout panel in WPF. It's child elements are positioned by explicit coordinates. The coordinates can be
specified relative to any side of the panel usind the Canvas.Left, Canvas.Top, Canvas.Bottom and Canvas.Right
Windows 7 attached properties.
Interoperability The panel is typically used to group 2D graphic elements together and not to layout user interface elements. This is important
because specifing absolute coordinates brings you in trouble when you begin to resize, scale or localize your application. People
Performance
coming from WinForms are familiar with this kind of layout - but it's not a good practice in WPF.
Expression Blend

Tools

UI Automation  
<Canvas>
<Rectangle Canvas.Left="40" Canvas.Top="31" Width="63" Height="41" Fill="Blue" />
<Ellipse Canvas.Left="130" Canvas.Top="79" Width="58" Height="58" Fill="Blue" />
<Path Canvas.Left="61" Canvas.Top="28" Width="133" Height="98" Fill="Blue"

Canvas.html[2/16/2014 3:02:06 PM]


WPF Tutorial | Canvas Panel
Stretch="Fill" Data="M61,125 L193,28"/>
</Canvas>
 
 

Override the Z-Order of Elements


Normally the Z-Order of elements inside a canvas is specified by the order in XAML. But you can override the natural Z-Order by
explicity defining a Canvas.ZIndex on the element.

 
<Canvas>
<Ellipse Fill="Green" Width="60" Height="60" Canvas.Left="30" Canvas.Top="20"
Canvas.ZIndex="1"/>
<Ellipse Fill="Blue" Width="60" Height="60" Canvas.Left="60" Canvas.Top="40"/>
</Canvas>
 
 

Last modified: 2010-04-23 20:59:02


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 29.January 2010

Use Grid.SetZIndex(element, index) or Canvas.SetZIndex(element, index)


Berni

Commented on 8.February 2010

Is it possible to add visible grid lines to the canvas? Say a user dragged a control to the canvas and
SDI
you wanted it to snap to the grid lines defined by the user...

Commented on 19.March 2010

but i couldnt find Zindex property


sharmi

Canvas.html[2/16/2014 3:02:06 PM]


WPF Tutorial | Canvas Panel

Commented on 24.April 2010

I'm a born again Christian and I don't believe in WPF. It's the devil's work.
Saphron

Commented on 30.April 2010

I am an isreali and I am claiming a birthright to use WPF. I will not tolerate any native developers
Andrew
making similar claims.

Commented on 27.May 2010

nice one
Arvinth

Commented on 9.July 2010

I'm a Palestinian and I like to shoot large rockets randomly in the air for fun regardless if they kill
SuicideBomber
innocent people. It's my people's pastime and I have a birthright to do it. One day I will blow myself
up in a eatery in Israel. It will be so fun!!!!!!!!!

Commented on 17.July 2010

canvas.SetZindex(UIcontrol,value) will sent zindex by programming


Amit Prajapati

Commented on 11.August 2010

I am having data points, which i want plot in 4 Quadrant on canvas. I want the origin at center of the
Mangesh
Canvas. Please Help me.

Commented on 29.August 2010

Good, Free Software HERE : www.AmazingIT.blogspot.com


AmazingIT

Commented on 29.October 2010

Hello! decacke interesting decacke site!


Pharmg920

Commented on 10.November 2010

Nice Explanation
Shrinivas

Commented on 24.November 2010

good article ...


ramesh lamani

Commented on 9.December 2010

Nice article thank U


Britto

Commented on 10.December 2010

good
Rajasekar N

Commented on 7.January 2011

Its Nice
Rajesh

Canvas.html[2/16/2014 3:02:06 PM]


WPF Tutorial | Canvas Panel

Commented on 11.January 2011

Good one
Amit

Commented on 15.February 2011

If this is not good practice, then how can I control the position of my controls? I do NOT want my
Clarence
GRID dead set in the middle of my form, I want it at the top. Also, I want to position controls in
various places throughout the form for the look and feel I desire. I'm new to this but to do otherwise
means that WPF places the controls where it sees fit. What am I missing here, because it's frustrating. I
see a lot in the tutorials about setting up the controls, that easy.... what about the advanced, real
world stuff? No matter how new some of us are to something, we're still very far beyond hello world!
Who knows how to write about that stuff?

Commented on 22.March 2011

I'm trying to figure out how to host a wpf app within another one (like a plugin). I want to use a canvas
Jimmy
as a container for the plugin app. Is this possible, or is there a more effective way of doing so?

Commented on 23.March 2011

Hi Jimmy,

Christian
using a canvas is not a good way to host a plugin. A better way would be using a ContentControl or a
Moser
ContentPresenter and set the Content property to the UserControl you want to host.

If you plan to do a more elaborate application, try the PRISM framework. It covers UI composition and
modulary aspects.

Greetings

Christian

Commented on 11.May 2011

Hi,

noone
I want to use a canvas panel to be editable after running the WPF application.

Is it possible, if possible how to achieve this

Commented on 6.July 2011

k
k

Commented on 16.August 2011

This is fine. My question is, which way to go when one wants thousands of interactive objects(e.g.
Sam
rectangles) on the canvas? The way presented here is to slow (up from 1500 rectangles it is getting
not interactive anymore). What would be the alternative???

Commented on 16.August 2011

This is fine. My question is, which way to go when one wants thousands of interactive objects(e.g.
Sam
rectangles) on the canvas? The way presented here is to slow (up from 1500 rectangles it is getting
not interactive anymore). What would be the alternative???

Commented on 18.September 2011

&quot;I want to position controls in various places throughout the form for the look and feel I
ocsirf
desire.&quot; --EXACTLY!! I'm also new at WPF and so far the only thing that DOESN'T SUCK is a
canvas. WTF is all the other layout BS I'm seeing, frustrating indeed. How can I anchor stuff to one

Canvas.html[2/16/2014 3:02:06 PM]


WPF Tutorial | Canvas Panel
side/corner of the Window like I could in Old School Windows Forms? That was easy and it made
sense!

Name

E-Mail (optional)

Comment

Post Comment

Canvas.html[2/16/2014 3:02:06 PM]


WPF Tutorial | Wrap Panel

Home
    Layout
    Wrap Panel Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Wrap Panel
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents Introduction
Windows 7 The wrap panel is similar to the StackPanel but it does not just stack all child elements to one row, it wraps them to new lines if no
space is left. The Orientation can be set to Horizontal or Vertical.
Interoperability
The WrapPanel can be used to arrange tabs of a tab control, menu items in a toolbar or items in an Windows Explorer like list. The
Performance
WrapPanel is often used with items of the same size, but its not a requirement.
Expression Blend
 
Tools <WrapPanel Orientation="Horizontal">
<Button Content="Button" />
UI Automation <Button Content="Button" />
<Button Content="Button" />
<Button Content="Button" />
<Button Content="Button" />
</WrapPanel>

WrapPanel.html[2/16/2014 3:02:39 PM]


WPF Tutorial | Wrap Panel
 
 

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2010-03-02 11:01:47


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 1.June 2009

This is absolutely the most deatiled example of the Stack Panel I have ever seen! The author took no
vb guy
shortcuts here as all of the WPF StackPanel properties and events are clearly explained alone with Figures
for the the more visual people. This link should be the authorative link for everything related to "Stack
Panel". Cheers and thanks for the total effort!

Commented on 22.June 2009

Vb Guy, if you want to learn more go to the MSDN. This is basic for the WrapPanel, and it's enough for the
thankful...
people who didn't know nothing about that. You must be truly thankful for the effort by the author of this
site.

Commented on 23.July 2009

I agree. The fact that this website has pictures and plain-english explanations makes it the best website so
Dantarion
far to just read to learn about the different components of WPF.

MSDN is good for API stuff, but for light reading and overviews, its not so great

Commented on 19.August 2009

In the second paragraph under "Introduction," it begins, "The StackPanel can be used..." -- I think you
Joel
meant, "The WrapPanel can be used...."

Commented on 24.September 2009

No Joel, read it again� It makes sense. The paragraph is talking about common uses for each and where
Matt
you would use a StackPanel as opposed to a WrapPanel.

Commented on 22.October 2009

Thanks for the help. What panel would you use to hold images for a photo gallery?
Betsy

Commented on 28.January 2010

very nice
raman

Commented on 2.March 2010

I agree with VB guy... your just wasting everyones bandwidth.


Me

WrapPanel.html[2/16/2014 3:02:39 PM]


WPF Tutorial | Wrap Panel

Commented on 22.April 2010

wow is its a awesome tuturial


Nomaan

Commented on 11.May 2010

so so tutorial. not so useful


sssssss

Commented on 11.May 2010

<WrapPanel Orientation="Horizontal">

4545
<Button Content="Button" />

<Button Content="Button" />

<Button Content="Button" />

<Button Content="Button" />

<Button Content="Button" />

</WrapPanel>

Commented on 1.June 2010

Nice article.
Prasanta

Commented on 15.June 2010

very nice
suma

Commented on 31.August 2010

nice and light article


sm

Commented on 24.September 2010

I agree with the comment about wasting bandwith.


Why

Commented on 24.October 2010

I am new to WPF and am trying to convert a VB6 project to WPF using VB2010. We used a lot of Data
cstill
Repeaters in the VB6 project and I am looking for a replacement for that in WPF. What would be the best
replacement?

Commented on 4.January 2011

I have a wrap Panel. Now I want to add 1000 000 buttons into it. I write the method

CuongDV
private void AddButtons()

for (int i = 0; i < 10000; i++)

Button newBtn = new Button();

newBtn.Content = i.ToString();

wrapPanel1.Children.Add(newBtn);

But when run this code I see that the wrapPanel only display 1000 000 buttons after added 1000 0000

WrapPanel.html[2/16/2014 3:02:39 PM]


WPF Tutorial | Wrap Panel
completely. Now I want after adding each button, the wrapPanel will updateLayout(or refresh) immediately
so that I can see that button . Can you help me how to do that?

Commented on 4.March 2011

Totally agree with vb guy. I am visually oriented, so images are the best. I think the xaml is too long to read.
mike

The last paragraph should be titled conclusion for better clarity, text is too clutered.

Commented on 21.May 2011

I am wandering again and again. Very nice job. Thanks


Rahi,...

Commented on 22.June 2011

Miu
Thanks for to the point and simple description! Simplicity is rare! :)

Commented on 28.June 2011

Thanks,Nice artical.....
Gourav

Commented on 10.August 2011

I noticed this was copy righted. Can I still use a WrapPanel?


Mike

Commented on 17.August 2011

Excellent and strait forward example!


Roman P

Name

E-Mail (optional)

Comment

Post Comment

WrapPanel.html[2/16/2014 3:02:39 PM]


WPF Tutorial | ViewBox

Home
    Layout
    ViewBox Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to use the ViewBox in WPF
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics
Introduction
3D Graphics

Animation
The ViewBox is a very useful control in WPF. If does nothing more than scale to fit the content to the available size. It does not
resize the content, but it transforms it. This means that also all text sizes and line widths were scaled. Its about the same behavior as
Multimedia if you set the Stretch property on an Image or Path to Uniform.

Documents Although it can be used to fit any type of control, it's often used for 2D graphics, or to fit a scalable part of a user interface into an
screen area.
Windows 7
<Button Content="Test" />
Interoperability  
<Viewbox Stretch="Uniform">
Performance
<Button Content="Test" />
Expression Blend </Viewbox>
 
Tools

UI Automation
  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2009-05-19 00:16:31

ViewBox.html[2/16/2014 3:02:51 PM]


WPF Tutorial | ViewBox
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 17.July 2009

Textwrapping is not working with Viewbox.. I tried lots of.. please let me know if any solution or
Ujval
alternative

Commented on 17.July 2009

Hi Ujval,
Christian Moser
The viewbox gives it's content infinite space. Then is measures the size of the content and scales the
content, so that is fits into box. That is the reason why textwarpping is not working, because the
TextBlock has no reason to wrap the text, if infinite space is available.

Commented on 9.August 2009

Hi Moser ,
vimal

I have a problem using the viewbox control. I have a shape derived from frameworkelement. I am
getting these shapes dynamically. The dimension of these shapes is very small. What i need to do is
to show these shapes to a fixed size enlarged . say (width = 50, height = 50) . How can i do this.
What i did is , I made this shape inside a border set it a width and height. Then i put these inside a
viewbox and made stretch = fill . But it didnt work as i expected. The shape goes beyond 50 and a
lot more.. pls help.

Commented on 25.August 2009

I fixed it eventhough you didnt tell me a solution


vimal

Commented on 5.November 2009

Murad Mohd How you did it Vimal?


Zain

Commented on 18.November 2009

How can i set the background color of a VeiwBox? There is no property available for it :|
Raul

Commented on 19.January 2010

Murad Mohd vimal I like your solution. Thanks.


Zain

Commented on 21.January 2010

This is way too simplistic to actually be defined as a tutorial on the viewbox. Where is the data binding
James
to the viewbox, the many properties associated with the viewbox and the databinding to those
properties. How do you change the view within the viewbox, lets say that little button was a separate
user control with it's own code behind containing it's own event handlers and you clicked it and the
intent was to send a larger version of the button, scaled to not look like a brick from super mario
bros and display it in the viewbox. Not only that what if it had an enumeration of buttons and then
you wanted to display them in the viewbox like a dynamic picture viewer. Way to do the bare

ViewBox.html[2/16/2014 3:02:51 PM]


WPF Tutorial | ViewBox
minimum and stop, you could of at least provided a link that says, for more go to...

Commented on 29.January 2010

Great tutorial. That's all I needed. Thanks


Jean-Pierre...

Commented on 12.June 2010

I am making a image viewer. First I have Buttons inside a uniforgrid, I want to click the Button and
Betsy
send the image to a viewbox. Can you help me with this? Thanks for all the tutorials,they are very
helpful!!!

Commented on 24.June 2010

hi betsy,

vimal
If i get u right, then u can put a contentcontrol inside your viewbox and set the image as the content
of the content control. Hope this is what u need.

Commented on 24.June 2010

hi betsy,

vimal
If i get u right, then u can put a contentcontrol inside your viewbox and set the image as the content
of the content control. Hope this is what u need.

Commented on 27.June 2010

Thank-you vimal I'll work on that.


Betsy

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
C-MOSE
from another website

Commented on 6.January 2011

Hi, Can the viewbox tool display Pictures? and if the answer is yes, How to do so?
SHeeDeED

Commented on 10.February 2011

...

Commented on 7.April 2011

Can anybody tell me that why i cant set the value from code behind for the child element of Viewbox.
DragonBaki
For eg., I have the structure like this..

&lt;Border&gt;

&lt;ViewBox&gt;

&lt;TextBlock/&gt;

&lt;/ViewBox&gt;

&lt;/Border&gt;

In this structure, I need to display the textblock after animation. I cant able to this by making the
visibility property as visible from code behind as well as i cant able to set the text value from code
behind.. It shows the error as &quot;Object reference not set&quot;. Can anybody help me out to
overcome it..?

ViewBox.html[2/16/2014 3:02:51 PM]


WPF Tutorial | ViewBox

Commented on 16.April 2011

dfsgbdfsgdf
dfghsdfhsd

Commented on 24.May 2011

Hi How are you?


Bob Dole

Commented on 8.June 2011

That\'s way the besetst answer so far!


Velvet

Commented on 8.June 2011

i m fine
boom

Commented on 20.August 2011

hi,

Prathyusha

can we display viewbox as message box

Name

E-Mail (optional)

Comment

Post Comment

ViewBox.html[2/16/2014 3:02:51 PM]


WPF Tutorial | Create a Custom Layout Panel

Home
    Layout
    Create a Custom Layout Panel Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to create a Custom Layout Panel in WPF
Custom Controls
WPF already ships with a rich set of layout panels. Each of them fits to solve a particular problem.
Layout
Canvas - To arrange elements by X,Y coordinates.
Input
Grid - To arrange elements based on rows and columns.
Data Binding StackPanel - To stack elements horizontally or vertically.
DockPanel - To dock elements to a particular side.
Styling
WrapPanel - To stack elements and automatically begin a new row.
Localization
But sometimes none of the included layout panels helps you to arrange child elements in the way you like it. In this case its easy to
Interaction write your own layout panel. All you need to do is to create a new class that derives from Panel. There are two methods to override:
Resources
MeasureOverride - to determine the required size of the panel according to the desired size of the child elements and the
2D Graphics available space.
ArrangeOverride - to arrange the elements in the finally available space. The final size can be smaller than the requested.
3D Graphics
 
Animation public class MySimplePanel : Panel
Multimedia
{
// Make the panel as big as the biggest element
Documents protected override Size MeasureOverride(Size availableSize)
{
Windows 7
Size maxSize = new Size();
Interoperability  
foreach( UIElement child in InternalChildern)
Performance
{
Expression Blend child.Measure( availableSize );
maxSize.Height = Math.Max( child.DesiredSize.Height, maxSize.Height);
Tools maxSize.Width= Math.Max( child.DesiredSize.Width, maxSize.Width);
}
UI Automation
}
 
// Arrange the child elements to their final position
protected override Size ArrangeOverride(Size finalSize)

CustomLayoutPanel.html[2/16/2014 3:03:36 PM]


WPF Tutorial | Create a Custom Layout Panel
{
foreach( UIElement child in InternalChildern)
{
child.Arrange( new Rect( finalSize ) );
}
}
}
 
 

Popular Custom Panels


Here are some popular custom panels on the internet:

TreeMap Panel
Animating Tile Panel
Radial Panel
Element Flow Panel
Ribbon Panel

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2009-08-11 01:07:26


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 29.June 2009

Good example..
Venu

Commented on 10.August 2009

Not so good example - according to Microsoft http://msdn.microsoft.com/en-


Ido Ran
us/library/system.windows.frameworkelement.measureoverride.aspx

you should call Measure on each of the children before getting their DesiredSize - you forgot to do
that.

Commented on 11.August 2009

Hi Ido,

Christian
thanks for the feedback. I really forgot to call Measure(). I corrected it in the example.
Moser

Commented on 7.April 2010

You're also not returning the values in the methods. This wont compile
Chris

Commented on 31.August 2010

Very nice article


Rajesh

CustomLayoutPanel.html[2/16/2014 3:03:36 PM]


WPF Tutorial | Create a Custom Layout Panel

Commented on 6.September 2010

some more clear


vishnuvardhan

Commented on 18.November 2010

As someone already said, you aren't returning the values from methods and "Children" is spelled
Steve
incorrectly in "InternalChildern" [sic].

Name

E-Mail (optional)

Comment

Post Comment

CustomLayoutPanel.html[2/16/2014 3:03:36 PM]


WPF Tutorial | Keyboard

Home
    Input
    Keyboard Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to Convert a System.Windows.Input.Key to a Char
Custom Controls
Today i wanted to write a custom input control that hooks up to the KeyDown event of a CustomControl to collect the typed chars. In
Layout the KeyEventArgs you find a e.Key that is of type System.Windows.Input.Key. I tried to use the KeyConverter or cast
it to a char or string, but nothing seems to work.
Input
 
Data Binding
private string _text = string.Empty;
Styling  
void MyControl_KeyDown(object sender, KeyEventArgs e)
Localization
{
Interaction _text += e.Key;
}
Resources  
 
2D Graphics The solution is to hook to another event called TextInput. The provided TextCompositionEventArgs has a Text property
3D Graphics
that is excatly what we want. The event handler will look like this:

 
Animation
void MyControl_TextInput(object sender, TextCompositionEventArgs e)
Multimedia {
_input += e.Text;
Documents
}
Windows 7  
 
Interoperability

Performance   ► Tutorial   ► Convert Unicode   ► Convert Text   ► Convert C#
Expression Blend

Tools Last modified: 2009-06-17 17:31:13


Copyright (c) by Christian Moser, 2011.

UI Automation

 Comments on this article

ConvertKeyToChar.html[2/16/2014 3:03:49 PM]


WPF Tutorial | Keyboard
Show all comments

Commented on 6.May 2009

is it really working ?
nandy

Commented on 19.May 2009

Can you explain it a bit more?


Vimal

Commented on 27.May 2009

Can WPF application windows can process mouse events through SendMessage() notifications (with or
KingMarcusVi...
without mouse pointer hovering above its window)?

Commented on 18.June 2009

First example is NOT WORK.


George

Commented on 26.June 2009

I tried its not working.


sara

Commented on 26.June 2009

Hi, what exactly is not working?

Christian
Did you register the eventhandler? TextInput += MyControl_TextInput;

Moser
Do you receive the entered text in the _text string?

Commented on 11.August 2009

Heres some keyboard input for you buddy.

Mr Sda
Your a boss eyed jack ass.

Commented on 6.September 2009

Agree with Mr.Sda


Agree

Commented on 17.December 2009

Oh, good joke) Why do birds fly south for the winter? It's quicker than driving.
tarahgiv
___________________________

<a href= http://ordervigerausa.fizwig.com/site_map.html >cealis order San Jose</a>

Commented on 7.January 2010

This does not work !!


Jonathan

Commented on 28.January 2010

TextBox will mark the key press as handled, use PreviewTextInput event.
Phil

Commented on 2.March 2010

Code is not working....


ajay sharma

ConvertKeyToChar.html[2/16/2014 3:03:49 PM]


WPF Tutorial | Keyboard

Commented on 23.August 2010

2 things:

COPYRIGHT

1. you paki's are dumb as hell

2.COPYRIGHT INFRINGEMENT AT ITS FINEST!!!!!!!!!

MOSER IS GREASY AS HELL

Commented on 23.August 2010

Its funny that you guys find my articles so helpful considering I just copy and pasted random shit from
Christian
other random sites that I found. Its all good though because those google ads are making me cash!!!

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
Christian M
from another website

Name

E-Mail (optional)

Comment

Post Comment

ConvertKeyToChar.html[2/16/2014 3:03:49 PM]


WPF Tutorial | RoutedCommands in a ContextMenu

Home
    Input
    RoutedCommands in a ContextMenu Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to Solve Execution Problems of RoutedCommands in a WPF
Custom Controls
ContextMenu
Layout

Input
The Problem
Data Binding
I recently run into a problem, with RoutedCommands in a ContextMenu. The problem was, that the commands could not be
Styling executed, even if the CommandBinding on the parent window allowed it.
Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation
The following example shows the problem with simple window that has a Menu and a ContextMenu on it. Both menus contains a
Multimedia
MenuItem with a "Cut" command set.
Documents
 
Windows 7 <Window x:Class="RoutedCommandsInPopups.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Interoperability xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
Performance
<StackPanel x:Name="stack" Background="Transparent">
Expression Blend <StackPanel.ContextMenu>
<ContextMenu>
Tools <MenuItem Header="Cut" Command="Cut" />
UI Automation
</ContextMenu>
</StackPanel.ContextMenu>
<Menu>
<MenuItem Header="Edit" >
<MenuItem Header="Cut" Command="Cut" />

RoutedCommandsInContextMenu.html[2/16/2014 3:04:04 PM]


WPF Tutorial | RoutedCommands in a ContextMenu
</MenuItem>
</Menu>
</StackPanel>
</Window>
 
 
In the codebehind of the Window I added a CommandBinding to handle the "Cut" command.

 
public Window1()
{
InitializeComponent();
 
CommandBindings.Add(
new CommandBinding(ApplicationCommands.Cut, CutExecuted, CanCut));
}
 
private void CutExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Cut Executed");
}
 
private void CanCut(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
 
 

The Reason
The reason is, that ContextMenus are separate windows with their own VisualTree and LogicalTree.

The reason is that the CommandManager searches for CommandBindings within the current focus scope. If the current focus scope
has no command binding, it transfers the focus scope to the parent focus scope. When you startup your application the focus scope
is not set. You can check this by calling FocusManager.GetFocusedElement(this) and you will receive null.

The Solution

Set the Logical Focus

The simplest solution is to initially set the logical focus of the parent window that is not null. When the CommandManager searches
for the parent focus scope it finds the window and handels the CommandBinding correctly.

 
public Window1()
{
InitializeComponent();
 
CommandBindings.Add(
new CommandBinding(ApplicationCommands.Cut, CutExecuted, CanCut));
 
// Set the logical focus to the window
Focus();
}
 
 
RoutedCommandsInContextMenu.html[2/16/2014 3:04:04 PM]
WPF Tutorial | RoutedCommands in a ContextMenu
...or the same in XAML
 
<Window x:Class="RoutedCommandsInPopups.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
FocusManager.FocusedElement="
{Binding RelativeSource={x:Static RelativeSource.Self}, Mode=OneTime}>
...
</Window>
 
 
Manually bind the CommandTarget

Another solution is to manually bind the CommandTarget to the parent ContextMenu.

 
<MenuItem Header="Cut" Command="Cut" CommandTarget="
{Binding Path=PlacementTarget,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}}}"/>
 
 

  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Web Design Books

Last modified: 2009-06-17 12:26:26


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 26.January 2010

very useful. thanks.


alex

Commented on 26.March 2010

ads
a

Commented on 20.April 2010

Now that is the best idea I've read all day. Thank you for posting it.
speed

Commented on 21.April 2010

Super!
Dario
thanks

Commented on 5.May 2010

At last! That's what I was looking for.


Ed

RoutedCommandsInContextMenu.html[2/16/2014 3:04:04 PM]


WPF Tutorial | RoutedCommands in a ContextMenu

Commented on 28.July 2010

Thank you for that, saved me a lot of time.


Andreas

Commented on 14.November 2010

Nice tutorial.really saved my time


Aftab

Commented on 29.December 2010

did not help in my situation.


a

Commented on 20.April 2011

Thank you. Your post really helped me. I've been looking into this problem for 2 days, and your post
Kai
answered my question.

Commented on 6.June 2011

thanks :)
serine

Name

E-Mail (optional)

Comment

Post Comment

RoutedCommandsInContextMenu.html[2/16/2014 3:04:04 PM]


WPF Tutorial | Mouse

Home
    Input
    Mouse Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Mouse Handling in WPF
Custom Controls

Layout
How to get the Absolute Position of the Mouse on the Screen
Input
You can call Mouse.GetPosition(this) on any WPF element. This function returns the relative offset of the mouse to the upper
Data Binding left corner of your control.

Styling To get the absolute screen cordinates, call the PointToScreen() function.

Localization  
Point absoluteScreenPos = PointToScreen( Mouse.GetPosition( new Point(), this ));
Interaction
 
Resources  

2D Graphics
  ► Tutorial   ► ActionScript   ► Flash CS3   ► Loaded
3D Graphics

Animation
Last modified: 2009-06-17 17:39:50
Multimedia Copyright (c) by Christian Moser, 2011.

Documents

Windows 7
 Comments on this article
Interoperability
Show all comments
Performance

Expression Blend Commented on 11.August 2009

Johhny This is how you do it in WPF NOT JAVA, for gods sake.
Tools
Rubber
UI Automation
Commented on 22.February 2010

Thank you very much ! it's so hard to find a good solution to do that !
David

Mouse.html[2/16/2014 3:04:39 PM]


WPF Tutorial | Mouse

Commented on 14.September 2010

Johhny Rubber wrote " This is how you do it in WPF NOT JAVA, for gods sake."

Jeff

This is a WPF tutorial and not Java, so why would you think otherwise?

Commented on 6.February 2011

It really works!
balaji

Commented on 15.February 2011

Jeff wrote "This is a WPF tutorial and not Java, so why would you think otherwise?"

Paul

Perhaps somebody was talking about Java, and Johnny was trying to correct them by telling them that
this is a WPF tutorial.

Commented on 1.April 2011

Java? wtf? That&Acirc;&acute;t not possible, for gods sake. Think...


Alisator

Commented on 1.May 2011

Nice tut.
Brandon

Commented on 27.September 2011

hi, is there a way to set the position of the mouse?


xl

Name

E-Mail (optional)

Comment

Post Comment

Mouse.html[2/16/2014 3:04:39 PM]


WPF Tutorial | Mutli Touch

Home
    Input
    Mutli Touch Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Introduction to Multitouch Programming in WPF 4.0
Custom Controls
Please note: This article is outdated and needs to be updated!
Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability
Windows 7 and .NET 4.0 only
Performance

Expression Blend In version 4.0 of the .NET framework, Microsoft supports multitouch programming. The .NET API builds on the native Win32 API that
is only available in Windows 7 and later versions. You can simulate multitouch on Windows Vista by using a special user input
Tools management layer that emulates multitouch on a normal PC.
UI Automation

What is availabel in Beta 1


The manipulation events are already available in Beta 1, but the WPF controls do not take use of them. In later versions you can just

Multitouch2.html[2/16/2014 3:04:51 PM]


WPF Tutorial | Mutli Touch
enable manipulation of sliders or scrollviewers on control level

How to handle multitouch input


Multitouch gestures like scaling, panning or rotating are already preprocessed by the underlying layer. You will receive the result in
form of an Manipulation struct that contains a Expansion, Rotation, Scale and Translation. The information is
provided in four maniuplation events:

ManipulationStarted
ManipulationDelta
ManipulationStarting
ManipulationCompleted

To enable receiving manipulation events you have to set the ManipulationMode to the manipulations you want to enable. If you
want to receive all kind of manipulations, you can set the ManipulationMode="All".

How to create a simple WPF multitouch foto viewer


Create a new WPF 4.0 solution.

 
public class TouchImage : Image
{
private MatrixTransform _matrixTransform;
 
public TouchImage()
{
ManipulationMode = ManipulationModes.All;
_matrixTransform = new MatrixTransform();
RenderTransform = _matrixTransform;
}
 
protected override void OnManipulationDelta(ManipulationDeltaEventArgs e)
{
var manipulation = e.GetCumulativeManipulation((IInputElement)Parent);
 
var delta = e.GetDeltaManipulation((IInputElement)Parent);
Matrix matrix = _matrixTransform.Matrix;
 
var originalCentre = new Point(ActualWidth / 2, ActualHeight / 2);
matrix.Translate(delta.Translation.X, delta.Translation.Y);
matrix.Transform(originalCentre);
 
var centre = matrix.Transform(originalCentre);
matrix.RotateAt(delta.Rotation, centre.X, centre.Y);
 
centre = matrix.Transform(originalCentre);
matrix.ScaleAt(delta.Scale, delta.Scale, centre.X, centre.Y);
 
_matrixTransform.Matrix = matrix;
e.Handled = true;
 
base.OnManipulationDelta(e);
}
}

Multitouch2.html[2/16/2014 3:04:51 PM]


WPF Tutorial | Mutli Touch
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2010-05-17 23:52:20


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 24.November 2009

Typo: availabel -> What is availabel in Beta 1


Diego

Commented on 29.December 2009

WoW,oh my god
saman

Commented on 30.January 2010

Look at the Title in the Menu: Mutlitouch


-

Commented on 12.February 2010

You mentioned "emulates multitouch on a normal PC" .Will it work for normal monitor(any pc
Bala
monitors)?

Commented on 17.February 2010

Bala, of course that will not work on any normal monitor. One thing are PCs and another thing are
Josep
monitors. You need to capture the points that you touch.

Sorry, my english is not very good.

Commented on 3.March 2010

Ok...Thanks. Josep :)
Bala

Commented on 11.March 2010

no props
heman

Commented on 18.March 2010

hi ..

Mohammed

thanks for the tutorial but i have small problem.

my problem is e.GetCumulativeManipulation is not exist in my visual studio 2010

what i can do..

i use winxp sp3..

Multitouch2.html[2/16/2014 3:04:51 PM]


WPF Tutorial | Mutli Touch
bye.

Commented on 21.May 2010

Just a friendly tip regarding your website's banner: http://theoatmeal.com/comics/apostrophe


Rob

Commented on 23.August 2010

COPYRIGHT INFRINGEMENT AT ITS FINEST!!!!!!!!!

FBI

MOSER IS GREASY AS HELL

Commented on 23.August 2010

YOU LOOK LIKE A GOOF IN YOUR PICTURE HAHAHA


FBI

Commented on 5.October 2010

The title in the menu system under "Input">"Mutli Touch" is not spelled correctly. (someone else
another-
commented in January but you still haven't fixed it. :P

Commented on 9.December 2010

I Christian!!!

Eduardo
You are using manipulationdelta, but if i want define a new gesture, how can i do?, example, fix one
touch, and second touch move vertical that mean in 3D rotate axis X, another example, if i fix one
touch and second touch move horizontal that mean in 3d rotate axis Y

please i hope your answer.

Commented on 2.February 2011

another-

Myth
This guy just copied and pasted bits and pieces of tutorials onto his own website (look in the comment
sections on multiple of the 'tutorials' he even admits it lol); I'm sure the typos are in the source as well

Commented on 16.February 2011

Kuldeep Nice WOrk..


Verma

Commented on 28.February 2011

Mutley touch? menu fail mutlitouch


Mutli

Commented on 10.May 2011

B. Clay Yes, mutlitouch is a new pattern, paradigm, or practice where you code with a pooch at your side.
Shannon

Name

E-Mail (optional)

Comment

Multitouch2.html[2/16/2014 3:04:51 PM]


WPF Tutorial | Mutli Touch
Post Comment

Multitouch2.html[2/16/2014 3:04:51 PM]


WPF Tutorial | Debug DataBinding Issues

Home
    Data Binding
    Debug DataBinding Issues Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Debug Databinding Issues in WPF
Custom Controls
DataBinding is one of the most powerful features in WPF. But because it resolves the bindings at runtime and does not throw
Layout exceptions, it's sometimes hard to find the reason why the data do not appear as expected.
There are mainly two reasons:
Input
The DataBinding expression is invalid. Then use Trace Output to resolve.
Data Binding The DataBinding expression is valid, but the result is not the expected. Then use a Debug Converter to resolve it.

Styling

Localization Method 1: Trace messages in the output window


Interaction In the example, the text property of the TextBlock is bound to the property "InvalidPath" of the StackPanel - which does not exists.

Resources  
<Window x:Class="DebugDataBinding.Window1"
2D Graphics xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3D Graphics
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<StackPanel x:Name="stack">
Animation <TextBlock Text="{Binding ElementName=stack, Path=InvalidPath}" />
</StackPanel>
Multimedia
</Window>
Documents  
 
Windows 7 In this case the invalid databinding expression is reported by a trace message in the output window

Interoperability
System.Windows.Data Error: 39 : BindingExpression path error: 'InvalidPath' property not
Performance found on 'object' ''StackPanel' (Name='stack')'. BindingExpression:Path=InvalidPath;
DataItem='StackPanel' (Name='stack'); target element is 'TextBlock' (Name=''); target
Expression Blend property is 'Text' (type 'String')
Tools
Note: Binding to a path of a property that has NULL value is a valid expression and does not generate an error message (for e.g.
UI Automation binding to a property of the data context that is NULL).

Adjust the trace level (.NET 3.5 and higher)

DebugDataBinding.html[2/16/2014 3:05:07 PM]


WPF Tutorial | Debug DataBinding Issues
NET3.5 has a new feature that allows you to set the level of details of trace messages to None, Low, Medium or High.

To set the trace level you have to include an extra namespace to your XAML:

 
<Window x:Class="DebugDataBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase">
 
<StackPanel x:Name="stack">
<TextBlock Text="{Binding ElementName=stack, Path=InvalidPath,
diag:PresentationTraceSources.TraceLevel=High}" />
</StackPanel>
</Window>
 
 
 
The following snipped shows how to adjust the trace level by code:
 
PresentationTraceSources.DataBindingSource.Listeners.Add(
new ConsoleTraceListener());
 
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.All;
 
 

Method 2: Use a ValueConverter to break into the debugger


A simple trick is to write a value converter that does nothins except breaking into the debugger. All you need to do now is to add this
converter to the binding expression that fails and you can easily see the values that should be bound.
 
/// <summary>
/// This converter does nothing except breaking the
/// debugger into the convert method
/// </summary>
public class DatabindingDebugConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
Debugger.Break();
return value;
}
 
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
Debugger.Break();
return value;
}
}
 
 
To use the converter in XAML, reference the namespace of the assembly that contains the converter and add an instance of it to the
resources of your window.

DebugDataBinding.html[2/16/2014 3:05:07 PM]


WPF Tutorial | Debug DataBinding Issues
 
<Window x:Class="DebugDataBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DebugDataBinding"
Title="Window1" Height="300" Width="300">
 
<Window.Resources>
<local:DatabindingDebugConverter x:Key="debugConverter" />
</Window.Resources>
 
<StackPanel x:Name="stack">
<TextBlock Text="{Binding ElementName=stack, Path=ActualWidth,
Converter={StaticResource debugConverter}}" />
</StackPanel>
</Window>
 
 

  ► Tutorial   ► C Sharp Tutorial   ► ASP Net Tutorial   ► VB Net

Last modified: 2009-06-08 08:31:10


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 23.March 2009

No one proofreads these articles, do they?


J

Commented on 25.March 2009

No, it's just me writing and publish them. But I am anxious to provide technically correct information. If
Christian
someone notices a mistake, I will correct it.
Moser

Commented on 29.March 2009

I believe 'J' was referring to the second bullet point of the introduction:

drewed
"The DataBinding expression is valid, but it . Then use Method 2 to resolve"

But it what?

Commented on 2.April 2009

does "nothins" except....


IC

Commented on 3.June 2009

Need A example to bind data from sql server to controls...


Vishal

Commented on 5.June 2009

DebugDataBinding.html[2/16/2014 3:05:07 PM]


WPF Tutorial | Debug DataBinding Issues

Hi Vishal,

Christian
you cannot bind data from an SQL database directly to WPF controls. You need to load the data into
Moser
objects first. This is because WPF binding depends on properties. You can use LINQ to SQL, Entity
Framework or Typed Datasets to nao your data in objects.

I hope this helps.

Commented on 5.June 2009

Another solution is to implement a trace listener that you add to the DataBindingSources
Ben
TraceListenerCollection in PresentationTraceSources. You can override the TraceEvent methods
implemented by the trace listener and either throw an exception or call Debugger.Break() to break into
the debugger whenever a data binding error occurs.

Commented on 31.July 2009

Thanks ... very helpful


Richard

Commented on 28.August 2009

very useful
Elia

Commented on 23.September 2009

Is it possible to bind the XML directly?


sathish

Commented on 3.October 2009

Salam :)

MAF
No you can't, you can use LINQ to XML or use an instance of XmlDataProvider.

Commented on 13.November 2009

very nice article


Farzad
specially the second part

Commented on 1.December 2009

Another solution is to declare ExceptionValidationRule in Binding.ValidationRules. It causes all


Ricibald
exceptions thrown in the databinding process to be reported as validation errors.

Commented on 14.April 2010

Fantastic. You should work for MS and this should be in MSDN Library!
Tony Wall

Commented on 8.May 2010

Another solution is to implement a trace listener that you add to the DataBindingSources
Ben
TraceListenerCollection in PresentationTraceSources. You can override the TraceEvent methods
implemented by the trace listener and either throw an exception or call Debugger.Break() to break into
the debugger whenever a data binding error occurs.

Commented on 29.June 2010

Ricibald: Can you post an example of how this is done? Also will all this work with Silverlight 4.0?
Eric

DebugDataBinding.html[2/16/2014 3:05:07 PM]


WPF Tutorial | Debug DataBinding Issues

Commented on 1.July 2010

A similar post written long back - http://www.beacosta.com/blog/?p=52


akjoshi

Commented on 20.July 2010

Hi Christian,

Bala

Could you please let me know how and where Path=ActualWidth is getting is used in the above
example 2

Commented on 9.September 2010

Thanks a million! This helped us solve a similar problem with Silverlight 4.0. We were trying to bind an
Lily
IsChecked property of a ToggleButton to an IsChecked custom DependencyProperty of a custom
control.

Commented on 30.January 2011

Thank you very much for this cool idea. To ensure that the ValueConverter is indeed "reached", use the
WPF-Coder
following data binding:

{Binding RelativeSource={RelativeSource Self},Converter={StaticResource debugConverter}}

Cheers, Ingo.

Commented on 9.February 2011

WOW its gud but j= "chuitya". what is that


deepak

Commented on 22.February 2011

Thanks for a great tip. I had a problem with Blend though. I can use the debug converter in VS, but if I
Yossu
add it using the Blend interface, Blend crashes. This happens consistently with this converter, on any
control. Blend behaves fine with other converters.

Any ideas? Thanks again

Commented on 28.February 2011

i am new to wpf.i think their is no proper decoupling between code behind and design code
vv

Commented on 23.March 2011

So you can leave the converter in place during development, and strip out later, use this approach
Allen
where you see if a debugger is in fact attached to the process (OTHERWISE, your app halts and waits
patiently for you in this routine!):

/// &lt;summary&gt;

/// Public method Convert(object value, Type targetType, object parameter, CultureInfo culture)

/// &lt;/summary&gt;

/// &lt;param name=&quot;value&quot;&gt;&lt;/param&gt;

/// &lt;param name=&quot;targetType&quot;&gt;&lt;/param&gt;

/// &lt;param name=&quot;parameter&quot;&gt;&lt;/param&gt;

/// &lt;param name=&quot;culture&quot;&gt;&lt;/param&gt;

/// &lt;returns&gt;&lt;/returns&gt;

public object Convert(object value, Type targetType,

DebugDataBinding.html[2/16/2014 3:05:07 PM]


WPF Tutorial | Debug DataBinding Issues
object parameter, CultureInfo culture)

if (Debugger.IsAttached)
Debugger.Break();

else

Logger.DebugFormat(&quot;Binding value in {0} = {1}&quot;,


&quot;DatabindingDebugConverter::Convert&quot;, value);

return value;

Commented on 9.June 2011

Do u have any tutorial on C#,asp.net,wcf,SilverLight or any of these?If not then please provide me the
sun
useful links

Name

E-Mail (optional)

Comment

Post Comment

DebugDataBinding.html[2/16/2014 3:05:07 PM]


WPF Tutorial | Popular Data Binding Expressions

Home
    Data Binding
    Popular Data Binding Expressions Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Popular DataBinding Expressions
Custom Controls

Layout
DataContext Bindings
Input
Each control in WPF has a DataContext property. It's meant to be bound to an object that contains the data to be displayed.
Data Binding
The DataContext property is inherited along the logical tree.
Styling
{Binding} Binds object in the DataContext
Localization Binds the Name property of the object in the
{Binding Name}
DataContext
Interaction
Binds the Length property of the Name
Resources
{Binding Name.Length}
property of the object in the DataContext.
2D Graphics

3D Graphics
RelativeSource Binding
Animation
The relative source mode of the binding extension helps you to bind to an object with an relative relation to you. You don't
Multimedia know your or its abolute position, but you know if it's the previous or next item, two levels above you or of an specific type.
Documents
Bind to your self. Helpful to access your own
{Binding RelativeSource={RelativeSource Self}}
Windows 7 properties.
{Binding Text, RelativeSource={RelativeSource Self}} Binds Text property of the target element.
Interoperability
{Binding IsSelected, RelativeSource={RelativeSource
Binds to the IsSelected property of a parent
Performance Mode=FindAncestor,AncestorType={x:Type
element of type ListBoxItem.
ListBoxItem}}}
Expression Blend

Tools

UI Automation
Current Item of Collection Bindings

The slash is a special operator that lets you access the current item of a collection view.

Binds to the current item of a collection in the



{Binding /}

BindingExpressions.html[2/16/2014 3:05:42 PM]


WPF Tutorial | Popular Data Binding Expressions
data context.
Binds to the current item of a collection from

{Binding Customers/} the Customer property within the data
context.
Binds to the Name property of the current item

{Binding Customers/Name} of the Customer collection within the data
context.

  ► Tutorial   ► After Effects   ► Book Binding   ► Book Printing

Last modified: 2009-12-23 07:45:26


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 2.February 2010

if have examples that more understand.


mr.Ha

Commented on 17.February 2010

If learn English understand better :)


Ilya

Commented on 23.February 2010

I logged in just to say LOL


Saqib

Commented on 28.February 2010

I have gases
Yo

Commented on 28.March 2010

THANKS A LOT
Atul Raina

Commented on 22.April 2010

Current Item? I've not heard of that usage. Very interesting.


ErkDog

Commented on 28.May 2010

More examples
More

Commented on 1.July 2010

Might I suggest adding some examples with type-qualified properties in the binding path? This is
Mike
sometimes necessary to work around ambiguous matches caused by member name collisions. For
Strobel
example, say you have a 'Customer' class that has two 'Name' properties--one defined by the class itself
and another defined by an 'IEntity' interface that Customer implements. To bind to the correct property,
you would need to qualify it with the declaring type:

BindingExpressions.html[2/16/2014 3:05:42 PM]


WPF Tutorial | Popular Data Binding Expressions
{Binding Path=(entities:Customer.Name).Length}

{Binding Path=(entities:IEntity.Name).Length}

This syntax is especially useful if you are using a tool like ReSharper, which can provide smart completion
for PropertyPath expressions in Xaml, but only if the first property in the path can be resolved at design
time. You also get some level of compile-time verification that your PropertyPath expressions are correct.

Commented on 8.July 2010

Binding a System.Data.DataTable

Tod

{Binding Path=[my_column_name]}

Commented on 1.September 2010

Nice post
Vikas

Commented on 15.February 2011

very nice examples


kiran more

Commented on 4.March 2011

Is possible a binding to a static property?


zinov

Commented on 6.May 2011

why it's look different then what i know?but thanks for the post
loque

Name

E-Mail (optional)

Comment

Post Comment

BindingExpressions.html[2/16/2014 3:05:42 PM]


WPF Tutorial | How to Bind EnumValues

Home
    Data Binding
    How to Bind EnumValues Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to Bind to Values of an Enum
Custom Controls

Layout

Input

Data Binding

Styling
You cannot directly bind the values of an enum to a WPF list control, because the enum type does not provide a property that
Localization returns all values. The only way to get the names is to call the GetNames() method. But how to call a method from XAML?
Interaction The trick is to use an ObjectDataProvider, that allows us to specify the name of a method and their parameters and he invokes it
from XAML. The result can be used by using a normal data binding
Resources

2D Graphics
 
3D Graphics xmlns:sys="clr-namespace:System;assembly=mscorlib"
Animation
 
<Window.Resources>
Multimedia <ObjectDataProvider x:Key="aligmnments"
MethodName="GetNames" ObjectType="{x:Type sys:Enum}">
Documents
<ObjectDataProvider.MethodParameters>
Windows 7 <x:Type TypeName="VerticalAlignment" />
</ObjectDataProvider.MethodParameters>
Interoperability </ObjectDataProvider>
</Window.Resources>
Performance
 
Expression Blend  
 
Tools <ComboBox ItemsSource="{Binding Source={StaticResource aligmnments}}" />
 
UI Automation  

  ► Tutorial   ► Photoshop CS4   ► Book Printing   ► Book Binding

BindEnumValues.html[2/16/2014 3:06:01 PM]


WPF Tutorial | How to Bind EnumValues

Last modified: 2009-06-12 17:42:05


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 9.September 2009

I was just wondering if we could use IValueConverter in order to bind enums.


Pavan

Commented on 9.September 2009

I think this is incomplete example. what is TypeName argument in


Ravi
<ObjectDataProvider.MethodParameters>

<x:Type TypeName="VerticalAlignment" />

</ObjectDataProvider.MethodParameters>

Commented on 9.September 2009

Hi Ravi,

Christian
it's not incomplete. The ObjectDataProvider calls the static method "GetNames()" on the "Enum" type.
Moser
This method requires a type object as parameter. This is resolved by the <x:Type /> markup
extension. It resolves a type object by a specified name. It's equal to typeof(VerticalAlignment) in C#.

Commented on 29.September 2009

I don't think it's very smart to bind a control to enumeration members at all. For one, it doesn't allow
tsahi
localization of the GUI. And secondly, the user will see things like ReallyBigNumber instead of the
string "Really Big Number", which is something he can understand more easily.

Commented on 20.July 2010

Personally, I like this solution for binding enum values:

Anubisascends

http://www.ageektrapped.com/blog/the-missing-net-7-displaying-enums-in-wpf/

This allows you to handle localization an more 'user-friendly' display values.

Commented on 21.March 2011

test
tesdt

Name

E-Mail (optional)
Comment

Post Comment

BindEnumValues.html[2/16/2014 3:06:01 PM]


WPF Tutorial | How to Bind EnumValues

BindEnumValues.html[2/16/2014 3:06:01 PM]


WPF Tutorial | Elegant way for INotifyPropertyChanged

Home
    Data Binding
    Elegant way for INotifyPropertyChanged Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
An elegant way to implement INotifyPropertyChanged
Custom Controls

Layout
Introduction
Input
A very common and popular way to synchronize data between the model and the view in WPF is using DataBinding. The value of the
Data Binding model is transferred to the view once, when the binding is initialized. But for every subsequent change, the model must notify the
binding to transfer the value again. This is done by implementing the INotifyPropertyChanged interface on the model.
Styling
In the setter of every bound property there must be some code to raise the PropertyChanged event, passing the name of the
Localization
modified property as a string. This has some disadvantages:
Interaction
You cannot use Auto-properties
Resources The property name is passed as a string. This brings ugly errors, when you forgot to change the string after a rename.
Every property needs extra code
2D Graphics

3D Graphics
The basic way to do it
Animation
 
Multimedia
private string _name;
Documents  
public string Name
Windows 7 {
Interoperability
get { return _name; }
set
Performance {
_name = value;
Expression Blend
PropertyChanged("Name");
Tools }
}
UI Automation  
private void PropertyChanged(string prop)
{
if( PropertyChanged != null )

INotifyPropertyChanged.html[2/16/2014 3:06:37 PM]


WPF Tutorial | Elegant way for INotifyPropertyChanged
{
PropertyChanged(this, new PropertyChangedEventArgs(prop);
}
}
 
 
 

A more elegant way to do it


The basic implementation requires two lines of code in the setter and the property name is passed as a string, which is not very
robust. A more elegant solution is to use the power of expression trees to get the property name out of a lambda expression. The
result looks like this:

 
private string _name;
public string Name
{
get { return _name; }
set { PropertyChanged.ChangeAndNotify(ref _name, value, () => Name); }
}
 
 
 
public static bool ChangeAndNotify<T>(this PropertyChangedEventHandler handler,
ref T field, T value, Expression<Func<T>> memberExpression)
{
if (memberExpression == null)
{
throw new ArgumentNullException("memberExpression");
}
var body = memberExpression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("Lambda must return a property.");
}
if (EqualityComparer<T>.Default.Equals(field, value))
{
return false;
}
 
var vmExpression = body.Expression as ConstantExpression;
if (vmExpression != null)
{
LambdaExpression lambda = Expression.Lambda(vmExpression);
Delegate vmFunc = lambda.Compile();
object sender = vmFunc.DynamicInvoke();
 
if( handler != null)
{
handler(sender, new PropertyChangedEventArgs(body.Member.Name));
}
}
 
field = value;
return true;

INotifyPropertyChanged.html[2/16/2014 3:06:37 PM]


WPF Tutorial | Elegant way for INotifyPropertyChanged
}
 
 
The solution is ispired by the following articles:

http://blog.decarufel.net/2009/07/how-to-use-inotifypropertychanged-type_22.html
http://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist<7a>

Last modified: 2011-03-03 20:28:18


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 4.March 2011

The property value needs to be set before the notification.


Adrian Cole

Commented on 8.March 2011

I am testing this out now.


Jared
Barneck
Thanks,

Jared

Http://www.rhyous.com

Commented on 26.April 2011

What about using Reflection, like &quot;MethodBase.GetCurrentMethod&quot;, for giving name of the
Manu Reva
property.
Do we expect performance issue ? or it is just too ugly :-)

Commented on 12.July 2011

Denis What about when you obfuscate the code?


González

Commented on 21.July 2011

If I was debugging this code. I would appreciate the basic way


Jim Yost

Name

E-Mail (optional)

Comment

INotifyPropertyChanged.html[2/16/2014 3:06:37 PM]


WPF Tutorial | Elegant way for INotifyPropertyChanged
Post Comment

INotifyPropertyChanged.html[2/16/2014 3:06:37 PM]


WPF Tutorial | Evaluate a localization mechanism

Home
    Localization
    Evaluate a localization mechanism Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to evaluate a localization mechanism
Custom Controls

Layout
Criterias for evaluation
Input
To choose an appropriate localization mechanism you have to find one that meets the requirements and your companys established
Data Binding translation process.

Styling Criterias to compare the localization mechanisms among each others:

Localization Dynamic language switching


Interaction Usage in XAML and Code
Types of applicable resources
Resources
Ease and flexibility of use
2D Graphics Translation performance

3D Graphics

Animation
Different WPF translation mechanisms compared
Multimedia Localization using a MarkupExtension
Localization using Satellite Assemblies
Documents

Windows 7

Interoperability   ► Tutorial   ► Pro Engineer   ► Pro E CAD   ► Sketch Pro

Performance

Expression Blend Last modified: 2010-02-25 08:31:07


Copyright (c) by Christian Moser, 2011.

Tools

UI Automation
 Comments on this article

Show all comments

EvaluateLocalizationMechanism.html[2/16/2014 3:06:56 PM]


WPF Tutorial | Evaluate a localization mechanism

Commented on 5.April 2010

I am learning WPF from this amazing Website, I started from the beginning and here I am, i would like to
Maher...
thank you Cristain , Thank you very much

Commented on 11.July 2011

Hi.. I'm very eager to know more about WPF, cause I'm thinking if I can use it in my thesis.. I hope I could
24ml
Learn here more.. but thank you for this new Knowledge :)

Name

E-Mail (optional)

Comment

Post Comment

EvaluateLocalizationMechanism.html[2/16/2014 3:06:56 PM]


WPF Tutorial | Localization using a MarkupExtension

Home
    Localization
    Localization using a MarkupExtension Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Localization of a WPF application using a custom MarkupExtension
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents
The Idea
Windows 7
A simple and effective way to localize application resources is to write a custom MarkupExtension that provides a localized value. The extension
Interoperability
takes a parameter in the constructor that is the unique resource key. When the DepdendencyProperty asks for the value, the markup extension looks
Performance up the value from a generic resource provider. This gives you the flexibility to reuse the resource management and translation process that is already
established within your company.
Expression Blend
Using a custom markup extension has some advantages
Tools
Lightweight and flexible solution
UI Automation
Dynamic language switch at runtime
Works with any kind of resource providers.

Other Implementations
The idea of using a markup extension for localization is not unique by me. There are also other similar implementations out there. Here you find some
links:

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension
LocalizeExtension by Bernhard Millauer
Resx MarkupExtension by Grant Frisken

How to use it
The usage of the markup extension is very simple. Just replace the string you want to localize by {l:Translate resourceKey}.

 
<TextBlock Text="{l:Translate CustomerForm.FirstName}" />
 
 

Implementation details of the translation infrastructure


The translation infrastructure consists of the folling parts

Translation manager

The translation manager is a static class that manages the current language and notifies all markup extensions, to update their values when the
language changes. It also provides access to translated resources. The resources itself are provided by a generic translation provider.

Translate markup extension



The tanslate markup extension knows the resource key and provides the translated value. It listens to the LanguageChanged event of the
translation manager and updates its value. This event handler is implemented by the weak event pattern to prevent memory leaks.

Translation provider

The translation provider is a class that provides the translated resources. It has to implement the ITranslationProvider and can access
any kind of resources you like. For e.g. ResX, XML or text files.

 
public class TranslateExtension : MarkupExtension
{
private string _key;
 
public TranslateExtension(string key)
{
_key = key;
}
 
[ConstructorArgument("key")]
public string Key
{
get { return _key; }
set { _key = value;}
}
 
public override object ProvideValue(IServiceProvider serviceProvider)
{
var binding = new Binding("Value")
{
Source = new TranslationData(_key)
};
return binding.ProvideValue(serviceProvider);
}
}
 
 
 
public class TranslationData : IWeakEventListener,
INotifyPropertyChanged, IDisposable
{

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension

private string _key;


 
public TranslationData( string key)
{
_key = key;
LanguageChangedEventManager.AddListener(
TranslationManager.Instance, this);
}
 
~TranslationData()
{
Dispose(false);
}
 
 
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
 
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
LanguageChangedEventManager.RemoveListener(
TranslationManager.Instance, this);
}
}
 
 
public object Value
{
get
{
return TranslationManager.Instance.Translate(_key);
}
}
 
public bool ReceiveWeakEvent(Type managerType,
object sender, EventArgs e)
{
if (managerType == typeof(LanguageChangedEventManager))
{
OnLanguageChanged(sender, e);
return true;
}
return false;
}
 
private void OnLanguageChanged(object sender, EventArgs e)
{
if( PropertyChanged != null )
{
PropertyChanged( this, new PropertyChangedEventArgs("Value"));
}
}
 
public event PropertyChangedEventHandler PropertyChanged;

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension
}
 
 
 
public class TranslationManager
{
private static TranslationManager _translationManager;
 
public event EventHandler LanguageChanged;
 
public CultureInfo CurrentLanguage
{
get { return Thread.CurrentThread.CurrentUICulture; }
set
{
if( value != Thread.CurrentThread.CurrentUICulture)
{
Thread.CurrentThread.CurrentUICulture = value;
OnLanguageChanged();
}
}
}
 
public IEnumerable<CultureInfo> Languages
{
get
{
if( TranslationProvider != null)
{
return TranslationProvider.Languages;
}
return Enumerable.Empty<CultureInfo>();
}
}
 
public static TranslationManager Instance
{
get
{
if (_translationManager == null)
_translationManager = new TranslationManager();
return _translationManager;
}
}
 
public ITranslationProvider TranslationProvider { get; set; }
 
private void OnLanguageChanged()
{
if (LanguageChanged != null)
{
LanguageChanged(this, EventArgs.Empty);
}
}
 
public object Translate(string key)
{
if( TranslationProvider!= null)
{
object translatedValue =TranslationProvider.Translate(key);

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension
if( translatedValue != null)
{
return translatedValue;
}
}
return string.Format("!{0}!", key);
}
}
 
 

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2010-05-25 22:11:25


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 21.May 2010

I created a translator project and have generated a dll.


Juliana
I created another one and am trying to use the translation.
Could tell me if I have to do some configuration, so the project recognizes the project resource translator?

Commented on 20.August 2010

@Gnought: Your solution is working, because the "removeListener" isn't executed, isn't it?

Sebastian

in your solution it will be called, if dispose is called with "disposing=true"

if (disposing)

// Code to dispose the managed resources of the class

LanguageChangedEventManager.RemoveListener(TranslationManager.Instance, this);

but the finalizer calls the dispose with "false".

another question:

shouldn't the "removeListener" function be called, after closing and destroying a form that uses the specific
MarkupExtension. If you create the same Window 3 times. The Listener will be added 3 times in a row. And will
only be removed after closing the application. It this intended?

Commented on 9.October 2010

Is it possible to have design time support? I would like to see the default text (en-US locale) during design time in
Bo
Visual Studio instead of the "!TEXT_KEY!" syntax.
Skjoett

Commented on 9.October 2010

Is it possible to have design time support? I would like to see the default text (en-US locale) during design time in
Bo
Visual Studio instead of the "!TEXT_KEY!" syntax.
Skjoett

Commented on 18.October 2010

@Sebastian, did you try?

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension
Gnought
Closing and destroying a form will call Dispose() method which calls Disposing(true) so the listener will still listen 1
event.

Commented on 8.November 2010

Why is this better than simply using something like

Steven
xmlns:resx="clr-namespace:MyApp.Properties"

Text="{x:Static resx:Resources.Title}

Commented on 23.December 2010

Great article, thanks for that!

Doc

But I still wonder, is there an easy way to create this {Translator Resource Binding} dynamically in the code?

Commented on 9.January 2011

Awesome article! I was struggling to get a dynamic way to switch languages and did not want to deal with
Steve G.
LocBaml. Your classes work great.

Commented on 26.January 2011

Wonderful article.

Griz

FYI, From code I was able to use

TextBox.Text = TranslationManager.Instance.Translate(tranlationKey) as string;

Commented on 26.January 2011

Continuing... to get the value in the current culture.

Griz

And to bind from code, this worked

var binding = new Binding("Value")

Source = new TranslationData(tranlationKey)

};

BindingOperations.SetBinding(TextBox, TextBox.TextProperty, binding);

which both methods were taken from the Translate classes in the sample.

Commented on 11.February 2011

Can you tell more about the memory management in this example? Why do you use WeakEventListener instead
Spook
of simple delegation? And why one shall implement both Finalize and Dispose methods? I am not familiar with
such resource allocation and collection issues :(

Commented on 11.February 2011

Do I have to do any aditional linking to get the .resource files or the .dll they are in linked to the assembly? My
Flo
app continiosly tells me it can't find <Namespace>.Resource.resources but the files are created in the bin
directory and then correctly packed into a dll which is found in the debug directory.

lg flo

Commented on 24.February 2011

Is there a reason why in your sample project the languages are displayed in the combobox as 'German' and

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension
Wom
'Dutch' while in my own project it just stays 'nl' and 'de'?

Commented on 24.March 2011

Hi

Klaus

Is there a way to use this extension in a multibinding?

I want to have a label that consists of a text from the markup extension followed by a text that comes from a
second control (im my example: datagrid.items.count.

The resulting label should be &quot;Number of records: 123&quot; where &quot;Number of records:&quot;
comes from the extension and &quot;123&quot; is the number of records in a datagrid on the same window

Regards

Commented on 24.March 2011

Hi Klaus,

Christian
since the TranslationExtension returns a binding, you can use it like a binding in a multibinding. If you are using
Moser
.NET 4.0 you can profit of the new bindable &lt;Run&gt; within a &lt;TextBlock&gt; to combine fragments to one
string.

Greetings

Christian

Commented on 6.April 2011

I like that very much - Small, lean straight forward. Thanks a lot for sharing - learned some new concepts on your
Stefan
code!

Commented on 26.April 2011

Nice work Christian. Can you tell me, though, why the languages in my sample-project display in the ComboBox
James
as &quot;en&quot; and &quot;de&quot; while they display in your project as &quot;English&quot; and
Hurst
&quot;German&quot;? I've been digging and searching and can't figure out why! I would expect the binding (to
that ComboBox) to use the ToString() method on the CultureInfo objects by default, which yields the
&quot;de&quot; and &quot;en&quot; values. The solution that comes to my mind is to add a ValueConverter.
But I would like to know how you got yours to automatically show the EnglishName property in that ComboBox?!

Thank you for your advice, James Hurst

Commented on 3.May 2011

Hey James,

Manuel
I'm not sure if this will help you but I did it with a ValueConverter which gets applied on each item like so in xaml
Strausz
notation:

&lt;ComboBox.ItemTemplate&gt;

&lt;DataTemplate&gt;

&lt;TextBlock Text=&quot;{Binding Converter={StaticResource TranslationConverter}}&quot;/&gt;

&lt;/DataTemplate&gt;

&lt;/ComboBox.ItemTemplate&gt;

Where TranslationConverter is a simple converter which will translate the values given by the combobox by using
the TranslationManager directly. Could be useful for other things as well, I suppose.

Commented on 20.May 2011

A great article.

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension
Hari

I have one question on the use of this markup extension with binding.

For ex.

We often have situtations to bind Text property to view model property

&lt;TextBlock Text=&quot;{Binding CustomerType}&quot; /&gt;

Assuming we need translation for CustomerType

&lt;TextBlock Text=&quot;{l:Translate {Binding CustomerType}}&quot; /&gt; does not work.

I could use a value converter to do this. However, I would like keep the option open as the value converter may
be used for converting from a specific object to string. Also, if we use value converters, dynamic language
switching will not work

Commented on 14.June 2011

I observed that if you choose the .Net Framework 4 instead of 3.5, as in the example code, the combobox for the
jones
language selection shows only the short names of the culture (de, en) instead of the complete name (Deutsch,
English).

Can you please show, how to display the full name when using .net Framework 4?

Commented on 20.July 2011

&Oslash;&ordf;&Oslash;&sect;&Ugrave;�&Oslash;&sect;&Oslash;&ordf;&Ugrave;�&Oslash;&sect;&Oslash;&ordf;&Ugrave;�
‫ا تئنت‬

Commented on 12.September 2011

Hi Christian,

apo

great job! is your code restricted to any license?

Commented on 12.September 2011

Hi Christian,

apo

great job! is your code restricted to any license?

Commented on 17.September 2011

How about if i want to use the translation manager in different assemblies (which consists of different resource
Great
files?

article.

Example:

Assembly.exe (resource.de.resx:MyString=&quot;Foo A&quot;)

AssemblyA.dll (resource.de.resx:MyString=&quot;Foo B&quot;)

AssemblyB.dll (resource.de.resx:MyString=&quot;Foo C&quot;)

Commented on 20.September 2011

Great post!

Beck

Do you know of a way to show a default value on the designer window, currently it is littered with the key values?

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Localization using a MarkupExtension
Thanks in advance

Name

E-Mail (optional)

Comment

Post Comment

LocalizeMarkupExtension.html[2/16/2014 3:07:34 PM]


WPF Tutorial | Drag & Drop

Home
    Interaction
    Drag & Drop Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Drag and Drop in WPF
Custom Controls

Layout
Introduction
Input
Drag&Drop can drasticly improve the productiviy and user experience of a software. But only a few programmers provide drag and
Data Binding drop functionality in their applications, because they think its much more dificult than it really is. This article shows how simple drag
and drop can be implemented in WPF.
Styling

Localization
Drag&Drop in 6 Steps
Interaction

Resources
1. Detect a drag as a combinatination of MouseMove and MouseLeftButtonDown
2. Find the data you want to drag and create a DataObject that contains the format, the data and the allowed effects.
2D Graphics 3. Initiate the dragging by calling DoDragDrop()
3D Graphics 4. Set the AllowDrop property to True on the elements you want to allow dropping.
5. Register a handler to the DragEnter event to detect a dragging over the drop location. Check the format and the data by
Animation
calling GetDataPresent() on the event args. If the data can be dropped, set the Effect property on the event args to display
Multimedia the appropriate mouse cursor.
6. When the user releases the mouse button the DragDrop event is called. Get the data by calling the GetData() method on the
Documents
Data object provided in the event args.
Windows 7
...and that's all the magic.
Interoperability

Performance
Drag
Expression Blend
To start the drag operation, we have to detect a mouse move while the left mouse button is pressed. To do this we have to hook up
Tools handlers on the PreviewMouseMove and PreviewMouseLeftButtonDown events.
UI Automation To prevent occasionally drags, its a good design to not start the drag operation until the user has moved the mouse cursor by a
couple of pixels. WPF provides a constant that contains the amount of pixel that Windows uses.

When the drag is initiated, we need to specify the data we want to drag. In our case its the data of the ListViewItem we dragged.
We find the ListViewItem in the OriginalSource of the mouse event args. By calling

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | Drag & Drop
ItemContainerGenerator.ItemFromContainer we get the data behind the ListViewItem.

Create a DataObject to transport the data to the drop location. The constructor takes two arguments. A string that describes the
format and the data we want to drag.

 
<ListView x:Name="DragList"
PreviewMouseLeftButtonDown="List_PreviewMouseLeftButtonDown"
PreviewMouseMove="List_MouseMove"/>
 
 
 
private void List_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Store the mouse position
startPoint = e.GetPosition(null);
}
 
 
 
private void List_MouseMove(object sender, MouseEventArgs e)
{
// Get the current mouse position
Point mousePos = e.GetPosition(null);
Vector diff = startPoint - mousePos;
 
if (e.LeftButton == MouseButtonState.Pressed &&
Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance )
{
// Get the dragged ListViewItem
ListView listView = sender as ListView;
ListViewItem listViewItem =
FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);
 
// Find the data behind the ListViewItem
Contact contact = (Contact)listView.ItemContainerGenerator.
ItemFromContainer(listViewItem);
 
// Initialize the drag & drop operation
DataObject dragData = new DataObject("myFormat", contact );
DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move);
}
}
 
 
 
// Helper to search up the VisualTree
private static T FindAnchestor<T>(DependencyObject current)
where T : DependencyObject
{
do
{
if( current is T )
{
return (T)current;
}

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | Drag & Drop
current = VisualTreeHelper.GetParent(current);
}
while (current != null);
return null;
}
 
 

Drop
To make an element be a drop location, set the AllowDrop property to true. When the user drags an item over the element, the
DragEnter event is called. In this event you can analyze the data and decide if a drop is allowed or not.

When the user releases the mouse button the Drop event is called. The data is available in the DataObject provided in the
DragEventArgs.

 
<ListView x:Name="DropList"
Drop="DropList_Drop"
DragEnter="DropList_DragEnter"
AllowDrop="True" />
 
 
 
private void DropList_DragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("myFormat") ||
sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
}
 
 
 
private void DropList_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("myFormat"))
{
Contact contact = e.Data.GetData("myFormat") as Contact;
ListView listView = sender as ListView;
listView.Items.Add(contact);
}
}
 
 

  ► Tutorial   ► ActionScript   ► Flash 8   ► Flash CS3


Last modified: 2011-04-19 16:59:14


Copyright (c) by Christian Moser, 2011.

 Comments on this article

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | Drag & Drop

Show all comments

Commented on 17.June 2011

I tried the same thing in the RightButton click but at that time DragOver event is not fired.. How can i
David C
resolve this problem ?

Commented on 17.June 2011

Very Good.

ZeePrime

Warning with the if, you miss a couple of brackets as &amp;&amp; has precedence over ||

if (e.LeftButton == MouseButtonState.Pressed &amp;&amp;

Math.Abs(diff.X) &gt; SystemParameters.MinimumHorizontalDragDistance ||

Math.Abs(diff.Y) &gt; SystemParameters.MinimumVerticalDragDistance )

Commented on 23.June 2011

how can i go for multiple drag and drop?? say i want to select three items @ a time from Drag_list and
kamlendra
drop them into Drop_list.

Commented on 27.June 2011

Hi,
oc
I am trying out your code but in Datagrid not in Listview. I couldn't figure it out the 'Contact' in this line
Contact contact = (Contact)listView.ItemContainerGenerator.

what does it stands for ?

Regards

Commented on 20.July 2011

I agree with Olivier as for the missing parentheses in the mouseMove conditions. You should correct it in
david
the main article :p

Commented on 21.July 2011

Hi Christian,

NIkhil

Please elaborate what is Contact used in 4 places in this example?

Contact contact = (Contact)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);

Contact contact = e.Data.GetData(&quot;myFormat&quot;) as Contact;

Thanks in advance

Commented on 28.July 2011

Sweet and simple. Thanks for the wealth of info on your site.

KornMuffin

@oc - just use a string instead of the Contact class if you don't want to create your own Contact class.

Commented on 2.August 2011

i can smell poo and a small amount of wee too.


tooma

Commented on 2.August 2011

i can smell poo and a small amount of wee too.

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | Drag & Drop
tooma

Commented on 4.August 2011

Why i am getting this exception everytime?


seiko
Element already has a logical parent. It must be detached from the old parent before it is attached to a
new one.

on line
listView.Items.Add(contact); ??

Somebody may know that?

Commented on 17.August 2011

Hi,

bizzare
Im a newbie to WPF and i dont know if this question even makes sense here but i dint know where else to
post it! I need to select two or more items from a list box and then enable a button. Can you please help
me as to how i could do it?Thanks!

Commented on 17.August 2011

Hi,

bizzare
Im a newbie to WPF and i dont know if this question even makes sense here but i dint know where else to
post it! I need to select two or more items from a list box and then enable a button. Can you please help
me as to how i could do it?Thanks!

Commented on 17.August 2011

I m using very similar drag and drop functionality in my WPF app , while i wish to drag item from
Abhishek...
combobox to textbox , when im doing so , the combobox always get closed and i can't select any items
from it to drag towards textbox.

Commented on 17.August 2011

Hi,

bizzare
Im a newbie to WPF and i dont know if this question even makes sense here but i dint know where else to
post it! I need to select two or more items from a list box and then enable a button. Can you please help
me as to how i could do it?Thanks!

Commented on 17.August 2011

Hi,

bizzare
Im a newbie to WPF and i dont know if this question even makes sense here but i dint know where else to
post it! I need to select two or more items from a list box and then enable a button. Can you please help
me as to how i could do it?Thanks!

Commented on 21.August 2011

Contact is just a class (domain/poco)

Tom Pester

public class Contact

public Contact(string firstname, string lastname)

Firstname = firstname;

Lastname = lastname;

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | Drag & Drop

public string Firstname { get; set; }

public string Lastname { get; set; }

public override string ToString()

return string.Format(&quot;Firstname: {0}, Lastname: {1}&quot;, Firstname, Lastname);

To get the code working I had to change the code from (this is a bug IMO)

if (e.LeftButton == MouseButtonState.Pressed &amp;&amp;


Math.Abs(diff.X) &gt; SystemParameters.MinimumHorizontalDragDistance ||

Math.Abs(diff.Y) &gt; SystemParameters.MinimumVerticalDragDistance

to
if (e.LeftButton == MouseButtonState.Pressed &amp;&amp;
(

Math.Abs(diff.X) &gt; SystemParameters.MinimumHorizontalDragDistance ||

Math.Abs(diff.Y) &gt; SystemParameters.MinimumVerticalDragDistance

I also got null reference exceptions and had to check the listViewItem for null:

ListViewItem listViewItem =

FindAnchestor&lt;ListViewItem&gt;((DependencyObject) e.OriginalSource);

if (listViewItem == null) return;

I think its due to a timing issue if you do a drag and drop very fast or execute the code on a fast
computer?

Thanks for this minimal sample. It's excellent to get started from.

Commented on 22.August 2011

Hi!

Lasoty
Please show mi how look the Contact class.

TXH

Commented on 22.August 2011

Hi!

Lasoty
Please show mi how look the Contact class.

TXH

Commented on 5.September 2011

Hi!!

Guest
I am able to drag the control. but i have to drop the control to dynamically created Panel or Canvas. How
i should proceed? Pls help me

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | Drag & Drop

Commented on 5.September 2011

Hi!!

Guest
I am able to drag the control. but i have to drop the control to dynamically created Panel or Canvas. How
i should proceed? Pls help me

Commented on 5.September 2011

Hi!!

Guest
I am able to drag the control. but i have to drop the control to dynamically created Panel or Canvas. How
i should proceed? Pls help me

Commented on 5.September 2011

Hi!!

Guest
I am able to drag the control. but i have to drop the control to dynamically created Panel or Canvas. How
i should proceed? Pls help me

Commented on 5.September 2011

Hi!!

Guest
I am able to drag the control. but i have to drop the control to dynamically created Panel or Canvas. How
i should proceed? Pls help me

Commented on 23.September 2011

Hi,

Raman

I have tried this program, just used the class &quot;People&quot; instead of &quot;Contact&quot; and it
wors fine. Here is the code that I have tried for the &quot;People&quot;:

public class Person

private string _name;

private string _relationshipType;

public string Name

get { return _name; }

set

_name = value;

public string RelationshipType

get { return _relationshipType; }

set { _relationshipType = value; }

public Person(string name, string relationshiptype)

this._name = name;

this._relationshipType = relationshiptype;

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | Drag & Drop
}

public class People : ObservableCollection&lt;Person&gt;

public People()

Add(new Person(&quot;Sean&quot;, &quot;Friend&quot;));

Add(new Person(&quot;Chris&quot;, &quot;Friend&quot;));

Add(new Person(&quot;Peter&quot;, &quot;Brother&quot;));

Add(new Person(&quot;Jeremy&quot;, &quot;Brother&quot;));

Add(new Person(&quot;Kevin&quot;, &quot;Brother&quot;));

Regards

Commented on 27.September 2011

Hello,

Patrick
I tried to implement this and the button state is never pressed. Also my Clickevents don't trigger anymore.
So drag and drop works or the Clickevent never both.

regards

Name

E-Mail (optional)

Comment

Post Comment

DragAndDrop.html[2/16/2014 3:07:48 PM]


WPF Tutorial | MergedDictionaries

Home
    Resources
    MergedDictionaries Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Merged ResourceDictionaries
Custom Controls

Layout
Problems loading merged resource dictionaries in .NET 4.0
Input
I experienced a problem, when I am trying to merge resource dictionaries at app-level. As soon as I changed the target framework
Data Binding from 3.5 to 4.0 they don't get loaded anymore. It seems as if they have changed something in the behavior of
MergedResourceDictionaries in .NET 4.0.
Styling

Localization
I found a way how to fix this problem. Just add a dummy default style in the resource dictionary where you merge all resources
together. See the following example:
Interaction
This is the official bug description from Microsoft:
Resources
On the creation of every object in XAML, if a default style is present (i.e. style w/ a key of Type) that style should be applied.
As you can
2D Graphics imagine there are several performance optimizations to make that (implied) lookup a light weight as possible.
One of them is that we
don’t look inside Resource Dictionaries unless they are flagged as “containing default Styles”.
There is a bug: if all your default styles are
3D Graphics
nested in merged dictionaries three levels deep (or deeper) the top dictionary does not get flagged so the search skips it.
The work
Animation around is to put a default Style to something, anything, <Style TargetType="x:Dummy" /> in the root Dictionary.

Multimedia Bug entry on Microsoft Connect

Documents  
<Application.Resources>
Windows 7 <ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
Interoperability
<ResourceDictionary Source="Styles/DefaultStyle.xaml"/>
Performance </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
Expression Blend </Application.Resources>
Tools
 
 
 
UI Automation
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 

MergedDictionaryPerformance.html[2/16/2014 3:08:25 PM]


WPF Tutorial | MergedDictionaries
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="DefaultStyle/Button.xaml"/>
</ResourceDictionary.MergedDictionaries>
 
<Style TargetType="{x:Type Rectangle}" />
 
</ResourceDictionary>
 
 

Improve the performance of merged ResourceDictionaries


Each time a control references a ResourceDictionary XAML creates a new instance of it. So if you have a custom control library
with 30 controls in it and each control references a common dictionary you create 30 identical resource dictionaries!
 
<ResourceDictionary.MergedDictionaries>
<SharedResourceDictionary Source="/MyControlLibrary;component/Themes/Brushes.xaml"
/>
</ResourceDictionary.MergedDictionaries>
 
 
To get rid of this problem, I created the SharedResourceDictionary. You can use it the same way as a conventional
ResourceDictionary. The only suptile difference is, that if it is instanced multiple times, the resources are loaded only once.
 
 
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation",

"WPFTutorial.Utils")]
 
/// <summary>
/// The shared resource dictionary is a specialized resource dictionary
/// that loads it content only once. If a second instance with the same source
/// is created, it only merges the resources from the cache.
/// </summary>
public class SharedResourceDictionary : ResourceDictionary
{
/// <summary>
/// Internal cache of loaded dictionaries
/// </summary>
public static Dictionary<Uri, ResourceDictionary> _sharedDictionaries =
new Dictionary<Uri, ResourceDictionary>();
 
/// <summary>
/// Local member of the source uri
/// </summary>
private Uri _sourceUri;
 
/// <summary>
/// Gets or sets the uniform resource identifier (URI) to load resources from.
/// </summary>
public new Uri Source
{
get { return _sourceUri; }
set
{

MergedDictionaryPerformance.html[2/16/2014 3:08:25 PM]


WPF Tutorial | MergedDictionaries
_sourceUri = value;
 
if (!_sharedDictionaries.ContainsKey(value))
{
// If the dictionary is not yet loaded, load it by setting
// the source of the base class
base.Source = value;
 
// add it to the cache
_sharedDictionaries.Add(value, this);
}
else
{
// If the dictionary is already loaded, get it from the cache
MergedDictionaries.Add(_sharedDictionaries[value]);
}
}
}
}
 
 

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2011-03-14 08:47:50


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 14.May 2009

Seems great, I'll check it and post results here.

AVEbrahimi
I've very long startup time in my big WPF project...

Commented on 28.May 2009

Looks nice, but is this SharedResourceDictionary Blend "friendly"?


Andrew

Commented on 28.May 2009

Hi Andrew,

Christian
Moser
No, unfortunately the current versions of Blend cannot deal with it :-( I am searching for another
solution that is fast and also supported by Blend.

Commented on 1.June 2009

Looks like I've found a solution which address the same issue as yours, but it is a Blend friendly - check
Andrew
it out http://www.drwpf.com/blog/Home/tabid/36/EntryID/10/Default.aspx - in section "Manage a
Collection of Resource Dictionaries in Code and Merge them at the Element Level" there is class
"SharedResources".

MergedDictionaryPerformance.html[2/16/2014 3:08:25 PM]


WPF Tutorial | MergedDictionaries

Commented on 31.July 2009

Hi Andrew,

DJanjicek

since totday I'm using MergedDictionaries in my Silverlight project and I'm facing huge performance
problems. The app is consuming almost 1GB of memory after a few clicks. Your solution could help me
out of this trouble but I have no idea how to implement your code and how to use it.

Could you help me with this?

Commented on 10.August 2009

I agree with DJanjicek.

Sergey
Andrew, could you share an example of using your class?

Commented on 24.August 2009

Just be aware... we were using the SharedResourceDictionary in our project, until we found out that it
Cameron
was holding onto XAML pages that had been closed, and thus were not being garbage collected.

Commented on 31.October 2009

_sourceUri = new Uri(value.OriginalString); allows garbage collection.


HDW

Also wrapping access to _sharedDictionaries in lock (((ICollection)_sharedDictionaries).SyncRoot) and


wrapping access to MergedDictionaries in lock (((ICollection)MergedDictionaries).SyncRoot) makes the
class thread safe.

Commented on 9.November 2009

SharedResourceDictionary seems not be compatible with the {ThemeDictionary ...} markup extensions.
fmunkert
An InvalidOperationException is thrown which states that ThemeDictionaryExtension can be used with
ResourceDictionary only.

There might be other code in WPF which does not work if you derive from ResourceDictionary.

Commented on 12.May 2010

Thanks Christian,

Lee Campbell
FYI: I have added a colleagues expansion on the problem referencing this post on this site

http://leecampbell.blogspot.com/2010/05/mergeddictionaries-performance-problems.html

Commented on 2.July 2010

I'm having some issues with this solution in the designer. I am trying to use the designer in VS2010.
Mike
Using this, I get an error when using the designer, and I can't get any code completion. Any ideas, if
this works in the designer?

Commented on 31.August 2010

Same here. I'm receiving a NotSupportedException when using SharedResourceDictionary on design


Fran Herrera
time. When running the app, everything seems to work. VS2010Express.

Commented on 16.November 2010

The code mentioned above to fix garbage collection throws exceptions:

jep
_sourceUri = new Uri(value.OriginalString); allows garbage collection.

MergedDictionaryPerformance.html[2/16/2014 3:08:25 PM]


WPF Tutorial | MergedDictionaries

Any solution to this?

Commented on 22.November 2010

i m working with Silverlight 4.

shemesh
1) isn't this behavior (of making a new instance for each control reference) is a memory leak? shouldn't
this be addressed by Microsoft?

2)could you post a code that allows GC and thread safe?

Commented on 17.December 2010

If you want use the MergedDictionary and working Designer, just implement this :

EinMitleser

public bool IsInDesignMode

get

return

(bool)

DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty,

typeof(DependencyObject)).Metadata.DefaultValue;

Commented on 17.December 2010

Hello,

EinMitleser

if you want to use this class in your project without loosing the designer, just impemelent this static
prop into the class:

private static bool IsInDesignMode

get

return (bool)
DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty,

typeof(DependencyObject)).Metadata.DefaultValue;

--- thats the new getter:

if (IsInDesignMode)

return base.Source;

return _sourceUri

And this put in front of the old setter-code :

if (IsInDesignMode)

base.Source = value;

return;

MergedDictionaryPerformance.html[2/16/2014 3:08:25 PM]


WPF Tutorial | MergedDictionaries

The problem is the memory at runtime(yes ms just cookin with water, like all others too/do)...and thanks
to mr. moser for his little work...

Commented on 17.December 2010

I forgott to write the try catch sourrund the base.Source=value


Ups

Commented on 14.January 2011

ya its very useful for us.Its a great one for beginners.


Arun

Commented on 19.January 2011

Does anyone have this working in Silverlight 4? I am getting an exception when it tries to do
Mary Ellen
"MergedDictionaries.Add" --> InvalidOperationException: Element is already the child of another
element.

Any help is appreciated.

Commented on 1.February 2011

I'm also trying to get this working in SL4. Anyone know of a good example?
Coop

Commented on 28.March 2011

nice article.... Thanks!!


bobs

Commented on 1.April 2011

In order to overcome the designer issue I used a Powershell script in a Pre and Post Build event to
David
change ResourceDictionary to SharedResourceDictionary at build time.
Compton

Commented on 25.May 2011

Hi Christian,

Kaushal
We are experiencing problem is display of context of ViewBox after installing .Net 4.0 framweowrk.
Viewbox contains some chart or tabular data. Problem is that some text get invisible on randoam basis.
Cant google any suitable solution.

Looking forward for your help.

Commented on 25.May 2011

Hi Christian,

Kaushal
We are experiencing problem is display of context of ViewBox after installing .Net 4.0 framweowrk.
Viewbox contains some chart or tabular data. Problem is that some text get invisible on randoam basis.
Cant google any suitable solution.

Looking forward for your help.

Commented on 3.June 2011

Hi Christian, Its really a good article. But when i am planning to use it, it shows me an compilation error
Vikas
state Error 13 The tag 'SharedResourceDictionary' does not exist in XML namespace '[My Name
Dangwal
Space]'. Line 6 Position 10. [somefile.xaml] 6 10[ ProjectName]

Could you please tell me if i am missing something. I just created same class suggested by you.

MergedDictionaryPerformance.html[2/16/2014 3:08:25 PM]


WPF Tutorial | MergedDictionaries

Name

E-Mail (optional)

Comment

Post Comment

MergedDictionaryPerformance.html[2/16/2014 3:08:25 PM]


WPF Tutorial | Read WPF resources from WinForms

Home
    Resources
    Read WPF resources from WinForms Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to read WPF ResourceDictionaries from WinForms
Custom Controls
When you add resources dictionaries to an WPF project the build action is automatically set to Page. This means that the compiler
Layout generates a BAML stream and adds it to the resources of the assembly.
Input Since WPF has the built-in functionality to read a BAML stream but its API is not public, we have to write a little helper class that access
the internal method by using reflection.
Data Binding
 
Styling
public static class BamlReader
Localization {
public static object Load(Stream stream)
Interaction {
Resources
ParserContext pc = new ParserContext();
MethodInfo loadBamlMethod = typeof(XamlReader).GetMethod("LoadBaml",
2D Graphics BindingFlags.NonPublic | BindingFlags.Static)
return loadBamlMethod.Invoke(null, new object[] { stream, pc, null, false });
3D Graphics
}
Animation }
 
Multimedia
 
 
Documents StreamResourceInfo sri = System.Windows.Application.GetResourceStream(
new Uri("/MyAssemblyName;component/MyResourceDict.xaml", UriKind.Relative));
Windows 7
ResourceDictionary resources = (ResourceDictionary)BamlReader.Load(sri.Stream);
Interoperability  
 
Performance

Expression Blend
  ► Tutorial   ► Learn Quick Books   ► Read Books   ► Basics
Tools

UI Automation
Last modified: 2009-07-10 13:39:59
Copyright (c) by Christian Moser, 2011.

ReadWPFResourcesFromWinForms.html[2/16/2014 3:08:41 PM]


WPF Tutorial | Read WPF resources from WinForms

 Comments on this article

Show all comments

Commented on 28.February 2009

It would have been nice if you took a example and explained step by step. But still its a good article
Goo

Commented on 10.July 2009

Hi, could you explain me how to get/read the xaml content of the form I designed in C#? Please send
Sean
me email if you could

Commented on 4.June 2010

That's a clear use of the BMALView. And for Goo, it's almost clear no need for a SbS Tutorial; all u have
Blood
to do is to read about the BAMLView (google it or go to mocrosoft website)
HaZaRd

Name

E-Mail (optional)

Comment

Post Comment

ReadWPFResourcesFromWinForms.html[2/16/2014 3:08:41 PM]


WPF Tutorial | Set DynamicResource from Code

Home
    Resources
    Set DynamicResource from Code Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to assign a dynamic resource link programmatically
Custom Controls
Normally you assign resources in XAML by using the StaticResource or DynamicResource extension. But how to do it
Layout programmatically?

The static behavior is simple. Just find the resource by using the TryFindResource() method and set it to the property of your
Input
choice. But if you want to have it dynamically updated, the following code snipped is your solutions:
Data Binding
 
Styling frameworkElement.SetResourceReference(dependencyProperty, resourceKey);
 
Localization  
Interaction

Resources   ► Tutorial   ► ActionScript   ► Flash Player 8   ► Adobe Flash

2D Graphics
Last modified: 2010-06-15 21:41:07
3D Graphics
Copyright (c) by Christian Moser, 2011.

Animation

Multimedia
 Comments on this article
Documents
Show all comments
Windows 7

Interoperability Commented on 8.July 2010

owsome
Performance Tod

Expression Blend
Commented on 13.September 2010
Tools
While, as we can see, this way requires a framework element to work on.

Hugo Gu
UI Automation
Do you know how to make it on a GridViewColumn? You know, the GridViewColumn is derived from
DependencyObject and don't have that SetResourceReference method.

Thank you very much.

DynamicResourceCode.html[2/16/2014 3:09:23 PM]


WPF Tutorial | Set DynamicResource from Code

Commented on 4.August 2011

Thanks for sharing.


CyberAngel

Name

E-Mail (optional)
Comment

Post Comment

DynamicResourceCode.html[2/16/2014 3:09:23 PM]


WPF Tutorial | Loading BAML

Home
    Resources
    Loading BAML Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to load BAML resources
Custom Controls

Layout
What is BAML?
Input
WPF is based on XAML an XML dialect to describe object graphs. This is very powerful but parsing an XAML file at runtime is quite
Data Binding expensive. So the MarkupCompiler converts the XAML file to a more compact binary version called BAML. The BAML stream then
is stored to the resources of the assembly and loaded within the InitializeComponent method.
Styling
The BAML API is something unique of WPF and was not public until .NET 4.0. Now it's available through the Baml2006Reader
Localization
implementation. The following code shows how to load a BAML stream in .NET 3.5 and 4.0
Interaction

Resources Load an object from a BAML stream


2D Graphics
Load a BAML stream in .NET 3.5 (by using reflection):
3D Graphics
 
Animation var pc = new ParserContext();
var readerType = presentationFrameworkAssembly
Multimedia .GetType("System.Windows.Markup.XamlReader");
var method = readerType.GetMethod("LoadBaml",
Documents
BindingFlags.NonPublic | BindingFlags.Static);
Windows 7 return method.Invoke(null, new object[] {stream, pc, null, false});
 
Interoperability
 
Performance
Load a BAML stream in .NET 4.0:

 
Expression Blend
var reader = new Baml2006Reader(stream);
Tools var writer = new XamlObjectWriter(reader.SchemaContext);
while(reader.Read())
UI Automation
{
writer.WriteNode(reader);
}
return writer.Result;

baml.html[2/16/2014 3:09:35 PM]


WPF Tutorial | Loading BAML
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2011-03-14 20:49:21


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 20.April 2011

It is very helpful !!! Thanks


Andrey

Name

E-Mail (optional)

Comment

Post Comment

baml.html[2/16/2014 3:09:35 PM]


WPF Tutorial | Draw excactly on physical device pixels

Home
    2D Graphics
    Draw excactly on physical device pixels Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Draw lines excactly on physical device pixels
Custom Controls

Layout
Why do my lines appear so blurry?
Input
When you draw a line in WPF you will experience that they often appear blurry. The reason for this is the antialiasing system that
Data Binding spreads the line over multiple pixels if it doesn't align with physical device pixels.

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics
The following example shows a usercontrol that overrides the OnRender method for custom drawing a rectange to the
Animation drawingContext. Even if all points are integer values and my screen has a resolution of 96dpi the lines appear blurry. Why?

Multimedia  
protected override void OnRender(DrawingContext drawingContext)
Documents {
Windows 7
Pen pen = new Pen(Brushes.Black, 1);
Rect rect = new Rect(20,20, 50, 60);
Interoperability  
drawingContext.DrawRectangle(null, pen, rect);
Performance
}
Expression Blend  
 
Tools

UI Automation Resolution independence


WPF is resoultion independent. This means you specify the size of an user interface element in inches, not in pixels. A logical unit in
WPF is 1/96 of an inch. This scale is chosen, because most screens have a resolution of 96dpi. So in most cases 1 logical unit maches
to 1 physical pixel. But if the screen resolution changes, this rule is no longer valid.

DrawOnPhysicalDevicePixels.html[2/16/2014 3:09:57 PM]


WPF Tutorial | Draw excactly on physical device pixels

Align the edges not the center points


The reason why the lines appear blurry, is that our points are center points of the lines not edges. With a pen width of 1 the edges are
drawn excactly between two pixels.

A first approach is to round each point to an integer value (snap to a logical pixel) an give it an offset of half the pen width. This
ensures, that the edges of the line align with logical pixels. But this assumes, that logical and physical device pixels are the same. This
is only true if the screen resolution is 96dpi, no scale transform is applied and our origin lays on a logical pixel.

Using SnapToDevicePixels for controls


All WPF controls provide a property SnapToDevicePixels. If set to true, the control ensures the all edges are drawn excactly on
physical device pixels. But unfortunately this feature is only available on control level.

Using GuidelineSets for custom drawing


Our first approach to snap all points to logical pixels is easy but it has a lot of assumptions that must be true to get the expected
result. Fortunately the developers of the milcore (MIL stands for media integration layer, that's WPFs rendering engine) give us a way
to guide the rendering engine to align a logical coordinate excatly on a physical device pixels. To achieve this, we need to create a
GuidelineSet. The GuidelineSet contains a list of logical X and Y coordinates that we want the engine to align them to
physical device pixels.

If we look at the implementation of SnapToDevicePixels we see that it does excatly the same.

 
protected override void OnRender(DrawingContext drawingContext)
{
Pen pen = new Pen(Brushes.Black, 1);
Rect rect = new Rect(20,20, 50, 60);
 
double halfPenWidth = pen.Thickness / 2;
 
// Create a guidelines set
GuidelineSet guidelines = new GuidelineSet();
guidelines.GuidelinesX.Add(rect.Left + halfPenWidth);
guidelines.GuidelinesX.Add(rect.Right + halfPenWidth);
guidelines.GuidelinesY.Add(rect.Top + halfPenWidth);
guidelines.GuidelinesY.Add(rect.Bottom + halfPenWidth);
 
drawingContext.PushGuidelineSet(guidelines);
drawingContext.DrawRectangle(null, pen, rect);
drawingContext.Pop();
}
 
 
The example above is the same as at the beginning of the article. But now we create a GuidelinesSet. To the set we add a
horizontal or vertical guidelines for each logical coordinate that we want to have aligned with physical pixels. And that is not the
center point, but the edge of our lines. Therefore we add half the penwidth to each point.

DrawOnPhysicalDevicePixels.html[2/16/2014 3:09:57 PM]


WPF Tutorial | Draw excactly on physical device pixels

Before we draw the rectange on the DrawingContext we push the guidelines to the stack. The result are lines that perfecly match
to our physical device pixels

Adjust the penwidth to the screen resolution


The last thing we need to consider is that the width of the pen is still defined in logical units. If we want to keep the pen width to one
pixel (think a moment if you really want to have this) you can scale the pen width with the ration between your screen resolution and
WPF's logical units which is 1/96.
The following sample shows you how to do this.

Matrix m = PresentationSource.FromVisual(this)
.CompositionTarget.TransformToDevice;
double dpiFactor = 1/m.M11;
 
Pen scaledPen = new Pen( Brushes.Black, 1 * dpiFactor );
 
 

Last modified: 2008-10-24 02:15:02


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 9.November 2008

I have a problem with WPF, maybe you could help me a little bit. I tried to draw on my window using
Juan
your method with the OnRender method, but nothing appears on my screen.

Commented on 11.November 2008

Hi Juan,

Christian
I have experienced the same problem. It seems that the OnRender() method does not work on
Moser
Windows. Create a custom control that derives from Control and add it to your window. Override the
OnRender() in your control. This will work.

Commented on 16.March 2009

I need to draw a grid which resembles a graph-sheet(along with minor grids), on that i need to plot line
Sam
graph. I tried to the above technique, but some horizantal lines are still alaising. It does not alias on
1280x1024 resolution, but on all other resolutions it aliases. Also its takes very long to paint. Please help
me on how can I do this so that this works for all resolutions and is paints very fast.

DrawOnPhysicalDevicePixels.html[2/16/2014 3:09:57 PM]


WPF Tutorial | Draw excactly on physical device pixels
Thanks,

Sam

Commented on 11.September 2009

Great article! Very useful. One additional thought is that if you are considering scaling your stroke
Cory Plotts
thicknesses to be physical units at the creation of the Pen ... you might want to also do that when
setting up the guidelines. That is:

double halfPenWidth = pen.Thickness / 2 * dpiFactor;

And that implicitly brings up another point ... there is no reason that you have to do this for just 1 pixel
stroke thicknesses ... although the benefits there are the most striking!

Commented on 15.December 2009

hi Christian Moser thanx alot for such explanation, though i have a question, does this also work when
zafer
im SkewTransforming a control, cause the edges get very sharp and i want them to be smooth.

thanx alot,

Zafer

Commented on 26.March 2010

This seems like the optimal method to get rid of anti-aliasing. I think it's ironic to rely on owner drawn
Yury
functions to achieve this when the goal of WPF is specifically to provide an alternative to custom
drawing.

Commented on 24.April 2010

I have a problem with life. Can you help me out with that?
Mzithra D....

Commented on 6.June 2010

You'd be better taking these stupid comments off each page on turning it into a forum, it makes your
Zaggle...
site look pretty stupid IMO

Commented on 16.June 2010

Take the time to add a signup system to keep idiots take away from what is a great site
x

Commented on 28.June 2010

Hi Sam,

HatemAmin
You can use the "DrawingBrush" to do such thing, please visit http://msdn.microsoft.com/en-
us/library/aa480159.aspx

Commented on 30.August 2010

How can I draw lines & text with the crispiness using C++ or Delphi? I hate .Net and refuse to use WPF
Johnny...
or any other crappy Microsoft technologies.

Commented on 1.September 2010

How about performing this on Silverlight 4. Is it possible? How?


Igor...

Commented on 25.May 2011

DrawOnPhysicalDevicePixels.html[2/16/2014 3:09:57 PM]


WPF Tutorial | Draw excactly on physical device pixels
You can turn off anti-aliasing with RenderOptions.SetEdgeMode(). Use this to set the edge mode of a
new_to_WPF
Canvas object to EdgeMode.Aliased. After that, anything you draw to the Canvas will not be blurry
(except text).

Commented on 16.June 2011

I recently stumbled upon a strange phenomenon:

Nebogipfel

This Code in an Image.OnRender(dc) override

GuidelineSet gs = new GuidelineSet();


gs.GuidelinesX.Add(500.5); // Arbitrary Integer + 0.5 works

gs.GuidelinesY.Add(500.5); // Arbitrary Integer + 0.5 works

dc.PushGuidelineSet(gs);

Brush b = Brushes.Red;

for (int i = 1; i &lt; 300; i++)

dc.DrawRectangle(null, new Pen(b, 1), new System.Windows.Rect(0, 0, i, i));

b = b == Brushes.Red ? Brushes.Blue : Brushes.Red;

dc.Pop();

produces perfectly pixel snapped Rectangles. It seems it takes only one Guideline in each X and Y to
work. If one of the guideline gets removed, the corresponding axis gets blurred again whilst the other
stays crisp.

Is here some blackbox magic going on? Or am I just stupid. Note that both options might apply ;)

Name

E-Mail (optional)
Comment

Post Comment

DrawOnPhysicalDevicePixels.html[2/16/2014 3:09:57 PM]


WPF Tutorial | Geometry Transformer

Home
    2D Graphics
    Geometry Transformer Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
WPF Geometry Transformation Tool
Custom Controls
The geometry transformer is a simple tool I wrote to scale-, translate- and rotate-transform a geometry in the path mini language.
Layout
Simply paste the geometry string into the input textbox and specify the transform parameters. After pressing "Transform" the output
Input textbox shows the translated geometry string. This is very useful to transform simple geometries like an expanded/collapsed chevron
used in an expander template.
Data Binding
Click here to download the Geometry Transformer

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

Last modified: 2008-10-28 15:09:03

GeometryTransformer.html[2/16/2014 3:10:34 PM]


WPF Tutorial | Geometry Transformer
Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 4.April 2009

Hmmm, I checked a "popular" article and reading without comprehension on a mini language, then I
x
noticed the search engine deceiving comments :D

Commented on 1.July 2009

can you please tell me the logic for this? i want to implement this in a vector drawing application
wpf

Commented on 1.August 2009

This is nice. Can you make the source available please?


micaleel

Commented on 2.December 2009

It'll be nice if there is source code too...


Jawahar

Commented on 26.January 2010

With WPF, you can tranform elements by using RenderTransform.

mastermind
you can rotate, scale, and move them freely. I'm sorry I have no further information, I haven't tried it yet.
Look here for example:

http://www.codeguru.com/csharp/csharp/cs_misc/userinterface/article.php/c12221/

Commented on 3.May 2010

Perfect!! Was looking for the path of a chevron and I even got the tool to rotate it as a bonus! :D Thanks
Yuri
a lot.

Commented on 20.July 2010

<StackPanel OverridesDefaultStyle=\"True\">

hi
<Button>

<Button.Background>

<SolidColorBrush x:Name=\"MyBrush\" Color=\"Orange\" >

</SolidColorBrush>

</Button.Background>

<Button.Triggers>

<EventTrigger RoutedEvent=\"Button.Click\">

<BeginStoryboard>

<Storyboard>

<DoubleAnimation
Storyboard.TargetName=\"MyAnimatedBrush\"

Storyboard.TargetProperty=\"(Brush.Opacity)\"
From=\"1\" To=\"0\" Duration=\"0:0:5\" AutoReverse=\"True\" />

</Storyboard>

</BeginStoryboard>

</EventTrigger>

</Button.Triggers>

GeometryTransformer.html[2/16/2014 3:10:34 PM]


WPF Tutorial | Geometry Transformer

</Button>

</StackPanel>

Commented on 14.September 2010

Excellent Artical i have ever seen


Haribabu

Commented on 1.December 2010

even my 3 year old child would created this type of scrap application.
rude

Commented on 15.March 2011

it is good could i have material for this


jogi

Name

E-Mail (optional)

Comment

Post Comment

GeometryTransformer.html[2/16/2014 3:10:34 PM]


WPF Tutorial | Images

Home
    2D Graphics
    Images Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Images in WPF
Custom Controls

Layout
How to set the Icon of a Window
Input
If you try to set the Window.Icon from Codebehind, you probably get the error ImageSource for Icon property must be an icon
Data Binding file.. You can use the following snippet to do the trick:

Styling  
var icon = BitmapFrame.Create(Application.GetResourceStream(
Localization
new Uri("MyAppIcon.ico", UriKind.RelativeOrAbsolute)).Stream);
Interaction  
 
Resources Note: You can get an "Image format is unrecognized" exception under XP, if the icon only contains compressed PNG files. In this case
you have to recreate the icon without compression.
2D Graphics

3D Graphics
How to create a Thumbnail of an Image
Animation
 
Multimedia private ImageSource GetThumbnail( string fileName )
{
Documents
byte[] buffer = File.ReadAllBytes(fileName);
Windows 7 MemoryStream memoryStream = new MemoryStream(buffer);
 
Interoperability
BitmapImage bitmap = new BitmapImage();
Performance bitmap.BeginInit();
bitmap.DecodePixelWidth = 80;
Expression Blend bitmap.DecodePixelHeight = 60;
bitmap.StreamSource = memoryStream;
Tools
bitmap.EndInit();
UI Automation bitmap.Freeze();
 
return bitmap;
}
 

Images.html[2/16/2014 3:10:48 PM]


WPF Tutorial | Images
 

How to automatically crop an image


The following method allows you to automatically crop an image to it's content.

 
public static ImageSource AutoCropBitmap(BitmapSource source)
{
if (source == null)
throw new ArgumentException("source");
 
if (source.Format != PixelFormats.Bgra32)
source = new FormatConvertedBitmap(source,
PixelFormats.Bgra32, null, 0);
 
int width = source.PixelWidth;
int height = source.PixelHeight;
int bytesPerPixel = source.Format.BitsPerPixel / 8;
int stride = width * bytesPerPixel;
 
var pixelBuffer = new byte[height * stride];
source.CopyPixels(pixelBuffer, stride, 0);
 
int cropTop = height, cropBottom = 0, cropLeft = width, cropRight = 0;
 
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int offset = (y * stride + x * bytesPerPixel);
byte blue = pixelBuffer[offset];
byte green = pixelBuffer[offset + 1];
byte red = pixelBuffer[offset + 2];
byte alpha = pixelBuffer[offset + 3];
 
//TODO: Define a threshold when a pixel has a content
bool hasContent = alpha > 10;
 
if (hasContent)
{
cropLeft = Math.Min(x, cropLeft);
cropRight = Math.Max(x, cropRight);
cropTop = Math.Min(y, cropTop);
cropBottom = Math.Max(y, cropBottom);
}
}
}
 
return new CroppedBitmap(source,
new Int32Rect(cropLeft, cropTop, cropRight - cropLeft,
cropBottom - cropTop));
}
 
 

Images.html[2/16/2014 3:10:48 PM]


WPF Tutorial | Images

How to flip an image horizontally or vertically


The easiest way to flip an image in WPF is to use a TransformedBitmap. It's a wrapper around a BitmapImage that takes a
generic Transform object.

 
var flippedImage = new TransformedBitmap(originalImage, new ScaleTransform( -1,1));
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2011-03-01 08:43:30


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 1.November 2009

Very nice code. I have a question though, say you have a 3 images (png, jpeg, etc). One is the regular
Curtis
image, one for mouseover and one for mousedown. Is there any way in Expression 3 or code to do an
event while still maintaining the button aspect. Meaning, is there a way to make a rollover event using
3 images?

Commented on 1.November 2009

Hi Curtis,

Christian
I did not exactly understood your question. Is it correct, that you would like to build a button that has a
Moser
normal, a mouseover and a pressed appearance?

If that was your question, you can create a style with triggers. Triggers are conditions within a style, who
can switch the source of the image, when the mouse hovers over the button or the button is pressed.

I hope this helps.

Greetings

Christian

Commented on 17.December 2009

Hi,

Nanda

Very good code, however are there any examples on image move in the canvas. For example I have a
football image and have placed in the canvas, when ever I move my mouse it should move within the
canvas and shouldn't go outside.

Commented on 27.April 2010

yeah excellent code


Gourav

Commented on 2.June 2010

Images.html[2/16/2014 3:10:48 PM]


WPF Tutorial | Images
Good code but you are wasting much memory, because of:

Christian
bitmap.StreamSource = memoryStream;

That is a reference on the stream which will be available until the Image itself is destryoed, so you are
holding the Memory for the real Image AND the thumbnail!

Better solution for me is to creating a

WriteableBitmap bmp = new WriteAbleBitmap(bitmap);

And Dispose the stream:

memorystream.close();

memorystream.Dispose();

memorystream = null;

(Better Solution is using the "Using" statement)

and returning only the thumbnail!

ps.: Some Websites recomment that you freeze() the Bitmaps to confirm that the memory is beeing
released after use

Commented on 9.June 2010

Show outputs of above examples


M.Sreekanth

Commented on 16.July 2010

How do I move an image with code ie, I want to center an image inside a grid keeping the image
Hector
hight/width ratio

Commented on 18.February 2011

Excellent Christian Moser,

Ayyappa
We need elaborate description and Examples.

INDIA

Greetings,

Ayyappan,

INDIA,

banyansoft.blogspot.com

Name

E-Mail (optional)

Comment

Post Comment

Images.html[2/16/2014 3:10:48 PM]


WPF Tutorial | How to get a Bitmap from a Visual

Home
    2D Graphics
    How to get a Bitmap from a Visual Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to get a Bitmap from a Visual
Custom Controls
 
Layout public void SaveImage(Visual visual, int width, int height, string filePath)
{
Input RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, 96, 96,
Data Binding PixelFormats.Pbgra32);
bitmap.Render(visual);
Styling  
PngBitmapEncoder image = new PngBitmapEncoder();
Localization
image.Frames.Add(BitmapFrame.Create(bitmap));
Interaction using (Stream fs = File.Create(filePath))
{
Resources
image.Save(fs);
2D Graphics }
}
3D Graphics  
 
Animation

Multimedia
  ► Tutorial   ► Learn Quick Books   ► Coding Learning   ► Basics
Documents

Windows 7
Last modified: 2009-07-13 11:28:57
Interoperability Copyright (c) by Christian Moser, 2011.

Performance

Expression Blend  Comments on this article


Tools
Show all comments
UI Automation
Commented on 24.November 2009

Awesome post!! thats what I was looking for.

Sachin
Thanks.

BitmapFromVisual.html[2/16/2014 3:11:30 PM]


WPF Tutorial | How to get a Bitmap from a Visual

Commented on 6.August 2010

Rahul Nice One!!!


Mehta

Commented on 3.May 2011

Thanks a lot !!!!


Kc

Name

E-Mail (optional)

Comment

Post Comment

BitmapFromVisual.html[2/16/2014 3:11:30 PM]


WPF Tutorial | DrawRoundedRectangle

Home
    2D Graphics
    DrawRoundedRectangle Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
DrawRoundedRectangle with individual radius for each corner
Custom Controls

Layout

Input

Data Binding

Styling
drawingContext.DrawRoundedRectangle() has an ugly limitation, that you can set the corner radius only for all four corners
Localization at the time. This function extends the drawing context by a new overload of the DrawRoundedRectangle() method, that allows
it to set the corner radius for each corner individually.
Interaction
 
Resources
/// <summary>
2D Graphics /// Draws a rounded rectangle with four individual corner radius
/// </summary>
3D Graphics public static void DrawRoundedRectangle(this DrawingContext dc, Brush brush,
Pen pen, Rect rect, CornerRadius cornerRadius)
Animation
{
Multimedia var geometry = new StreamGeometry();
using (var context = geometry.Open())
Documents
{
Windows 7 bool isStroked = pen != null;
const bool isSmoothJoin = true;
Interoperability
 
Performance context.BeginFigure(rect.TopLeft + new Vector(0, cornerRadius.TopLeft), brush
!= null, true);
Expression Blend context.ArcTo(new Point(rect.TopLeft.X + cornerRadius.TopLeft, rect.TopLeft.Y),
Tools
new Size(cornerRadius.TopLeft, cornerRadius.TopLeft),
UI Automation 90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
context.LineTo(rect.TopRight - new Vector(cornerRadius.TopRight, 0), isStroked,
isSmoothJoin);
context.ArcTo(new Point(rect.TopRight.X, rect.TopRight.Y +
cornerRadius.TopRight),
DrawRoundedRectangle.html[2/16/2014 3:11:43 PM]
WPF Tutorial | DrawRoundedRectangle

new Size(cornerRadius.TopRight, cornerRadius.TopRight),


90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
context.LineTo(rect.BottomRight - new Vector(0, cornerRadius.BottomRight),
isStroked, isSmoothJoin);
context.ArcTo(new Point(rect.BottomRight.X - cornerRadius.BottomRight,
rect.BottomRight.Y),
new Size(cornerRadius.BottomRight, cornerRadius.BottomRight),
90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
context.LineTo(rect.BottomLeft + new Vector(cornerRadius.BottomLeft, 0),
isStroked, isSmoothJoin);
context.ArcTo(new Point(rect.BottomLeft.X, rect.BottomLeft.Y -
cornerRadius.BottomLeft),
new Size(cornerRadius.BottomLeft, cornerRadius.BottomLeft),
90, false, SweepDirection.Clockwise, isStroked, isSmoothJoin);
 
context.Close();
}
dc.DrawGeometry(brush, pen, geometry);
}
 

  ► Tutorial   ► Draw   ► Adobe Illustrator   ► Photoshop Vector

Last modified: 2010-11-01 16:20:37


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 22.November 2010

lklkl
m,m,

Commented on 25.November 2010

lklkl
m,m,

Commented on 26.November 2010

Deepak this is for good


Badesara

Commented on 18.May 2011

Very nice, this is just what I needed!


Kristof...

Commented on 19.May 2011

nothing to understanu... ch*u...


Darshan

Commented on 1.August 2011

DrawRoundedRectangle.html[2/16/2014 3:11:43 PM]


WPF Tutorial | DrawRoundedRectangle
very difficult to understand there is no 2D
Poda

Commented on 13.September 2011

nice one
shweta

Name

E-Mail (optional)

Comment

Post Comment

DrawRoundedRectangle.html[2/16/2014 3:11:43 PM]


WPF Tutorial | Introduction to WPF 3D

Home
    3D Graphics
    Introduction to WPF 3D Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Introduction to WPF 3D
Custom Controls

Layout
3D Graphic Basics
Input
The basic idea of creating 3D graphics is to have a three dimensional model of an object. Because our screen is only two dimensional,
Data Binding we define a camera that takes a picture of the object. The picture is a projection of the object to a planar surface. This projection is
rendered into an bitmap by the 3D rendering engine. The engine determines the color for every pixel by calculating the amount of
Styling
light that is reflected by any light sources to the projection surface by the objects in the 3D space.
Localization
All surfaces of objects have a material and a brush. The material defines how much light is reflected for a specific angle and the
brush defines the color. A brush can either be a simple color or a gradient or even an image called texture.
Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools A world of triangles


UI Automation
In the world of 3D graphics, all objects are described by a set of triangles. But why triangles? The reason for this is that a triangle is the
most granular geometry to describe a planar surface. The rendering engine can calculate the color of each triangle depending on its
material and angle to the lights in the scene. If we would build our world on rectangles, the points don't need to be plane. The
surface will be a lot more complex to calculate and render.

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
A surface of a 3D object is called a mesh. A mesh is defined by a number of 3D points. These points are called vertices. The vertices
are joined together by a winding pattern to define the triangles. Every triangle has a front and a back side. Only the front side is
rendered. The front side is defined by the winding order of the points. WPF uses a counter clockwise winding pattern. You can
remember this with a simple mnemonic called the "right hand rule". This means if you close your right hand to a thumb-up gesture,
your finger make a counter clockwise move while the thumb shows up. The fingers show the winding order, while the thumb
indicates the upper-side of the triangle.

A right handed coordinate system


WPF uses a right-handed coordinate system. This means that if you hold the fingers of your right hand as shown on the picture, the
fingers indicate the positive direction of the tree axes.

Elements of a 3D scene
Viewport3D
The viewport is the control that builds the gate between the 2D and the 3D world.
Camera
Every 3D scene has excactly one camera. The camera defines the Position and the LookDirection and the
UpDirection of the viewer. WPF supports orthographical and perspective cameras.
3D Models
A 3D model defines an object in the scene. It has a Geometry that is the mesh and a Material that can be a diffuse,
specular or emmisive material. The material itself has a brush.

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
Lights
Without any lights you see nothing. So we need to place at least one light in our scene to illuminate our models. WPF supports
different kind of lights, like:
AmbientLight
DirectionalLight
PointLight
SpotLight

Hello 3D-World - A Simple Cube


The following example shows how to create a basic cube mesh with 8 vertices that are wired up in 12 triangles that form the shape of
the cube.

<Viewport3D>
<Viewport3D.Camera>
<PerspectiveCamera Position="-40,40,40" LookDirection="40,-40,-40 "
UpDirection="0,0,1" />
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup>
<DirectionalLight Color="White" Direction="-1,-1,-3" />
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="0,0,0 10,0,0 10,10,0 0,10,0 0,0,10
10,0,10 10,10,10 0,10,10"
TriangleIndices="0 1 3 1 2 3 0 4 3 4 7 3 4 6 7 4 5 6
0 4 1 1 4 5 1 2 6 6 5 1 2 3 7 7 6 2"/>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Red"/>
</GeometryModel3D.Material>
</GeometryModel3D>
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
 

  ► Tutorial   ► Java Web Tutorial   ► Learn Quick Books   ► Coding Learning

Last modified: 2009-07-04 16:21:17


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 20.October 2010

You have a special web-Site....And thank about the perfect information.

Debug
how now how to paint Star or polygon in the code (in WPF) and I have only

the width and height of the star or polygon.

It very important me and I need it S-O-S.

Thank

Debug.....

Commented on 21.October 2010

This is good i think this help to all developer who want to work on WPF
Shekhar

Commented on 23.November 2010

Great work !!
Achilles

Commented on 1.December 2010

need more, plz continue


tsingroo

Commented on 28.December 2010

This is good. But I like to know how to design 3D objects using Expression Blend.
Jawahar

Commented on 28.December 2010

Hey, good tutorial....well i developed a browser with this 3D cube concept but currently only single
Saurabh
phase of the browser is active to show the single URL and all other phases shows its screen shot....pls.
tell me how to enable or load different URL's on each phase...is it ur area of working or not...

Commented on 12.January 2011

232
rer

Commented on 11.February 2011

Very good article


simran

Commented on 15.February 2011

Ok so how about events, multiple geometries in the same viewport, storyboards and different lighting
Mega
types? a lil disappointed with this extremely limited example of what wpf 3d can do. guess this is not

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
the place to find out how to trigger an event when a mouse is clicked on a face of a mesh or another
mesh within the viewport

Commented on 2.March 2011

Caro,

Rafael
podes me ajudar?

tenho uma serie de pontos e preciso plotar uma superfície e rotaciona-la e aplicar zoom.

No aguardo.

Commented on 2.March 2011

Friend,

Rafael
can you help me?

I have a series of plot points and need a surface and rotate it and zoom.

Waiting in the wings.

Commented on 2.March 2011

Very Very Good And Esay To DO.


Rahul

Commented on 8.March 2011

I'll try this and after i will lets you know.


Rajendra

Commented on 9.March 2011

i want to write the PROPEQUITY in 3d and import XAML, can you tell me wht is the xaml code. pls ....
Chetan

Commented on 20.March 2011

xxgk wwprs <a href="http://www.gabbysporn.com">free adult videos</a> zgehnu g pe q cnr


free adult...

scbu ysyey [URL=http://www.gabbysporn.com - porno[/URL - eoetve e ts y fgd

Commented on 27.June 2011

Supa nice
Johnson

Commented on 7.July 2011

&lt;Viewport3D&gt;

kondsreddy
&lt;Viewport3D.Camera&gt;

&lt;PerspectiveCamera Position=&quot;-40,40,40&quot; LookDirection=&quot;40,-40,-40 &quot;


UpDirection=&quot;0,0,1&quot; /&gt;

&lt;/Viewport3D.Camera&gt;

&lt;ModelVisual3D&gt;

&lt;ModelVisual3D.Content&gt;

&lt;Model3DGroup&gt;

&lt;DirectionalLight Color=&quot;White&quot; Direction=&quot;-1,-1,-3&quot; /&gt;

&lt;GeometryModel3D&gt;

&lt;GeometryModel3D.Geometry&gt;

&lt;MeshGeometry3D Positions=&quot;0,0,0 10,0,0 10,10,0 0,10,0 0,0,10


10,0,10 10,10,10 0,10,10&quot;

TriangleIndices=&quot;0 1 3 1 2 3 0 4 3 4 7 3 4 6 7 4 5 6
0 4 1 1 4 5 1 2 6 6 5 1 2 3 7 7 6 2&quot;/&gt;

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
&lt;/GeometryModel3D.Geometry&gt;

&lt;GeometryModel3D.Material&gt;

&lt;DiffuseMaterial Brush=&quot;Red&quot;/&gt;

&lt;/GeometryModel3D.Material&gt;

&lt;/GeometryModel3D&gt;

&lt;/Model3DGroup&gt;

&lt;/ModelVisual3D.Content&gt;

&lt;/ModelVisual3D&gt;

&lt;/Viewport3D&gt;

Commented on 9.August 2011

hmm
at

Commented on 9.August 2011

very nice it's impressive


Onur

Commented on 14.August 2011

Md. Nasim nice document


Uddin

Commented on 28.August 2011

hello, I am new to 3D and WPF together,

jenny
i tried to create simple 2 buttons in Viewport3D, like this:

--------------------------------------------------------------

&lt;Viewport3D Width=&quot;300&quot; Height=&quot;300&quot; &gt;

&lt;Viewport3D.Children&gt;

&lt;Viewport2DVisual3D&gt;

&lt;Viewport2DVisual3D.Geometry&gt;

&lt;MeshGeometry3D

Positions=&quot;-1,-1,0 1,-1,0 1,1,0 -1,1,0&quot;

TextureCoordinates=&quot;0,1 1,1 1,0 0,0&quot;

TriangleIndices=&quot;0,1,2 2,3,0&quot;

/&gt;

&lt;/Viewport2DVisual3D.Geometry&gt;

&lt;Viewport2DVisual3D.Material&gt;

&lt;DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial=&quot;True&quot;
Brush=&quot;Red&quot;/&gt;

&lt;/Viewport2DVisual3D.Material&gt;

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
&lt;Canvas Height=&quot;300&quot; Width=&quot;300&quot;&gt;

&lt;Button Canvas.Left=&quot;0&quot; Canvas.Top=&quot;0&quot; Height=&quot;60&quot;


Width=&quot;60&quot; Content=&quot;one&quot; /&gt;

&lt;Button Canvas.Left=&quot;65&quot; Canvas.Top=&quot;60&quot; Height=&quot;100&quot;


Width=&quot;40&quot; Content=&quot;two&quot; /&gt;

&lt;/Canvas&gt;

&lt;/Viewport2DVisual3D&gt;

&lt;ModelVisual3D&gt;

&lt;ModelVisual3D.Content&gt;

&lt;SpotLight Color=&quot;White&quot; Position=&quot;0,0,3&quot; Direction=&quot;0,0,-1&quot;


Range=&quot;50&quot;

OuterConeAngle=&quot;59&quot; InnerConeAngle=&quot;0&quot; /&gt;

&lt;/ModelVisual3D.Content&gt;

&lt;/ModelVisual3D&gt;

&lt;/Viewport3D.Children&gt;

&lt;!-- Camera. --&gt;

&lt;Viewport3D.Camera&gt;

&lt;PerspectiveCamera FarPlaneDistance=&quot;20&quot;

LookDirection=&quot;0,0,-1&quot;

UpDirection=&quot;0,1,1&quot;

NearPlaneDistance=&quot;1&quot;

Position=&quot;0,0,5&quot;

FieldOfView=&quot;45&quot;

/&gt;

&lt;/Viewport3D.Camera&gt;

&lt;/Viewport3D&gt;

----------------------------------------------------------------------

i can't understand why when i change the properties of one button its affecting how i see the other
button, for example when i change button's &quot;two&quot; height from 60 to 100 , button
&quot;one&quot; becomes smaller???

please help me understand,

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D

tnx jenny

Commented on 28.August 2011

hello, I am new to 3D and WPF together,

jenny
i tried to create simple 2 buttons in Viewport3D, like this:

--------------------------------------------------------------

&lt;Viewport3D Width=&quot;300&quot; Height=&quot;300&quot; &gt;

&lt;Viewport3D.Children&gt;

&lt;Viewport2DVisual3D&gt;

&lt;Viewport2DVisual3D.Geometry&gt;

&lt;MeshGeometry3D

Positions=&quot;-1,-1,0 1,-1,0 1,1,0 -1,1,0&quot;

TextureCoordinates=&quot;0,1 1,1 1,0 0,0&quot;

TriangleIndices=&quot;0,1,2 2,3,0&quot;

/&gt;

&lt;/Viewport2DVisual3D.Geometry&gt;

&lt;Viewport2DVisual3D.Material&gt;

&lt;DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial=&quot;True&quot;
Brush=&quot;Red&quot;/&gt;

&lt;/Viewport2DVisual3D.Material&gt;

&lt;Canvas Height=&quot;300&quot; Width=&quot;300&quot;&gt;

&lt;Button Canvas.Left=&quot;0&quot; Canvas.Top=&quot;0&quot; Height=&quot;60&quot;


Width=&quot;60&quot; Content=&quot;one&quot; /&gt;

&lt;Button Canvas.Left=&quot;65&quot; Canvas.Top=&quot;60&quot; Height=&quot;100&quot;


Width=&quot;40&quot; Content=&quot;two&quot; /&gt;

&lt;/Canvas&gt;

&lt;/Viewport2DVisual3D&gt;

&lt;ModelVisual3D&gt;

&lt;ModelVisual3D.Content&gt;

&lt;SpotLight Color=&quot;White&quot; Position=&quot;0,0,3&quot; Direction=&quot;0,0,-1&quot;


Range=&quot;50&quot;

OuterConeAngle=&quot;59&quot; InnerConeAngle=&quot;0&quot; /&gt;

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
&lt;/ModelVisual3D.Content&gt;

&lt;/ModelVisual3D&gt;

&lt;/Viewport3D.Children&gt;

&lt;!-- Camera. --&gt;

&lt;Viewport3D.Camera&gt;

&lt;PerspectiveCamera FarPlaneDistance=&quot;20&quot;

LookDirection=&quot;0,0,-1&quot;

UpDirection=&quot;0,1,1&quot;

NearPlaneDistance=&quot;1&quot;

Position=&quot;0,0,5&quot;

FieldOfView=&quot;45&quot;

/&gt;

&lt;/Viewport3D.Camera&gt;

&lt;/Viewport3D&gt;

----------------------------------------------------------------------

i can't understand why when i change the properties of one button its affecting how i see the other
button, for example when i change button's &quot;two&quot; height from 60 to 100 , button
&quot;one&quot; becomes smaller???

please help me understand,

tnx jenny

Commented on 28.August 2011

hello, I am new to 3D and WPF together,

jenny
i tried to create simple 2 buttons in Viewport3D, like this:

--------------------------------------------------------------

&lt;Viewport3D Width=&quot;300&quot; Height=&quot;300&quot; &gt;

&lt;Viewport3D.Children&gt;

&lt;Viewport2DVisual3D&gt;

&lt;Viewport2DVisual3D.Geometry&gt;

&lt;MeshGeometry3D

Positions=&quot;-1,-1,0 1,-1,0 1,1,0 -1,1,0&quot;

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
TextureCoordinates=&quot;0,1 1,1 1,0 0,0&quot;

TriangleIndices=&quot;0,1,2 2,3,0&quot;

/&gt;

&lt;/Viewport2DVisual3D.Geometry&gt;

&lt;Viewport2DVisual3D.Material&gt;

&lt;DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial=&quot;True&quot;
Brush=&quot;Red&quot;/&gt;

&lt;/Viewport2DVisual3D.Material&gt;

&lt;Canvas Height=&quot;300&quot; Width=&quot;300&quot;&gt;

&lt;Button Canvas.Left=&quot;0&quot; Canvas.Top=&quot;0&quot; Height=&quot;60&quot;


Width=&quot;60&quot; Content=&quot;one&quot; /&gt;

&lt;Button Canvas.Left=&quot;65&quot; Canvas.Top=&quot;60&quot; Height=&quot;100&quot;


Width=&quot;40&quot; Content=&quot;two&quot; /&gt;

&lt;/Canvas&gt;

&lt;/Viewport2DVisual3D&gt;

&lt;ModelVisual3D&gt;

&lt;ModelVisual3D.Content&gt;

&lt;SpotLight Color=&quot;White&quot; Position=&quot;0,0,3&quot; Direction=&quot;0,0,-1&quot;


Range=&quot;50&quot;

OuterConeAngle=&quot;59&quot; InnerConeAngle=&quot;0&quot; /&gt;

&lt;/ModelVisual3D.Content&gt;

&lt;/ModelVisual3D&gt;

&lt;/Viewport3D.Children&gt;

&lt;!-- Camera. --&gt;

&lt;Viewport3D.Camera&gt;

&lt;PerspectiveCamera FarPlaneDistance=&quot;20&quot;

LookDirection=&quot;0,0,-1&quot;

UpDirection=&quot;0,1,1&quot;

NearPlaneDistance=&quot;1&quot;

Position=&quot;0,0,5&quot;

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
FieldOfView=&quot;45&quot;

/&gt;

&lt;/Viewport3D.Camera&gt;

&lt;/Viewport3D&gt;

----------------------------------------------------------------------

i can't understand why when i change the properties of one button its affecting how i see the other
button, for example when i change button's &quot;two&quot; height from 60 to 100 , button
&quot;one&quot; becomes smaller???

please help me understand,

tnx jenny

Commented on 28.August 2011

hello, I am new to 3D and WPF together,

jenny
i tried to create simple 2 buttons in Viewport3D, like this:

--------------------------------------------------------------

&lt;Viewport3D Width=&quot;300&quot; Height=&quot;300&quot; &gt;

&lt;Viewport3D.Children&gt;

&lt;Viewport2DVisual3D&gt;

&lt;Viewport2DVisual3D.Geometry&gt;

&lt;MeshGeometry3D

Positions=&quot;-1,-1,0 1,-1,0 1,1,0 -1,1,0&quot;

TextureCoordinates=&quot;0,1 1,1 1,0 0,0&quot;

TriangleIndices=&quot;0,1,2 2,3,0&quot;

/&gt;

&lt;/Viewport2DVisual3D.Geometry&gt;

&lt;Viewport2DVisual3D.Material&gt;

&lt;DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial=&quot;True&quot;
Brush=&quot;Red&quot;/&gt;

&lt;/Viewport2DVisual3D.Material&gt;

&lt;Canvas Height=&quot;300&quot; Width=&quot;300&quot;&gt;

&lt;Button Canvas.Left=&quot;0&quot; Canvas.Top=&quot;0&quot; Height=&quot;60&quot;


Width=&quot;60&quot; Content=&quot;one&quot; /&gt;

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
&lt;Button Canvas.Left=&quot;65&quot; Canvas.Top=&quot;60&quot; Height=&quot;100&quot;
Width=&quot;40&quot; Content=&quot;two&quot; /&gt;

&lt;/Canvas&gt;

&lt;/Viewport2DVisual3D&gt;

&lt;ModelVisual3D&gt;

&lt;ModelVisual3D.Content&gt;

&lt;SpotLight Color=&quot;White&quot; Position=&quot;0,0,3&quot; Direction=&quot;0,0,-1&quot;


Range=&quot;50&quot;

OuterConeAngle=&quot;59&quot; InnerConeAngle=&quot;0&quot; /&gt;

&lt;/ModelVisual3D.Content&gt;

&lt;/ModelVisual3D&gt;

&lt;/Viewport3D.Children&gt;

&lt;!-- Camera. --&gt;

&lt;Viewport3D.Camera&gt;

&lt;PerspectiveCamera FarPlaneDistance=&quot;20&quot;

LookDirection=&quot;0,0,-1&quot;

UpDirection=&quot;0,1,1&quot;

NearPlaneDistance=&quot;1&quot;

Position=&quot;0,0,5&quot;

FieldOfView=&quot;45&quot;

/&gt;

&lt;/Viewport3D.Camera&gt;

&lt;/Viewport3D&gt;

----------------------------------------------------------------------

i can't understand why when i change the properties of one button its affecting how i see the other
button, for example when i change button's &quot;two&quot; height from 60 to 100 , button
&quot;one&quot; becomes smaller???

please help me understand,

tnx jenny

Commented on 16.September 2011

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Introduction to WPF 3D
Hi Everyone,

BindraBindu
Really! this is very nice article.

Here I have also another example, how to create 3D shape in WPF. Please check out the following
links for more details .............

http://www.mindstick.com/Articles/fdec9740-4e4c-49c2-8395-6e610950f3c4/?Create%203-
D%20cube%20in%20WPF

Thanks !!!!!!!

Name

E-Mail (optional)
Comment

Post Comment

IntroductionTo3D.html[2/16/2014 3:12:17 PM]


WPF Tutorial | Debugging Animations

Home
    Animation
    Debugging Animations Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Debugging style and template Errors
Custom Controls

Layout
Common Errors

Input If you get the following error: Cannot animate ... on an immutable object instance. it could be that you are run
into one of the following issues:
Data Binding
You are animating a dependency property without having a value set
Styling
You are animating a dependency property who's value is resolved by a DynamicResource
Localization You are animating a dependency property who's current value is defined in another assembly that is not merged into the
Interaction
resource dictionary.
You are animating a value that is currently databound
Resources You have an invalid property path specified.
2D Graphics

3D Graphics
  ► Tutorial   ► C Sharp Tutorial   ► C C++ Programming   ► Visual C++
Animation

Multimedia
Last modified: 2011-03-24 17:42:20
Documents Copyright (c) by Christian Moser, 2011.

Windows 7

Interoperability  Comments on this article


Performance
Show all comments
Expression Blend
Commented on 11.September 2009
Tools
Thanks for putting this up, it helped.
Dmitry
UI Automation

Commented on 19.November 2009

siva its good but give more information

DebuggingAnimations.html[2/16/2014 3:12:34 PM]


WPF Tutorial | Debugging Animations
krishna...

Commented on 1.March 2010

This Content is Useful. But it is not enough. Need More Info


Thangavel

Commented on 21.March 2010

This is no brainer that most of us will try to set color in storyboard and get this exception. not only you
Not Crishna
havent mentioned it but you also dont say what to do.... and yeah - what does "without setting a local
value" means really? local to what? typical jew stuff. saying but not telling. thanks

Commented on 11.July 2010

I have a question
alan

Commented on 21.October 2010

@Not Crishna - Local Value = for example: property value set in xaml or call SetValue directly in code for
Stefan
example. Basically, the WPF framework calls SetValue(...) for a given DP when used in bindings directly
instead of the property, that's why the breeakpoint set in the DP setter sometimes doesn't get hit.

@Christian M - Thanks man. If only I could have had this 1 year ago... :)

Name

E-Mail (optional)

Comment

Post Comment

DebuggingAnimations.html[2/16/2014 3:12:34 PM]


WPF Tutorial | Adjust the Frame Rate

Home
    Animation
    Adjust the Frame Rate Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to control the frame rate for WPF animations
Custom Controls
Animations are very cool, but they can cause a high CPU load. One reason could be a missing hardware acceleration due to a old
Layout graphics adapter or a software rendering constraint. Another reason could be the the high frame rate of animations that is set to 60
fps by default.
Input
You can easily lower the framerate for all animations by overriding the DesiredFrameRate property of the timeline. Just add the
Data Binding
following code to your project and play around with the setting to find a good tradeoff between performance and aesthetic.
Styling
 
Localization Timeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline),
new FrameworkPropertyMetadata { DefaultValue = 30 });
Interaction  
Resources
 
Or you can set the framerate individually for each animation in XAML, using the following code:
2D Graphics  
3D Graphics
<DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:0.5"
From="1.0" To="0.5" Timeline.DesiredFrameRate="30" />
Animation  
 
Multimedia

Documents
  ► Tutorial   ► ActionScript   ► Flash 8   ► Flash CS3
Windows 7

Interoperability
Last modified: 2010-03-02 00:31:02
Performance Copyright (c) by Christian Moser, 2011.

Expression Blend

Tools  Comments on this article

UI Automation
Show all comments

Commented on 4.February 2010

Good tutorial for WPF


karthik

FrameRate.html[2/16/2014 3:13:10 PM]


WPF Tutorial | Adjust the Frame Rate

Commented on 1.March 2010

Thank you for this. And seeing it's defined by a property, we can even define this individually for
RomanK
animations (e.g. to make soft animations smoother or reduce CPU load on fast animations). In XAML
this can look like this:

<DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:0.5" From="1.0" To="0.5"


Timeline.DesiredFrameRate="30" />

Why not add this to your tutorial?

Commented on 2.March 2010

Christian Thanks Roman! I added your XAML example.


Moser

Commented on 28.March 2010

Adjusting frame rates was always a mess for me being a novice flash programmer , the way you
Atul Raina
expressed the topic out here would help me in getting through. Thanks a lot and your knowledge
share is appreciating

Commented on 24.July 2010

Nice tutorial
Iyappan Mani

Commented on 25.July 2010

klam zy el fol wallahy , ana msh 3aref a2olko eh > < ento nas zy el fol , 5llo balko mn nfsko w isa
3bdeen tb3n
htb2o 7d kowyes

Commented on 25.July 2010

klam zy el fol wallahy , ana msh 3aref a2olko eh > < ento nas zy el fol , 5llo balko mn nfsko w isa
3bdeen tb3n
htb2o 7d kowyes

Commented on 11.August 2010

Does a round gauge control (controls for WPF) uses animation to move the indicator??? thanks
Qualitatserz...

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
MOSER
from another website

Commented on 23.August 2010

I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
MOSEY
from another website

Commented on 6.September 2010

Good
subbu

Commented on 21.September 2010

FrameRate.html[2/16/2014 3:13:10 PM]


WPF Tutorial | Adjust the Frame Rate
Hi

Rev
Cool Article, but I have real big problem with animations.(its about framrates)

Commented on 29.March 2011

Hi
raj
Cool Article, but I have real big problem with animations.(its about framrates)

Commented on 19.July 2011

GOOD TUTORIAL..
shivraj...

Commented on 4.August 2011

its good but how to add in user control please tell


Pradip

Commented on 13.September 2011

swetha Thank you..nice tutorial


sreepada

Name

E-Mail (optional)

Comment

Post Comment

FrameRate.html[2/16/2014 3:13:10 PM]


WPF Tutorial | Inline Images in a FlowDocument

Home
    Documents
    Inline Images in a FlowDocument Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to inline Images in a FlowDocument
Custom Controls

Layout
Introduction
Input
Sometimes you want to deploy, share or load just a plain XAML file containing a FlowDocument. Then you want to put in some inline
Data Binding images. HTML provides a functionality to express the image as Base64 encoded CDATA section, but WPF does not have such a
functionality.
Styling

Localization
I found a solution how to do this, by creating a custom InlineImage element, that does the trick. The following example shows
how to do it.
Interaction
 
Resources <FlowDocument>
<InlineImage Width="100" Height="100" Stretch="Fill">
2D Graphics
<![CDATA[iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAB3RJTUUH2AQP
3D Graphics SFlzAAALEgAACxIB0t1+/AAAAARnQU1BAACxjwv8YQUAAAnOSURBVHjaxVcLcBvVFT1vV
ki3Hju3GCQnGjkObONQkJkxCSIHQQGnIdEr5TFs+LaGl7RRCSUvDp8nglH4mDGQ6EwZIm=]]>
Animation </InlineImage>
Multimedia
</FlowDocument>
 
Documents  

Windows 7
Implementation of the InlineImage Control
Interoperability
 
Performance namespace XamlInlineImageDemo
{
Expression Blend  
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation",
Tools
"XamlInlineImageDemo")]
UI Automation  
[ContentProperty("Base64Source")]
public class InlineImage : BlockUIContainer
{
#region DependencyProperty 'Width'

InlineImagesXaml.html[2/16/2014 3:13:23 PM]


WPF Tutorial | Inline Images in a FlowDocument
 
/// <summary>
/// Gets or sets the width.
/// </summary>
public double Width
{
get { return (double)GetValue(WidthProperty); }
set { SetValue(WidthProperty, value); }
}
 
/// <summary>
/// Registers a dependency property to get or set the width
/// </summary>
public static readonly DependencyProperty WidthProperty =
DependencyProperty.Register("Width", typeof(double),
typeof(InlineImage),
new FrameworkPropertyMetadata(Double.NaN));
 
#endregion
 
#region DependencyProperty 'Height'
 
/// <summary>
/// Gets or sets the height.
/// </summary>
public double Height
{
get { return (double)GetValue(HeightProperty); }
set { SetValue(HeightProperty, value); }
}
 
/// <summary>
/// Registers a dependency property to get or set the height
/// </summary>
public static readonly DependencyProperty HeightProperty =
DependencyProperty.Register("Height", typeof(double),
typeof(InlineImage),
new FrameworkPropertyMetadata(Double.NaN));
 
#endregion
 
#region DependencyProperty 'Stretch'
 
/// <summary>
/// Gets or sets the stretch behavior.
/// </summary>
public Stretch Stretch
{
get { return (Stretch)GetValue(StretchProperty); }
set { SetValue(StretchProperty, value); }
}
 
/// <summary>
/// Registers a dependency property to get or set the stretch behavior
/// </summary>
public static readonly DependencyProperty StretchProperty =
InlineImagesXaml.html[2/16/2014 3:13:23 PM]
WPF Tutorial | Inline Images in a FlowDocument

DependencyProperty.Register("Stretch", typeof(Stretch),
typeof(InlineImage),
new FrameworkPropertyMetadata(Stretch.Uniform));
 
#endregion
 
#region DependencyProperty 'StretchDirection'
 
/// <summary>
/// Gets or sets the stretch direction.
/// </summary>
public StretchDirection StretchDirection
{
get { return (StretchDirection)GetValue(StretchDirectionProperty); }
set { SetValue(StretchDirectionProperty, value); }
}
 
/// <summary>
/// Registers a dependency property to get or set the stretch direction
/// </summary>
public static readonly DependencyProperty StretchDirectionProperty =
DependencyProperty.Register("StretchDirection", typeof(StretchDirection),
typeof(InlineImage),
new FrameworkPropertyMetadata(StretchDirection.Both));
 
#endregion
 
#region DependencyProperty 'Base64Source'
 
/// <summary>
/// Gets or sets the base64 source.
/// </summary>
public string Base64Source
{
get { return (string)GetValue(Base64SourceProperty); }
set { SetValue(Base64SourceProperty, value); }
}
 
/// <summary>
/// Registers a dependency property to get or set the base64 source
/// </summary>
public static readonly DependencyProperty Base64SourceProperty =
DependencyProperty.Register("Base64Source", typeof(string),
typeof(InlineImage),
new FrameworkPropertyMetadata(null, OnBase64SourceChanged));
 
#endregion
 
#region Private Members
 
private static void OnBase64SourceChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
var inlineImage = (InlineImage)sender;
var stream = new

InlineImagesXaml.html[2/16/2014 3:13:23 PM]


WPF Tutorial | Inline Images in a FlowDocument
MemoryStream(Convert.FromBase64String(inlineImage.Base64Source));
 
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = stream;
bitmapImage.EndInit();
 
var image =new Image {
Source = bitmapImage,
Stretch = inlineImage.Stretch,
StretchDirection = inlineImage.StretchDirection,
};
 
if (!double.IsNaN(inlineImage.Width))
{
image.Width = inlineImage.Width;
}
 
if (!double.IsNaN(inlineImage.Height))
{
image.Height = inlineImage.Height;
}
 
inlineImage.Child = image;
}
 
#endregion
 
}
}
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2010-07-15 08:22:33


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 19.May 2011

0
o

Commented on 15.June 2011

aa
Aa

Commented on 5.July 2011

Very good tutorial

MooningGloub

InlineImagesXaml.html[2/16/2014 3:13:23 PM]


WPF Tutorial | Inline Images in a FlowDocument

Name

E-Mail (optional)

Comment

Post Comment

InlineImagesXaml.html[2/16/2014 3:13:23 PM]


WPF Tutorial | FlowDocuments

Home
    Documents
    FlowDocuments Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to use FlowDocuments
Custom Controls

Layout
How to save or load a FlowDocument embedded images
Input
There is a way to save and load a flow document including all embedded images by putting them into a XamlPackage. The
Data Binding following sample shows how to do this:

Styling  
// Save
Localization
var source = new FlowDocument();
Interaction var range = new TextRange(source.ContentStart, source.ContentEnd);
using (var stream = File.Create("output.pak"))
Resources {
2D Graphics
range.Save(stream, DataFormats.XamlPackage);
}
3D Graphics  
 
Animation  
// Load
Multimedia using(var stream = File.OpenRead("output.pak"))
Documents
{
var target = new FlowDocument();
Windows 7 var range = new TextRange(target.ContentStart, target.ContentEnd);
range.Load(stream, DataFormats.XamlPackage);
Interoperability
}
Performance  
 
Expression Blend

Tools
How to navigate by hyperlinks
UI Automation If you have a FlowDocument that contains Hyperlinks and you want to perform some action when the user clicks on the link, you can
use hook up to the RoutedEvent Hyperlink.RequestNavigateEvent. The following code snippet shows you how to do it:

 
<Window x:Class="HyperlinksInFlowDocument.Window1"

FlowDocuments.html[2/16/2014 3:13:37 PM]


WPF Tutorial | FlowDocuments
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<FlowDocumentReader>
<FlowDocument>
<Paragraph>
<Hyperlink NavigateUri="http://www.google.ch">Google</Hyperlink>
</Paragraph>
</FlowDocument>
</FlowDocumentReader>
</Grid>
</Window>
 
 
 
public Window1()
{
InitializeComponent();
AddHandler(Hyperlink.RequestNavigateEvent, new
RoutedEventHandler(OnNavigationRequest));
}
 
public void OnNavigationRequest(object sender, RoutedEventArgs e)
{
var source = e.OriginalSource as Hyperlink;
if (source != null)
Process.Start(source.NavigateUri.ToString());
}
 
 

  ► Tutorial   ► 3D Max Tutorials   ► Lightwave 3D   ► Rhino 3D


Last modified: 2010-07-08 17:45:05


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 5.September 2010

Thanks! Very Useful


Umar

Commented on 7.September 2010

Thanks
Soundar

Commented on 12.October 2010

thanks
tarun

FlowDocuments.html[2/16/2014 3:13:37 PM]


WPF Tutorial | FlowDocuments

Commented on 20.November 2010

Thanks !!
Anil

Commented on 24.September 2011

Hi!Thanks
ngocanhk6apro

Name

E-Mail (optional)

Comment

Post Comment

FlowDocuments.html[2/16/2014 3:13:37 PM]


WPF Tutorial | Task Dialog

Home
    Windows 7
    Task Dialog Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to use the Windows Vista TaskDialog in WPF
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability
Introduction
Performance Windows Vista comes with an new standard dialog box called task dialog. The TaskDialog was developed as part of Windows Vista's
"clarity" offensive to improve the user experience. It provides a lot more features than the original message box.
Expression Blend
The TaskDialog is part of the comctrl32.dll library and only available on Windows Vista or later, its not part of WPF or the .NET
Tools framework. To use it from managed code, we need to write a interop wrapper.
UI Automation This article is not finished yet... :-(

TaskDialog.html[2/16/2014 3:14:14 PM]


WPF Tutorial | Task Dialog

Last modified: 2009-02-10 09:05:09


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 15.June 2009

When is it going to be finished?


AlSki

Commented on 9.August 2009

looking forward to the article being finished.


vrd

Commented on 12.August 2009

You can use the Vista Bridge Library and/or the Windows API Code Pack:

Mani
http://code.msdn.microsoft.com/VistaBridge

http://code.msdn.microsoft.com/WindowsAPICodePack

HTH, Mani

Commented on 25.August 2009

really looking foward to this...

Austin
if i want to create an App with taskdialog, do i create the lib myself or can i download it from
somewhere and use it?

Commented on 31.August 2009

pretty much
cortisol

Commented on 6.June 2010

amitabh we are waiting for it buddy..


ghosh

Commented on 27.July 2010

You could release the source code of this application (screenshot) for

Flavio
download?

Commented on 22.August 2010

use Ookii dialog. it is good to use.


YJ

Commented on 13.September 2010

In addition to Manis comment from 12.August 2009...

Christian
There is a nice tutorial available as PDF on how to use the WinAPICodePack and its components:

http://www.hinzberg.net/api7/api7/downlaods_files/windows7api.pdf

TaskDialog.html[2/16/2014 3:14:14 PM]


WPF Tutorial | Task Dialog
Have fun!

Commented on 2.January 2011

Please update it tutorial. I am going mad implementing the API. Please!


Anonymous

Commented on 21.January 2011

It contains an incomplete information of taskdialog


rajesh

Commented on 19.May 2011

can I create a Font application (same as the application we click to change font its size and style) in
swat
WPF????? And if yes How??????

Commented on 31.May 2011

Hi,

Sreekumar
Can you please complete this article........

Commented on 19.July 2011

Danke f&Atilde;&frac14;r den Link zur Windows7api.pdf, war sehr hilfreich. Spitzen Homepage, immer
Tiberius
ein Quell an Inspiration f&Atilde;&frac14;r mich!

Commented on 28.July 2011

2 years and nothing comes. asshole


yourMother

Commented on 29.July 2011

Look under http://www.codeproject.com/KB/WPF/WPFTaskDialogVistaAndXP.aspx

Lmaa
There is Code for you

Commented on 4.September 2011

Can u please complete this atical, and show how to use it.

Ahtesham

reagrds thanks.

Name

E-Mail (optional)

Comment

Post Comment

TaskDialog.html[2/16/2014 3:14:14 PM]


WPF Tutorial | Glass Windows

Home
    Windows 7
    Glass Windows Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to extend the Aero Glass into the Client area
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation
Introduction
Multimedia
Windows Vista has a new default theme called Aero glass. In Aero glass, the title bar of a window and the frame is drawn transculent.
Documents
This gives the UI a clean and lightweight look. This nice feaure is provided by a service that is called the desktop window manager
Windows 7 (DWM).

Interoperability

Performance Extending the Glass


Expression Blend By default the blurry glass effect is only on the title bar and the frame, but the client area is drawn opaque. But there is a simple way
to extend the glass into the client area by using the DWM's API.
Tools
First thing you need to do is to include some Win32 functions from the dwmapi.dll library.
UI Automation
 
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Media;

ExtendGlass.html[2/16/2014 3:14:34 PM]


WPF Tutorial | Glass Windows
using System.Windows;
 
[StructLayout(LayoutKind.Sequential)]
struct MARGINS
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
}
 
[DllImport("dwmapi.dll")]
static extern int
DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
 
[DllImport("dwmapi.dll")]
extern static int DwmIsCompositionEnabled(ref int en);
 
 
 
I have written a helper method that does all the stuff to extend the glass by the specified amount of pixels on each border of the
window.
 
 
/// <summary>
/// Extends the glass area into the client area of the window
/// </summary>
/// <param name="window"></param>
/// <param name="top"></param>
public static void ExtendGlass(Window window, Thickness thikness)
{
try
{
int isGlassEnabled = 0;
DwmIsCompositionEnabled(ref isGlassEnabled);
if (Environment.OSVersion.Version.Major > 5 && isGlassEnabled > 0)
{
// Get the window handle
WindowInteropHelper helper = new WindowInteropHelper(window);
HwndSource mainWindowSrc = (HwndSource)HwndSource.
FromHwnd(helper.Handle);
mainWindowSrc.CompositionTarget.BackgroundColor =
Colors.Transparent;
 
// Get the dpi of the screen
System.Drawing.Graphics desktop =
System.Drawing.Graphics.FromHwnd(mainWindowSrc.Handle);
float dpiX = desktop.DpiX / 96;
float dpiY = desktop.DpiY / 96;
 
// Set Margins
MARGINS margins = new MARGINS();
margins.cxLeftWidth = (int)(thikness.Left * dpiX);
margins.cxRightWidth = (int)(thikness.Right * dpiX);
margins.cyBottomHeight = (int)(thikness.Bottom * dpiY);

ExtendGlass.html[2/16/2014 3:14:34 PM]


WPF Tutorial | Glass Windows
margins.cyTopHeight = (int)(thikness.Top * dpiY);
 
window.Background = Brushes.Transparent;
 
int hr = DwmExtendFrameIntoClientArea(mainWindowSrc.Handle,
ref margins);
}
else
{
window.Background = SystemColors.WindowBrush;
}
}
catch (DllNotFoundException)
{
 
}
}
 
 
Next thing you need to do is calling the ExtendGlass in the OnSourceInitialized callback. Because that is the time the
window handle has been created.

 
 
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
GlassHelper.ExtendGlass(this, LayoutRoot.Margin);
}
 
 
 
Since the user (or the system) can enable or disable the glass effect while the application is running, we need to hook up a callback in
the WndProc to undo or initialize the glass extension dynamically.

 
 
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,
IntPtr lParam, ref bool handled)
{
if (msg == GlassHelper.WM_DWMCOMPOSITIONCHANGED)
{
GlassHelper.ExtendGlass(this, LayoutRoot.Margin);
handled = true;
}
return IntPtr.Zero;
}
 
 
 

  ► Tutorial   ► Photoshop CS4   ► Glass Buttons   ► Photoshop Vector

Last modified: 2009-12-16 16:45:09


Copyright (c) by Christian Moser, 2011.

ExtendGlass.html[2/16/2014 3:14:34 PM]


WPF Tutorial | Glass Windows

 Comments on this article

Show all comments

Commented on 16.July 2009

Is it just me, or does Expression Blend 3 (RC) completely ignore the fact that there's a System.Drawing
Tim
namespace? I can't make the code work, and it's just this one single part that is holding me up. It says
there's no "Drawing" namespace in the "System" namespace. (???)

Commented on 16.July 2009

PS -- I got it working by removing the DPI detection (a workaround, not a fix, of course), and then it
Tim
started working like a charm. thanks so much for the helper class! Lovely how it pulls the margin right
off of my LayoutRoot!!

Commented on 16.July 2009

Hi Tim,

Christian
The System.Drawing namespace is defined in a separate assembly called "System.Drawing". You
Moser
probably forgot to add a reference to that assembly. In Blend it's a bit tricky to do this. But in Visual
Studio just right-click of the "References" folder in your project and choose "Add Reference..." then
select the tab ".NET" and find the "System.Drawing" entry.

I hope this helps.

Greetings

Christian

Commented on 17.July 2009

Thanks-- I'm still a bit new to C#, and my experience with Java isn't helping much at times like this :)
Tim
Thanks for the tip-- I will be sure to make use of it.

By the way, do you know if there's a way to render text with the Vista/Win7 blur behind it? That is, the
effect used on the gadget list when you try to add to the sidebar/desktop, or in the titlebar of a
window? I've read about this for doing straight-up C/++ application programming, but I don't know if
there is a way to specify such things given the interface that Blend gives you. And it would be slightly
backwards if I had to programatically render the text instead of using the xaml/gui editor.

If not, I can live with it :P (or fake the effect, either way!) Thanks muchly for sharing your expertise.

Commented on 17.July 2009

Hi Tim,

Christian
Moser
check out this Expression Blend Behavior: http://gallery.expression.microsoft.com/en-us/GlassBehavior

Greetings

Christian

Commented on 17.July 2009

Perfect. Thanks again. This is what I imagined it should be like :)


Tim

ExtendGlass.html[2/16/2014 3:14:34 PM]


WPF Tutorial | Glass Windows

Commented on 5.August 2009

Reading over the MSDN documentation, it looks as if the whole client area will have the Aero Glass
Matt
drawn under it if you set the margins to -1.

Wilkinson

http://msdn.microsoft.com/en-us/library/aa969537%28VS.85%29.aspx#frameextend

Commented on 28.August 2009

Implementation in VB.NET:

Ankit
Malhotra

Imports System.Drawing

Imports System.Runtime.InteropServices

Public Class Form1

<DllImport("dwmapi.dll", CharSet:=CharSet.Auto)> _

Public Shared Sub DwmExtendFrameIntoClientArea(ByVal hWnd As System.IntPtr, ByRef pMargins As


Printing.Margins)

End Sub

Private Glass_brush As SolidBrush = New SolidBrush(Color.Black)

Private border_extensions As Printing.Margins = New Printing.Margins

'Public Structure Margins

' Public Left As Integer

' Public Right As Integer

' Public Top As Integer

' Public Bottom As Integer

'End Structure

Public Sub New()

InitializeComponent()

border_extensions.Top = 300 'amount of border extension required from top border

border_extensions.Left = 300 'amount of border extension required from left border

border_extensions.Right = 300 'amount of border extension required from right border

border_extensions.Bottom = 300 'amount of border extension required from the bottom border

DwmExtendFrameIntoClientArea(Me.Handle, border_extensions)

End Sub

Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

e.Graphics.FillRectangle(Glass_brush, New System.Drawing.Rectangle(0, 0, 300, 300))

'' painting the areas in client regions in black..if these fall in the margins described u would get
'' glass effect!

End Sub

End Class

Commented on 20.October 2009

It seems overkill to do anything based just plainly on operating system such as vista. I work at a massive
Chris Jacobs
organisation and they wouldn't touch it. I havent used it so no comment, i like the glass effect. But
seriously solutions should and need to be for XP and above, not just for vista. home users use vista
organisations tend to stay away. And thats a fact. Why have a nice window that looks crap when
majority of users use it.

ExtendGlass.html[2/16/2014 3:14:34 PM]


WPF Tutorial | Glass Windows

Commented on 24.December 2009

why does my buttons and images look weird? my pictures have no transparency and my buttons don't
mitzaodx
show like buttons... they look weird..??

Commented on 27.December 2009

Fixed the buttons. I changed the color from black to navy and used a pannel to get the aero feel. I just
mitzaodx
want to know is there a way that the icons displayed in a listview can be full scale? when i set it to
32x32 they look very bad, can it be that the icons look like vista desktop icons? with that kind of select
effect?

Commented on 27.December 2009

thank,s
saman

Commented on 28.December 2009

Fixed the buttons. I changed the color from black to navy and used a pannel to get the aero feel. I just
mitzaodx
want to know is there a way that the icons displayed in a listview can be full scale? when i set it to
32x32 they look very bad, can it be that the icons look like vista desktop icons? with that kind of select
effect?

Commented on 6.January 2010

Hi, i have a problem with "complete" implementation of this. Could You please post a link to complete
Michał
source code of GlassHelper and sample Window that is to make use of it ? Thanks in advance, Michal

Commented on 11.January 2010

Hi Christian. Worked almost as expected ;-)


Tschaena

Commented on 17.April 2010

Hi Christian, thanks for a great tutorial. It works beautifully but I'm curious, just how does this look on
Eon
XP? Also, I was wondering if you know a technique to also extend the ability to drag a window by
clicking on the title bar over the entire new glass region. Even though the glass looks seamless I am still
only able to drag a window by the region up at the top.

Commented on 26.April 2010

Hey--do this work on Win 3.1?


Bob

Commented on 27.April 2010

yes, this do work on 3.1. I am currently getting it to work on DOS


Jill

Commented on 27.May 2010

cxv
vcxv

Commented on 8.July 2010

Any possible eay to achive this with XP


Bill

Commented on 8.July 2010

ExtendGlass.html[2/16/2014 3:14:34 PM]


WPF Tutorial | Glass Windows

Do this work with DOS 1.1


Bob 2

Commented on 8.July 2010

Oh.. Jill.. is doing it.. mad poor guy


Bob 2

Commented on 27.October 2010

thats stolen from another site... faggot


QWERT

Commented on 3.March 2011

Thanks. very nice paper


Simba

Commented on 10.May 2011

There are a couple of lines of code missing in your example to make it perfect.

Evans

First:

public const int WM_DWMCOMPOSITIONCHANGED = 0x031E;

needs to be declared in the GlassHelper class.

Secondly:

In order for the WndProc procedure to run in WPF the following lines should be added to the windows
load event since WPF windows don't have a hWnd

HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);

source.AddHook(new HwndSourceHook(WndProc));

Otherwise the example is a nice one.

Name

E-Mail (optional)
Comment

Post Comment

ExtendGlass.html[2/16/2014 3:14:34 PM]


WPF Tutorial | Jumplists

Home
    Windows 7
    Jumplists Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to add Tasks to Jumplists in .NET 4.0 and Windows 7
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation
Introduction
Multimedia
Windows 7 provides a new taskbar feature for applications called jumplists. They appear, when you right-click on a application icon in
Documents the taskbar. By default you see a list of recent files opened and two entries to launch and detach the application.
Windows 7 .NET 4.0 provides a managed API that allows you to easily manipulate the entries in the jumplist.
Interoperability

Performance How to add a Task to the Jumplist


Expression Blend A jumplist is nothing more than a categorizes list of links to files that can be launched by the user. The links are called JumpTasks.
Tools
They can be parametrized with a title, description, icon, filepath and command line arguments.

In the following sample I create a new JumpList and add a task to the list that launches the sample application, but with a
UI Automation
command line argument. If the application is launched with an argument, it shows a MessageBox instead.

 
public partial class App : Application
{

Jumplists.html[2/16/2014 3:15:10 PM]


WPF Tutorial | Jumplists
protected override void OnStartup(StartupEventArgs e)
{
 
if (e.Args.Count() > 0)
{
MessageBox.Show("You have the latest version.");
Shutdown();
}
 
JumpTask task = new JumpTask
{
Title = "Check for Updates",
Arguments = "/update",
Description = "Cheks for Software Updates",
CustomCategory = "Actions",
IconResourcePath = Assembly.GetEntryAssembly().CodeBase,
ApplicationPath = Assembly.GetEntryAssembly().CodeBase
};
 
JumpList jumpList = new JumpList();
jumpList.JumpItems.Add(task);
jumpList.ShowFrequentCategory = false;
jumpList.ShowRecentCategory = false;
 
JumpList.SetJumpList(Application.Current, jumpList);
}
}
 
 

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2009-12-16 13:50:20


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 27.January 2010

is there only work in WPF?

Andira
how about Form?
Muttakim

Commented on 27.January 2010

is there only work in WPF?

Andira
how about Form?
Muttakim

Commented on 28.March 2010

It does also work in Windows Forms under a .NET 4.x and Win7 environment.
Mario Fraiß

Jumplists.html[2/16/2014 3:15:10 PM]


WPF Tutorial | Jumplists

Commented on 17.May 2010

Any way you can implement this to standard run time?

Martin

e.g. Have a command on the list (Red) that changes the background color of the form to Red?

Commented on 25.June 2010

can jumplist support custom event like just calling a method inside the owner
K

Name

E-Mail (optional)

Comment

Post Comment

Jumplists.html[2/16/2014 3:15:10 PM]


WPF Tutorial | Top 11 WPF Performance Tips

Home
    Performance
    Top 11 WPF Performance Tips Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Top 11 WPF Performance Tips
Custom Controls
Windows Presentation Foundation provides a very confortable way to develop rich user experiences. A drop shadow for example can
Layout added by inserting two simple lines of XML. But this simplicity can also mislead us to overuse them. This leads to performance issues.
The following tipps may help you to avoid or fix them.
Input

Data Binding
1. Dispatch expensive calls either within the UI thread with a lower DispatcherPriority by calling
Styling Dispatcher.BeginInvoke() or to a background thread by using a BackgroundWorker to keep the UI responsive.
Localization 2. Fix binding errors because they consume a lot of time, trying to resolve the path error, including searching for attached
properties. You can find them by looking for System.Windows.Data Error in the Visual Studio output log.
Interaction
3. Reduce the number of visuals by removing unneeded elements, combining layout panels and simplifying templates. This
Resources keeps the memory footprint small and improves the rendering performance.
4. Prevent Software Rendering. The use of transparent windows by setting AllowsTransparency to true or using old
2D Graphics
BitmapEffects can cause WPF to render the UI in software on Windows XP, which is much slower.
3D Graphics 5. Load resources when needed. Even thow it's the most comfortable way to merge all resources on application level it can
also cost performance by loading all resources at startup. A better approach is to load only often used resources and load the
Animation
other on view level.
Multimedia 6. Virtualize lists and views by using a VirtualizingStackPanel as ItemsPanel for lists. This only creates the visible
elements at load time. All other elements are lazy created when they get visible. Be aware that grouping or
Documents
CanContextScrol="True" prevents virtualization!
Windows 7 7. Enable Container Recycling. Virtualization brings a lot of performance improvements, but the containers will be disposed
Interoperability and re created, this is the default. But you can gain more performance by recycle containers by setting
VirtualizingStackPanel.VirtualizationMode="Recycling"
Performance
8. Freeze Freezables by calling Freeze() in code or PresentationOptions:Freeze="true" in XAML. This reduces
Expression Blend memory consumption and improves performance, because the system don't need to monitor for changes.
9. Disable Assembly localization if you don't need it. By using the [NeutralResourcesLanguageAttribute]. This
Tools
prevents an expensive lookup for satelite assemblies
UI Automation 10. Lower the framerate of animations by setting Storyboard.DesiredFrameRate to lower the CPU load. The default is
60 frames/second
11. Use StreamGeometries instead of PathGeometries if possible to draw complex 2D geometries, because they are much
more efficient and consume less memory.

10PerformanceTips.html[2/16/2014 3:15:25 PM]


WPF Tutorial | Top 11 WPF Performance Tips

Other articles about WPF performance


Improve application startup performance (Jossef Goldberg)

WPF Performance Tools


There are two interesting tools to trace your WPF application and narrow down performance leaks:

Snoop to check the number of visuals.


WPF Performance Suite to trace events and rendering time

  ► Tutorial   ► Learn Quick Books   ► Basics   ► Coding Learning

Last modified: 2011-03-02 17:32:34


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 11.May 2010

haha, almost there.. 49 to go


Rafa

Commented on 11.May 2010

Good Tips, dont write anything and always fast:))

oyeeee

Commented on 13.May 2010

Come on I'm waiting for the other 49 dude!!!!!!!


Brad.A

Commented on 14.May 2010

I look also for other 49 :)


Alexej

Commented on 16.May 2010

After you couldn't find 50 performance tips, you switched to a Top 10.

Roman
And now you're showing us a Top 9 ??

It would be better if you completed articles before posting them.

Besides that, useful information. Thanks!

Commented on 17.May 2010

Hi Roman,

Christian Moser
sorry for that. I added the missing 10th :-)

Commented on 18.May 2010

10PerformanceTips.html[2/16/2014 3:15:25 PM]


WPF Tutorial | Top 11 WPF Performance Tips

Great article, keep up the good work, your blog is a very informative and useful.
Ben Dover

Commented on 18.May 2010

Thanks for the tips mate, they're useful for me. I'm just starting a migration from Winforms to WPF.
Alejandro Nagy
On a side note, is sad to see what jealousy does to people...why don't they try to make a great
resource page like this one...then we'll see if they find 50 tips to share.

Commented on 21.May 2010

Some of nice tips.Thanks

Radenko Zec

Commented on 21.May 2010

Moore's Law implies that we should be able to ignore these performance issues. Unfortunately, there's
Marv Luse
Marv's Law: the resource requirements of Windows doubles every 15 or 20 minutes. Thaaaat's
wwwhhhyyy duuuh-buuu-yoooo peeeee eeeeef iiiiiiiisssss sssssoooooooo ssssssslloooooowwwww.

Commented on 21.May 2010

What about WPFPerf Suite for .Net 4.0?


RaeNO

Commented on 23.August 2010

How much cash .. mind sharing..lol..J/K.. keep up the hunting for us. you should call this WPF HUB
Mysticool

Commented on 7.September 2010

It works in Silverlight

Denis
12. x:Name only the elements you need to use from code-behind or want to "Control2Control" bind.

Commented on 18.November 2010

Great post!

Elad Katz

Just one comment though - Freezable object are for thread safety and not as u said..

http://blogs.microsoft.co.il/blogs/eladkatz/archive/2010/11/18/freezable-objects-it-s-about-thread-
safety.aspx

Commented on 30.November 2010

Good Tutorial for beginners. Thanks a lot Christian...


Jeya

Commented on 9.December 2010

Nilesh Good Stuff, man!


Makwana

Commented on 8.January 2011

Which will be better ?...to write code in c# or xaml to get good peformance
Tinoy Malayil

Commented on 16.February 2011

hi

10PerformanceTips.html[2/16/2014 3:15:25 PM]


WPF Tutorial | Top 11 WPF Performance Tips
jai

Commented on 2.March 2011

Tip 5: What is the word Thow? Pretty sure this doesnt even exist in the americanized incorrect version
Darren Bruce
of the english language

Commented on 14.March 2011

small correction in 6:

Musab Ahmed
ScrollViewer.CanContentScroll="False" instead of CanContextScrol="True"
Ali

Commented on 23.March 2011

Tip 4: &quot;setting AllowsTransparency to true can cause WPF to render the UI in software on
len
Windows XP, which is much slower.&quot; -- Is it still true for now? Is there any fix for it?

Commented on 21.July 2011

I don't know what these guys are talking about !


Bean

Commented on 21.July 2011

I don't know what these guys are talking about !


Bean

Commented on 27.August 2011

good
adee.

Commented on 3.September 2011

Great Stuff man..


Lakmal

Name

E-Mail (optional)

Comment

Post Comment

10PerformanceTips.html[2/16/2014 3:15:25 PM]


WPF Tutorial | Addins

Home
    Expression Blend
    Addins Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Expression Blend 2 AddIns
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7
Introduction
Interoperability Expression Blend has an add-in model that allows developers to write add-ins to extend its functionality. Unfortunately this is mainly
unknown to most users of blend. A prominent example is the intellisense addin for blend.
Performance

Expression Blend
Popular Addins
Tools
Unify - AddIn Manager for Expression Blend
UI Automation
PluginManager - Loads all addins from a directory
Colorful - Access color palettes from Adobe Kuler
Blendsense - Brings IntelliSense to Expression Blend

BlendAddins.html[2/16/2014 3:16:01 PM]


WPF Tutorial | Addins

How to Load and Run an AddIn


To load and run an addin into expression, just pass a command parameter -addin followed the name of the add-in dll. You don't
need any registration of plug-ins, but you can load only one addin on the same time. To get over this limitation you can use an add-
in manager that dynamically loads multiple plugins even without restarting the tool.

C:\Program Files\Microsoft Expression\Blend 2\Blend.exe /addin:NameOfTheAddin.dll


 

  ► Tutorial   ► Blender   ► Pro Engineer   ► 3D Image


Last modified: 2009-10-13 12:22:50


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 13.October 2009

Twain, stopping the transaction and extracting a confession, then leaving Twain bound in Pseudoderm. ,
Mr.Carrot67

Commented on 22.October 2009

This total includes 52 new measures. ,


SouthWind83

Commented on 23.October 2009

Therefore we agree with Dr. ,


Faggot97

Name

E-Mail (optional)

Comment

Post Comment

BlendAddins.html[2/16/2014 3:16:01 PM]


WPF Tutorial | How to Import Photoshop Files

Home
    Expression Blend
    How to Import Photoshop Files Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to Import Photoshop Files into WPF
Custom Controls

Layout
Introduction
Input
In a WPF project you often have to deal with assets that are created by a designer. They are often part of Adobe Illustrator or
Data Binding Photoshop files. There are two ways to achieve this goal. You can

Styling Directly Import Photoshop Files in Expression Blend


Localization
This is the most simple approach if you have Expression Blend 3. Drawbacks are, that you can only import vector shapes as
Path elements. If you want to add these shapes into the resources, you have to manually extract the geometries.
Interaction
Import Photoshop Files in Expression Design and Export to XAML
Resources
This approach requires Expression Design to be installed but works already with Version 2.0. The workflow is a bit more
complex, but you can choose if you want to export your shapes as Paths or Geometries.
2D Graphics

3D Graphics
Preparing the Photoshop File
Animation
If you create graphical assets that should be integrated to a WPF project you should think of the following rules to make the import
Multimedia
easier.
Documents
Combine multiple vector shapes to one shape
Windows 7 Don't use layer effects, because they are mostly ignored by the converter
Interoperability Set the color dept to 8Bit. Higher color depts cause errors on import

Performance

Expression Blend
Directly Import Photoshop Files in Expression Blend
Tools The following tutorial explains how to directly import an Adobe Photoshop file into WPF.

UI Automation 1. Start Expression Blend and open an empty WPF project

ImportFromPhotoshop.html[2/16/2014 3:16:16 PM]


WPF Tutorial | How to Import Photoshop Files

2. Choose "Import Adobe Photoshop File..." from the "File" menu.

3. Select the file you want to import to Blend


4. Check or uncheck the layers you want to import and click [OK].

5. Blend imports the file now. Each layer will create a new Image or Path element. The images will automatically be added to

a separate folder in your project.

ImportFromPhotoshop.html[2/16/2014 3:16:16 PM]


WPF Tutorial | How to Import Photoshop Files

How to convert Path to Resources

To convert imported Path objects to Geometry objects that can be consumes as resources you have to do the following steps:

1. Copy the content of the "Data" attribute to the clipboard

2. Create a StreamGeometry object and paste the content between the opening and closing tag. Give the geometry a
unique key.

Import Photoshop Files in Expression Design and Export to XAML


The following tutorial explains how to import Adobe Photoshop Files in Expression Design and Export to XAML to use it in Expression
Blend.

1. Start Expression Blend and open the desired Photoshop File


2. Check or uncheck the layers you want to import and click [OK].

3. Open the Options Dialog in "Edit->Options->Clipboard(XAML)" and choose if you want to export shapes as Canvas or
Resource Dictionaries.

ImportFromPhotoshop.html[2/16/2014 3:16:16 PM]


WPF Tutorial | How to Import Photoshop Files

4. Select the objects you want to export and choose "Copy XAML" in the Edit menu.

5. Go back to Expression Blend andpPaste the XAML snippet from the clipboard.

ImportFromPhotoshop.html[2/16/2014 3:16:16 PM]


WPF Tutorial | How to Import Photoshop Files

  ► Tutorial   ► Adobe Photoshop 6   ► Photoshop CS4   ► Photoshop Brushes

Last modified: 2009-09-15 21:30:08


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 15.September 2009

Again, your tutorials are imbued with visuals making it extremely easy to read and understand. Excellent
Jeffrey
work!

Commented on 24.March 2010

Hi You are amazing keep your good work...


Pandiarajan

Commented on 22.July 2010

nice work
satish v

Commented on 23.August 2010

Its funny that you guys find my articles so helpful considering I just copy and pasted random shit from
Christian
other random sites that I found. Its all good though because those google ads are making me cash!!!

Commented on 10.November 2010

You really just copyed this haha?


Jake

Commented on 8.February 2011

hi mose, whether you copied it or not, that does not matter, but it is helping others or not, that matters,
anoop
and of course these are very helpful.

Name

E-Mail (optional)

Comment

Post Comment

ImportFromPhotoshop.html[2/16/2014 3:16:16 PM]


WPF Tutorial | Prototyping with SketchFlow

Home
    Expression Blend
    Prototyping with SketchFlow Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Prototyping with Expression Blend 3 + SketchFlow
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents Introduction
Windows 7
Software is getting even more complex, interactive and dynamic. It's nearly impossible, for a developer to find the best solution at first
Interoperability time. If you start writing code without testing the concept, you can throw away a lot of valuable time by following a suboptimal
approach.
Performance

Expression Blend
The idea of SketchFlow
Tools
The idea of SketchFlow is to combine the simpleness and informality of sketching with paper and pencil with the dynamic of
UI Automation
interactive prototypes. Most prototyping tools focus on creating high quality assets, but the main purpose of most prototypes is to
proove the interaction design of your software and not to impress your management.

To address this point the Team of SketchFlow has created special styles for controls that look as if they where drawn by pencil. This
focus the discussion on real interaction problems instead of discussing about details like colors or fonts and suggests that the screen

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow
design is still changeable with a small effort.

Workspace setup
Expression Blend 3 includes a workspace management feature that allows you to hide all panels you don't need to sketch your
prototype. You can save your settings by choosing "Save as new Workspace" from the "Windows" menu.

Create a new SketchFlow project


In Blend 3.0 you find two new project types to create prototypes for WPF or Silverlight.

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

Create and connect screens

Drop sketchy controls onto screens


In the asset library you will find a new category "SketchFlow". It contains a section called "Sketch Styles". It contains special styles for
most WPF or Silverlight controls that look like they are drawn by hand.

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

Extract common parts to component screens


If you have a part that is used on multiple screens, like a navigation or a login box, you can extract it to a component screen. This
screen can be referenced on multiple screens. If you modify the component screen, the changes are reflected to all screens.

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

Wire-up navigation

Add sample data


A prototype needs to provide sample data to make it understandable. In flash prototypes, sample data is often just a bunch of
textblocks and images. In SketchFlow we have a sample data generator, that creates real data sources that can be bound to lists and
elements as real data. Selection, scrolling and sorting all works.

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

In the Data panel you find a database icon. It allows you to create a new sample data source.

Give the sample data source a name and specify the scope of visibility. This can be only on this screen or within the whole prototype.
This can be useful, if you want to use the same demo data on multiple screens.

After creating the demo data source, you can define how a data record should look like. You can add properties or most popular
types and choose from a variety of sample data types. There are URL's, e-mail adresses, bild text (lorem ipsum), images, and much
mure...

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

Add assets from Photoshop, Illustrator or PowerPoint

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

Test prototype and get feedback

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

Generate prototype documentation


When you have finished your prototype, you can generate a design documentation by a single click. It includes the a table of content,
the flow map and screenshots of all screens and components. It's not meant to use it as a complete documentation, but it's a good
start to build on.

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

  ► Tutorial   ► Photoshop Brushes   ► Tablet Drawing   ► Photoshop Vector

Last modified: 2009-11-05 22:54:08


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 5.February 2010

Excellent work...

Mukesh

Commented on 28.March 2010

That's an impressive way to get out something for customers, i am always influenced by the RAD
Atul Raina
tools.Awesome introduction, that is a building block for my quest to explore WPF

Commented on 12.April 2010

and now in german ...


321213

Commented on 11.May 2010

atul very good work , i like the way of guiding.


kumar...

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

Commented on 20.May 2010

Okay, you've convinced me to use SketchFlow to debug my WPF app interaction/behavior first, then
Jason
beautify it. Seems really easy, and fast, and it can still look sophisticate by leveraging Photoshop files!
Thanks for a great site, it's very useful!

Commented on 24.May 2010

Okay, you've convinced me to use SketchFlow to debug my WPF app interaction/behavior first, then
jasonb
beautify it. Seems really easy, and fast, and it can still look sophisticate by leveraging Photoshop files!
Thanks for a great site, it's very useful!

Commented on 8.June 2010

Nice approach to explain sketchflow with wpf


Anindita

Commented on 21.October 2010

Another good one - this may sway me from Balsamiq Mockups!


Battered...

Commented on 27.April 2011

Thank you - this was very helpful in getting me started. Clear, concise and just enough info to point me in
Shazzas
the right direction.

Commented on 13.May 2011

Orale Carlitos! Me parece una buena introduccion a esto. Me parece que es una buena manera de darle
El Gran...
un pepinillo al cliente.

Commented on 16.June 2011

Very nice post! I'm loving WPF more and more because of you! Thank you very much!
Genesis

Commented on 23.July 2011

Great post - got me started with SketchFlow in no time at all.

SilverBlend

Commented on 3.August 2011

What is the difference between the applications created by WPF and WPF Sketchflow?? I know sketchflow
sanchayita
is used to match the hand made prototype.. But what I wanted to know is, except that, we can create
everything in WPF sketch application which we can in WPF application?? Please clarify if I am wrong..
Please give your views on the applications created by WPF and WPF Sketchflow and what are the
differences.. Thanks..

Name

E-Mail (optional)

Comment

Post Comment

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | Prototyping with SketchFlow

SketchFlow.html[2/16/2014 3:16:29 PM]


WPF Tutorial | XAML Converters

Home
    Tools
    XAML Converters Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
XAML Converters
Custom Controls
The following list shows converters developed by the WPF community to convert different formats to XAML or vice versa.
Layout
Adobe Illustrator XAML Export Plugin
Input
Adobe Photoshop to XAML Converter
Data Binding Blender XAML Export Plugin
Lightwave XAML Export Plugin
Styling
Visio XAML Export
Localization 3D Studio Max to XAML Converter
Maya to XAML Converter
Interaction
Flash to XAML Converter
Resources SVG to XAML Converter
2D Graphics WMF/EMF to XAML Converter

3D Graphics

Animation

Multimedia

Documents Last modified: 2009-02-28 22:19:15


Copyright (c) by Christian Moser, 2011.

Windows 7

Interoperability

Performance  Comments on this article

Expression Blend Show all comments

Tools
Commented on 25.July 2009

UI Automation Photoshop link is no longer valid. Would be great if anyone knew of one to post it.
Austin

Commented on 27.July 2009

Hi Austin,

XAMLConverters.html[2/16/2014 3:17:06 PM]


WPF Tutorial | XAML Converters
Christian
you can use Expression Blend 3 to convert Photoshop Files into XAML. You can download a 60 days
Moser
trial version from here: www.microsoft.com/expression

Commented on 30.October 2009

There is a tool that converts Adobe Flash/SWF files to Silverlight/XAML - SilverX (http://www.silverx.net).
Roman
Maybe this link can be useful too..

Commented on 14.June 2010

i want to convert my wpf application to asp.net.

shuchita
kindly help me.
saxena

Commented on 11.July 2010

Shuchita,

Mike Strobel

WPF and ASP.NET are fundamentally different platforms. One runs on the client, one runs on the
server. One is stateful, the other is stateless. I would definitely not recommend trying to "port" a WPF
application to ASP.NET. The opportunities for code reuse at the UX level are virtually nonexistent. If
you do not require the application to run on a server, but merely in a browser, you may want to
consider porting the application to Silverlight instead. The conversion may still be a long process, but it
would be somewhat less painful, and probably easier than rewriting the application from scratch for
ASP.NET.

Cheers,

Mike

Commented on 23.July 2010

Please post a link to a XAML to SVG converter.


Julian

Commented on 31.July 2010

I am writing a document in MS Word 2007 and using Expression Blend and Design to do the graphics.
Robert Smith
Is there a "XAML to WordML" converter available? Or do you have any other suggestions?

Thanks,

R. Smith

Columbia, MD.

Commented on 3.August 2010

Hi, Good Information


Jayesh...

Commented on 19.April 2011

Hi,
Sethu
i have a help document of my software in word2007 which contains tables, images , words and some
symbols included. Now need a convertor to convert to xbap application help me to find it.

Thanx,

Sethu

Mumbai

XAMLConverters.html[2/16/2014 3:17:06 PM]


WPF Tutorial | XAML Converters

Commented on 19.June 2011

I wrote the Google Sketchup Xaml Exporter - an addin for Google Sketchup (Rubi script, actually) that
Itai Bar-Haim
exports scenes to Xaml. http://itaibh.blogspot.com/2009/12/xaml-exporter-for-sketchup-round-2.html

Name

E-Mail (optional)

Comment

Post Comment

XAMLConverters.html[2/16/2014 3:17:06 PM]


WPF Tutorial | Graphical Designers

Home
    Tools
    Graphical Designers Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Graphical WPF Designers
Custom Controls
Mobiform Aurora XAML Designer
Layout
ZAM 3D (3D XAML Tool by Electric Rain)
Input

Data Binding
  ► Tutorial   ► App UI Design   ► User Interface   ► Interface Design
Styling

Localization
Last modified: 2010-06-03 11:11:19
Interaction Copyright (c) by Christian Moser, 2011.

Resources

2D Graphics
 Comments on this article
3D Graphics
Show all comments
Animation
Commented on 5.June 2009
Multimedia
Nice, but try to include the more porpular ms products eg. Expression Blend etc.
Documents Abdulmajeed

Windows 7 Commented on 20.August 2009

Interoperability The link to Mobiform Aurora does not work.


Bjoneskc
Performance
Commented on 20.August 2009
Expression Blend
Below is the latest link:

Tools Bjoneskc

http://www.dotnetuidevelopment.com/aurora.htm

UI Automation

Commented on 16.March 2010

Cool, We Need Some Templates and Themes...


Leon Ramesh

GraphicalDesigners.html[2/16/2014 3:17:27 PM]


WPF Tutorial | Graphical Designers

Name

E-Mail (optional)

Comment

Post Comment

GraphicalDesigners.html[2/16/2014 3:17:27 PM]


WPF Tutorial | Utilities

Home
    Tools
    Utilities Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Debugging and Development Utilities
Custom Controls
WPF Inspector - visual debugging for WPF
Layout
XAML Power Toys
Input Mole for Visual Studio
Snoop - A collection of visual debugging helpers
Data Binding
StyleSnooper - View styles of controls
Styling Show me the template
ProtoXAML - A stencil UI skin for WPF paper prototypes
Localization
Crack.NET - A runtime debugging and scripting tool to access internals of .NET applications
Interaction Pistachio - Resource Visualizer
XAML Type explorer
Resources

2D Graphics

3D Graphics

Animation

Multimedia Last modified: 2010-06-29 22:21:44


Copyright (c) by Christian Moser, 2011.

Documents

Windows 7

 Comments on this article


Interoperability

Performance Show all comments

Expression Blend Commented on 2.May 2010

Tools excellent tutorial to start and learn thanks


nilesh
UI Automation
Commented on 8.July 2010

Any Theaming Tool...????


Bob

DnDUtilities.html[2/16/2014 3:18:10 PM]


WPF Tutorial | Utilities

Commented on 13.August 2010

Hari Very nice article. And cute web theam


Haran

Commented on 28.April 2011

Is there any Free Online Book .for Web Application through WPF.
Kuldeep

Name

E-Mail (optional)

Comment

Post Comment

DnDUtilities.html[2/16/2014 3:18:10 PM]


WPF Tutorial | XAML Editors

Home
    Tools
    XAML Editors Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
XAML Editors
Custom Controls
XAML Editor (by Lary Bell)
Layout
XAML PadX (extended)
Input XAML Hack
KaXaml
Data Binding

Styling

Localization   ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Interaction

Resources Last modified: 2010-07-15 15:45:08


Copyright (c) by Christian Moser, 2011.

2D Graphics

3D Graphics
 Comments on this article
Animation

Multimedia Show all comments

Documents Commented on 8.March 2010

Windows 7 wat is xaml???i gota google it i guess!!!


fahad
Interoperability
Commented on 28.May 2010
Performance
@fahad Take a look under Fundamentals > XAML on this website. ^^
Ben
Expression Blend

Tools Commented on 21.November 2010

UI Automation
Rakesh Dora , plz maintain sanctity of the forum and behave urself.
Ramesh

Commented on 31.August 2011

hello, i work as a Business Analyst, but i have the task to prototype using an external IDE by Mobiform's
mumshad

XAMLEditors.html[2/16/2014 3:18:24 PM]


WPF Tutorial | XAML Editors
aurora in xaml, am looking on how navigation can be implemented using only xaml. Such a good resource
and i will study WPF too

Thanks In Advance

Commented on 31.August 2011

hello, i work as a Business Analyst, but i have the task to prototype using an external IDE by Mobiform's
mumshad
aurora in xaml, am looking on how navigation can be implemented using only xaml. Such a good resource
and i will study WPF too

Thanks In Advance

Name

E-Mail (optional)

Comment

Post Comment

XAMLEditors.html[2/16/2014 3:18:24 PM]


WPF Tutorial | Control Templates

Home
    Styling
    Control Templates Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Control Templates
Custom Controls

Layout
Introduction
Input
Controls in WPF are separated into logic, that defines the states, events and properties and template, that defines the visual
Data Binding appearance of the control. The wireup between the logic and the template is done by DataBinding.

Styling Each control has a default template. This gives the control a basic appearance. The default template is typically shipped together with
the control and available for all common windows themes. It is by convention wrapped into a style, that is identified by value of the
Localization
DefaultStyleKey property that every control has.
Interaction
The template is defined by a dependency property called Template. By setting this property to another instance of a control
Resources template, you can completely replace the appearance (visual tree) of a control.

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

The control template is often included in a style that contains other property settings. The following code sample shows a simple
control template for a button with an ellipse shape.

templates-2.html[2/16/2014 3:18:59 PM]


WPF Tutorial | Control Templates
 
<Style x:Key="DialogButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Ellipse Fill="{TemplateBinding Background}"
Stroke="{TemplateBinding BorderBrush}"/>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
 
 
 
<Button Style="{StaticResource DialogButtonStyle}" />
 
 

A Button without and with a custom control template

ContentPresenter
When you create a custom control template and you want to define a placeholder that renders the content, you can use the
ContentPresenter. By default it adds the content of the Content property to the visual tree of the template. To display the
content of another property you can set the ContentSource to the name of the property you like.

Triggers

{RelativeSource TemplatedParent} not working in DataTriggers of a ControlTemplate

If you want to bind to a property of a property on your control like Data.IsLoaded you cannot use a normal Trigger, since it does
not support this notation, you have to use a DataTrigger.

But when you are using a DataTrigger, with {RelativeSource TemplatedParent} it will not work. The reason is, that
TemplatedParent can only be used within the ControlTemplate. It is not working in the Trigger section. You have to use the
{RelativeSource Self} instead.

templates-2.html[2/16/2014 3:18:59 PM]


WPF Tutorial | Control Templates

What if a Binding working or a Setter is not applied when using a control template
There is something you need to know when setting a value of an element within a control template: The value does have a lower
precendence as the local value! So if you are setting the local value in the constructor of the contained element, you cannot override
it within the controltemplate. But if you use the element directly in your view, it will work. So be aware of this behavior!.


Here you can find more information about DependencyProperty value precendence: Dependency Property Value Precedence

  ► Tutorial   ► Dreamweaver CS4   ► WebPage Templates   ► Design Templates

Last modified: 2010-04-27 16:48:31


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 29.July 2010

you people I really not getting why you are congrat this guy ! This site is uglying explaning WPF ! just
ouais
good to run away and find real explanation from programmer !

Commented on 3.September 2010

seems really interesting thanks for your efforts to make this material available for us
i

Commented on 3.September 2010

Nice one
Arjun

Commented on 12.October 2010

Fill="{TemplateBinding Background}" Stroke="{TemplateBinding BorderBrush}"

Asha.MP
in the above properties we can specify the colors also, what is the meaning of TemplateBinding in the
above property??

Commented on 19.October 2010

nice...

siva

Commented on 22.November 2010

Great Article , thanks for your efforts :)


Praveen

Commented on 24.January 2011

very nice.
bala

Commented on 21.February 2011

good one

templates-2.html[2/16/2014 3:18:59 PM]


WPF Tutorial | Control Templates
sri

Commented on 24.March 2011

if u dont mind , can u thrown some light on visualstatemanager as well.. ?


prassanth

Commented on 17.April 2011

Many many thanks for this article...


Ankit

Commented on 21.April 2011

Gurpreet Great explaination ! thanks


Singh

Commented on 23.April 2011

Thanks buddy good articles

Tejas

Commented on 26.April 2011

Janynne Great explanation and i liked the figure, so clear!


Gomes

Commented on 4.May 2011

These comments are laughably fake.


anon

Commented on 18.May 2011

Thanks, Nice explanation


Paras

Commented on 24.May 2011

Great. And where do i have to write the style-tag down, now?


Anon

Commented on 1.June 2011

So Clear very nicely explained


Mayank

Commented on 14.June 2011

please show, how to focus and enable the elliptic button


jones

Commented on 9.July 2011

So Clear nice
bm

Commented on 12.July 2011

Thank you! This tutorial is awesome!


Dmitry

Commented on 13.July 2011

I want to create Template for TextBox. How can I aceess RelativeSource TEXT property.
Alibaba

templates-2.html[2/16/2014 3:18:59 PM]


WPF Tutorial | Control Templates

Commented on 18.July 2011

@Alibaba: If I am understanding you correctly, you would not use RelativeSource to bind to the text
stigma
property. You would use &quot;{TemplateBinding Text}&quot;. For example:

&lt;TextBlock Text=&quot;{TemplateBinding Text}&quot;/&gt;

Using a TextBox inside a TextBox ControlTemplate, however, I have found to be very unhelpful. Try
using: &lt;ScrollViewer x:Name=&quot;PART_ContentHost&quot;/&gt; If you name the ScrollViewer
exactly as I have here, the text will be bound to it. No other work required.

Commented on 22.August 2011

Life Saver :)
Ziad

Commented on 5.September 2011

Machi awesome article...Thanks !!!


johnson

Commented on 20.September 2011

Viva linux!!
Gonzalo

Name

E-Mail (optional)

Comment

Post Comment

templates-2.html[2/16/2014 3:18:59 PM]


WPF Tutorial | Apply a DataTemplate

Home
    Controls
    ListBox
    Apply a DataTemplate Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to apply a DataTemplate to a ListBox
Custom Controls

Layout
Introducing DataTemplates
Input
All controls deriving from ItemsControl have a DataTemplate that specifies how an object bound to an item is presented to the
Data Binding user. The default template renders a single line of text per item - as we know a listbox from HTML or WinForms.

Styling But WPF allows us to put whatever we like into a DataTemplate. If we want to display a list of customers we can provide a data
template that shows an image for each customer next to its name and age. In my opinion this is one of the most powerful features in
Localization
WPF.
Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools
In the following steps I will show you how to create such an DataTemplate
UI Automation

Bind the data to the ListBox


We bind a list of employees to the listbox. Because the listbox does not know anything about our employee class, it calls the

ListBoxDataTemplate.html[2/16/2014 3:19:14 PM]


WPF Tutorial | Apply a DataTemplate
ToString() method. The result is not yet very pleasing.
 
<Grid x:Name="LayoutRoot">
<ListBox Margin="10" ItemsSource="{Binding}"/>
</Grid>
 
 

Override the ToString() method to improve the display


What we do next is to overriding the ToString() method to provide some useful information instead of just the type name. But a string
is not really what we call a cool user experience.
 
public override string ToString()
{
return string.Format("{0} {1} ({2}), {3})",
Firstname, Lastname, Age, Role);
}
 
 

Create a DataTemplate
The ultimate flexibility is to create your own DataTemplate. A data template can consist of multiple controls like images, textblocks,
etc. It han have a flexible width and height, background color and shape. There are no limits for your creativity.

An easy way to create a data template is to use Expression Blend. Open the context menu of your list box and choose "Edit Other
Templates" -> "Edit Generated Items" -> "Create Empty".

ListBoxDataTemplate.html[2/16/2014 3:19:14 PM]


WPF Tutorial | Apply a DataTemplate

Blend will ask you to specify a name for your DataTemplate because it will define it in the resources of either the Application, the
current document of an external resource dictionary. The name you specify is the key for the resource dictionary.

After you press OK, you will be in the editor to design the data template. The item data (in our sample an employee) is set to the
DataContext, so you can easily access all properties of the employee by using databinding.

 
<DataTemplate x:Key="EmployeeDataTemplate">
<Grid>
<Grid.ColumnDefinitions>

ListBoxDataTemplate.html[2/16/2014 3:19:14 PM]


WPF Tutorial | Apply a DataTemplate
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Margin="5" BorderBrush="Black" BorderThickness="1">
<Image Source="{Binding Path=Image}" Stretch="Fill" Width="50" Height="50" />
</Border>
<StackPanel Grid.Column="1" Margin="5">
<StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold" >
<TextBlock Text="{Binding Path=Firstname, FallbackValue=FirstName}" />
<TextBlock Text="{Binding Path=Lastname, FallbackValue=LastName}"
Padding="3,0,0,0"/>
</StackPanel>
<TextBlock Text="{Binding Path=Age, FallbackValue=Age}" />
<TextBlock Text="{Binding Path=Role, FallbackValue=Role}" />
</StackPanel>
</Grid>
</DataTemplate>
 
 
 

  ► Tutorial   ► Learn Quick Books   ► Data Networking   ► Coding Learning

Last modified: 2008-10-24 01:06:02


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 10.June 2009

I had some problem trying to get this one to work.


bax

Commented on 17.June 2009

I suspect people are having problems with this example because there's no data to bind to... Maybe
ThomC
a code snippet that populates a collection when the form loads. This would also reinforce data
binding concepts and implementation.

Commented on 9.September 2009

useless.
Avishek

Commented on 26.September 2009

This is funny. I've spent several days searching how to bind data to a listbox. Of all the brilliant
Frank
authors on the web, not one has the same solution and none make sense.

Commented on 28.September 2009

I saw all of these examples in MSDN before,but the good things is that if it's the first time you want to
Mahmood
learn that concept ,it will be more easier to start from here.

ListBoxDataTemplate.html[2/16/2014 3:19:14 PM]


WPF Tutorial | Apply a DataTemplate

Commented on 30.September 2009

\"We bind a list of employees to the listbox\"... WHERE?


Bob

Commented on 8.November 2009

I have understood DataTemplate, but how it is used as itemSource of ListBox?

Yogesh
Also how it is binded to Employee objects?

Commented on 10.November 2009

How do you bind the data with the listbox itself? I tried
macias
ItemsSource={Binding Path=Employees}
assuming there is such property as Employees but it does not work (for me at least).

Commented on 19.December 2009

A good example to create a data template for a beginner. But how to set the template to the listbox.
Mukil

Commented on 5.January 2010

'An easy way to create a data template is to use Expression Blend. Open the context menu of your
W
list box and choose "Edit Other Templates" -> "Edit Generated Items" -> "Create Empty".'

!!!Can't find the menuitem of Edit Other Templates!!!

Commented on 13.January 2010

W. Are you right clicking? The example isn't to teach you how to bind data. He has other examples
Andy
for that. What is left out of the example is telling your itemscontrol to use your DataTemplate. You
can bind by setting the ItemSource of the ItemsControl.

I generally bind in the code... if x:Name="MyControl" then in the code MyControl.ItemsSource where
ItemsSource is an Observable collection of the object you want to use.

Commented on 23.January 2010

Very nice example!! Keep it up!


BoboSurabaya

Commented on 4.March 2010

I couldnt get it to work until my class in the Observable collection had public access properties (inside
Ken
of directly accessing "public string Name" for example). When I did that it worked. Hope this helps.

Commented on 9.June 2010

Its a awsome and helpful tutorial Thanks for helping


nomy

Commented on 16.June 2010

would there be any sample for same..? though it looks like gud sample but may be difficult for a
crazycopboy
beginner..

Commented on 19.August 2010

How would you bind the data template to XML in C#?


WPFed

ListBoxDataTemplate.html[2/16/2014 3:19:14 PM]


WPF Tutorial | Apply a DataTemplate

Commented on 19.August 2010

How would you bind the data template to XML in C#?


WPFed

Commented on 24.September 2010

sirs, this is what i wants. can you please send all the code to me please
IndianBoy

Commented on 21.October 2010

it's good and so helpfull thx


umut

Commented on 2.January 2011

Sir,would you please paste the complete version of source code here instead of some code snippet. I
Justin
think that would be more helpful. Thanks!

Commented on 20.January 2011

yep. paste the complete Source Code! Please!


WPFNoob

Commented on 6.July 2011

And how to apply a DataTemplate to a ListBox? - like you promised in the Headline. Would be nice if
Beginner
you could paste the complete Source Code :)

Commented on 11.July 2011

Thanks for the stuff and great explanation.


Ishkhan

Commented on 12.August 2011

very good
babu

Commented on 2.September 2011

Very Nice Explanation.


NagarjunaReddy

Name

E-Mail (optional)

Comment

Post Comment

ListBoxDataTemplate.html[2/16/2014 3:19:14 PM]


WPF Tutorial | Strech an Item

Home
    Controls
    ListBox
    Strech an Item Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to strech an WPF ListBox Item to span the whole width
Custom Controls
If you create a data template with a right-aligned element (like the age in our exmple), it only spans over the needed width, because
Layout the content of a listbox is left-aligned by default.
Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

3D Graphics
This is the DataTemplate I created for this example.
Animation
 
Multimedia <Style TargetType="ListBox" x:Key="strechedItemStyle">
<Setter Property="ItemTemplate">
Documents
<Setter.Value>
Windows 7 <DataTemplate>
<Grid Background="#330000FF">
Interoperability <Grid.ColumnDefinitions>
Performance
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
Expression Blend </Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" HorizontalAlignment="Left"
Tools
Grid.Column="0"/>
UI Automation <TextBlock Text="{Binding Age}" HorizontalAlignment="Right"
Grid.Column="1"/>
</Grid>
</DataTemplate>
</Setter.Value>

StrechListBoxItem.html[2/16/2014 3:19:51 PM]


WPF Tutorial | Strech an Item
</Setter>
</Style>
 
 
To make the listbox item span the whole width of the listbox you need to set the HorizontalContentAlignment property to
Stretch.

This is the way to set it directly on the listbox element:

 
<ListBox x:Name="listBox" Margin="20"
Style="{StaticResource strechedItemStyle}"
HorizontalContentAlignment="Stretch" />
 
 
If you want to set this property within a style you can do it with the following lines of code

 
<Style TargetType="ListBox" x:Key="strechedItemStyle">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Adobe Photoshop

Last modified: 2009-11-17 13:24:58


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 1.June 2009

I understand the concept of styles with this, but I didnt understand how you made the number to come to
Se122
the left, and the text to stay on left.

Commented on 5.August 2009

Hi,
Patrick
How can i apply animation for a selected listitem? Such as the zone out the selected itme.

StrechListBoxItem.html[2/16/2014 3:19:51 PM]


WPF Tutorial | Strech an Item

Commented on 9.April 2010

Se122,

Garry
He was able to accomplish that by setting up a grid in the datatemplate with 2 columns. 1 Column for the
text aligned to the left and one column for the numbers aligned to the right.

<Grid Background="#330000FF">

<Grid.ColumnDefinitions>

<ColumnDefinition Width="Auto" />

<ColumnDefinition Width="*" />

</Grid.ColumnDefinitions>

<TextBlock Text="{Binding Name}" HorizontalAlignment="Left" Grid.Column="0"/>

<TextBlock Text="{Binding Age}" HorizontalAlignment="Right" Grid.Column="1"/>

</Grid>

Commented on 22.September 2010

Hi I followed the example on this page to get right aligned in a text box, but having troubles

someone

Note, I'm printing it as a FlowDocument

It's right aligned in Blend

It's right aligned when I print preview

It's right aligned when I print to XPS

It's LEFT aligned when I print to printer

I also see if I do a .show() first, then print, it prints right aligned. But it's left aligned if I print directly

Any ideas?

Name

E-Mail (optional)
Comment

Post Comment

StrechListBoxItem.html[2/16/2014 3:19:51 PM]


WPF Tutorial | Selected Item Background

Home
    Controls
    ListBox
    Selected Item Background Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Change the Background of a selected ListBox Item
Custom Controls
If you select an item in a listbox it gets the default selection color (usually blue) as background. Even if you specify a custom data
Layout template.
The reason is that the blue background (or gray if the control is not focussed) is drawn outside of the data template. So you
have no chance to override it from within the data template.
Input

Data Binding

Styling

Localization

Interaction

Resources

2D Graphics

The color used to draw the blue and gray background are system colors. So the easiest way to get rid of these backgrounds is to
3D Graphics
locally override the highlight and control brushes of the system colors.
Animation
The best way to do this is to create a style for the listbox. Place the style in the resources of a parent element. For e.g.
Multimedia Window.Resources

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

 
<Style x:Key="myListboxStyle">
<Style.Resources>

ListBoxSelectionBackground.html[2/16/2014 3:20:06 PM]


WPF Tutorial | Selected Item Background
<!-- Background of selected item when focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red"
/>
<!-- Background of selected item when not focussed -->
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Green"
/>
</Style.Resources>
</Style>
 
 

The following XAML snippet shows how to apply the style to the listbox.

 
<Grid x:Name="LayoutRoot">
<ListBox Style="{StaticResource myListboxStyle}" />
</Grid>
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Brushes   ► Photoshop Editing

Last modified: 2008-10-24 01:37:10


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 5.August 2009

On registering a mobile casino account you'd better have a computer at hand in addition to your
DSCN2258
phone but it is not obligatory in some cases.;

Commented on 29.September 2009

NICE! pure zammel!


Berti

Commented on 2.November 2009

Great solution. This is exactly waht i was lookin 4


LearnerOfXAML

Commented on 21.January 2010

Hey thanks a lot!! Its d perfect solution....


Shrads

Commented on 4.March 2010

Thanks a lot! I spent 1+ days trying to solve this, thought it was hidden style overriding my setting,
Larry
never thought of system colors!

Commented on 27.April 2010

Indeed neat. Thank you.

kpatil
To add more, If you want to change the TextColor use

ListBoxSelectionBackground.html[2/16/2014 3:20:06 PM]


WPF Tutorial | Selected Item Background
HighlightTextBrushKey

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />

Commented on 17.May 2010

Thanks a lot for your great stuff! I like this solution, too:

iris
http://wildermuth.com/2007/04/17/Changing_the_Selected_Style_of_ListBox_s_in_XAML

Commented on 6.July 2010

That is a neat solution! avoid re-templating overkill is awesome...


Hj

Commented on 13.July 2010

Is not an 'Elegant' solution because it replaces a system color key, so that change will be applied to all
Homer
controls that use this key...

Commented on 2.September 2010

@Homer:

Neztnerol
No, it only replaces the system color key for the control that uses the style template "myListboxStyle"

So it only applies to the control that adds the property:

Style="{StaticResource myListboxStyle}"

Commented on 15.September 2010

nice Explanation...in kannada to say "Tumba Chenagide":-)


das

Commented on 25.November 2010

I,

Gally
I'm looking for an other solution on windows phone 7 with Silverlight because <Style.Resources>
doesn't exist.

Have you any idea ?

Commented on 9.December 2010

Hello tutorial Admin...


Haribabu
You have written tutorial well but y can't you extend topic some more briefly... For example in mouse
input why can't you explain mouse events at least few

Commented on 11.December 2010

Just what I was looking for and so neatly done. Thanks Christian
Karin

Commented on 4.January 2011

Thanks. I love you :)


bizon

Commented on 19.January 2011

GRANDE!!!!
Alfredo...

Commented on 11.February 2011

Exactly what I was looking for! New to WPF and your site is the main site when I need to out figure
Mustafa

ListBoxSelectionBackground.html[2/16/2014 3:20:06 PM]


WPF Tutorial | Selected Item Background
out something with WPF

Commented on 24.February 2011

thanks. very helpful :)


avmfree

Commented on 2.March 2011

Thanks for the solution. It works great in this form, but I would like to use a custom color (instead the
smafuboj
wpf's built-in colors).

I tried this, but it doesn't work:

...

<!-- Background of selected item when focussed -->

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" >

<SolidColorBrush.Color R="0" G="154" B="213" />

</SolidColorBrush>

...

Is there any way to solve my problem? Thanks for help!

Commented on 13.April 2011

Simple and nice solutions!

Armando
Rocha
Thanks

Commented on 18.April 2011

Aditya Kiran...
Hey Thanks alot.. your site is damn good. it is very helpful.

Commented on 13.June 2011

I'm trying top apply the same thing on a ListView but it doesn't work.

Frank
I've heard it could be due to the fact that this isn't supported on Windows 7. Any truth to this ? Is
there another way to accomplish this ?

Commented on 26.July 2011

Thanks for your solutions :)


DoNguyen

Commented on 8.August 2011

Thank for your help. thanks


Hamidreza...

Commented on 27.September 2011

I was tryin to diasble selection of node in treeview.. tis helped me to achieve it by givin d highlight
HK
colour brush same as d background colour of my window.. thanks alot..

Name

E-Mail (optional)

Comment

ListBoxSelectionBackground.html[2/16/2014 3:20:06 PM]


WPF Tutorial | Selected Item Background

Post Comment

ListBoxSelectionBackground.html[2/16/2014 3:20:06 PM]


WPF Tutorial | Layout of Items

Home
    Controls
    ListBox
    Layout of Items Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Change the arrangement of items in a listbox
Custom Controls
All WPF controls deriving from ItemsControl provide an ItemsPanel property that allows you to replace the internal layout
Layout panel that arranges the items.
Input

Data Binding Horizontal


Styling
We override the ItemsPanel property and set it to a StackPanel layout manager with an orientation set to Horizontal. We
Localization use an VirtualizingStackPanel that works just like a normal StackPanel, except that is does only create the items that are
visible. If you scroll it automatically creates the new items that become visible and recycles the hidden.
Interaction

Resources

2D Graphics

3D Graphics

 
Animation
<ListBox>
Multimedia <ListBox.ItemsPanel>
<ItemsPanelTemplate>
Documents
<VirtualizingStackPanel Orientation="Horizontal" />
Windows 7 </ItemsPanelTemplate>
</ListBox.ItemsPanel>
Interoperability </ListBox>
 
Performance
 
Expression Blend
Wrapped
Tools
Using a WrapPanel to layout the items row by row is a bit more complex. Since the layout panel is wrapped by a
UI Automation
ScrollContentPresenter (as seen by the scrolbar of the exmple above) the available width is infinite. So the WrapPanel does
not see a reason to wrap to a new line.

What we need to do is to set the width of the warp panel to the ActualWidth if the internal ScrollContentPresenter. The
ScrollContentPresenter can be found by using the FindAncestor mode of the relative source extension.

ListBoxItemsArrange.html[2/16/2014 3:20:41 PM]


WPF Tutorial | Layout of Items

 
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Brushes

Last modified: 2009-10-07 14:32:12


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 25.January 2010

very simple to study by using this tips


eldose

Commented on 10.August 2010

good
janu

Commented on 25.August 2010

Very good, very very good!


hero

Commented on 22.November 2010

Dear Christian,

Adnan

I've tried this and it is working fine, but the time whenever i use any theme its not working (all items in listbox
appearing in vertical order), and when i remove the theme reference it is working fine.

I am using

<Application x:Class="Application"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

StartupUri="Login.xaml">

ListBoxItemsArrange.html[2/16/2014 3:20:41 PM]


WPF Tutorial | Layout of Items
<Application.Resources>

<ResourceDictionary Source="Themes/ExpressionLight.xaml" />

</Application.Resources>

</Application>

Commented on 3.January 2011

in 10 years of computing I have never commented on a technical article that I've read. This is the first, and it's
dave
only because it's genius. Thanks for being concise, and getting this way overcomplicated thing to work.

Name

E-Mail (optional)

Comment

Post Comment

ListBoxItemsArrange.html[2/16/2014 3:20:41 PM]


WPF Tutorial | Remove the Icon

Home
    Controls
    Window
    Remove the Icon Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
How to remove the icon of a WPF window
Custom Controls

Layout

Input

Data Binding

Styling

Localization

Interaction

Resources Unfortumately WPF does not provide any function to remove the icon of a window. One solution could be setting the icon to a
transparent icon. But this way the extra space between the window border and title remains.
2D Graphics
The better approach is to use a function provided by the Win32 API to remove the icon.
3D Graphics
 
Animation public partial class Window1 : Window
{
Multimedia
public Window1()
Documents {
InitializeComponent();
Windows 7 }
 
Interoperability
protected override void OnSourceInitialized(EventArgs e)
Performance {
IconHelper.RemoveIcon(this);
Expression Blend
}
Tools }
 
UI Automation  
 
public static class IconHelper
{
[DllImport("user32.dll")]

RemoveIcon.html[2/16/2014 3:20:53 PM]


WPF Tutorial | Remove the Icon
static extern int GetWindowLong(IntPtr hwnd, int index);
 
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
 
[DllImport("user32.dll")]
static extern bool SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter,
int x, int y, int width, int height, uint flags);
 
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hwnd, uint msg,
IntPtr wParam, IntPtr lParam);
 
const int GWL_EXSTYLE = -20;
const int WS_EX_DLGMODALFRAME = 0x0001;
const int SWP_NOSIZE = 0x0001;
const int SWP_NOMOVE = 0x0002;
const int SWP_NOZORDER = 0x0004;
const int SWP_FRAMECHANGED = 0x0020;
const uint WM_SETICON = 0x0080;
 
public static void RemoveIcon(Window window)
{
// Get this window's handle
IntPtr hwnd = new WindowInteropHelper(window).Handle;
 
// Change the extended window style to not show a window icon
int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_DLGMODALFRAME);
 
// Update the window's non-client area to reflect the changes
SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE |
SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
 
}
 
 

  ► Tutorial   ► Photoshop CS4   ► Photoshop Action   ► Photoshop Vector

Last modified: 0000-00-00 00:00:00


Copyright (c) by Christian Moser, 2011.

 Comments on this article

Show all comments

Commented on 23.March 2009

This was a good article. I hat going into the Win32 stuff so having a class like this means I can add to
Ketan
any future projects that require this functionality.

Thanks

RemoveIcon.html[2/16/2014 3:20:53 PM]


WPF Tutorial | Remove the Icon

Commented on 27.May 2009

Does it work in Windows versions less then Vista (XP, Server 2003)?
konstantin

Commented on 28.May 2009

I was trying to do this on XP Professional and it did not appear to work. Maybe I am missing something
Steve
(I do that on occasion).

I still get the default windows icon on my window but no longer get the context menu (that shows
Restore, Move, Size, Minimize, etc). I basically copied the code from here and used it in my application.
Nothing was changed and I double checked that I did not get a copy/paste error.

Commented on 8.June 2009

does not work in Xp.


Alex

Commented on 25.July 2009

SendMessage(hwnd, WM_SETICON, IntPtr.Zero, IntPtr.Zero) can remove the Icon from XP


Kevinclcn

Commented on 26.February 2010

itz awesome....but one problem i am facing is ,when i run the exe of project the default icon comes at
shradz
that place...can u help me for this

Commented on 26.February 2010

itz awesome....but one problem i am facing is ,when i run the exe of project the default icon comes at
shradz
that place...can u help me for this

Commented on 27.February 2010

Thank you for this great trick!

RomanK
Do you by chance also know how to remove the window title?

Commented on 5.March 2010

Excellent approach, exactly what i was looking for!


Caian

Commented on 6.April 2010

Another way to do it:

SomeOne
<Window x:Class="Transparent.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Icon="transparent.png"

Title="Window1" SizeToContent="WidthAndHeight">

Commented on 27.September 2010

The SendMessage solution does not remove the icon in VisualStudio 2010 in XP.
Gorkster

Commented on 27.September 2010

RemoveIcon.html[2/16/2014 3:20:53 PM]


WPF Tutorial | Remove the Icon
The "transparent.png" approach does not remove the space reserved for the icon even thought there is
Gorkster
no icon showing.

Commented on 6.October 2010

a trick of lazy:

Max

WindowStyle="ToolWindow"

Commented on 23.February 2011

SetWindowLong by itself doesn't work on Vista x64 (VS2010) on remote desktop.

midspace
Requires both SetWindowLong and SendMessage.

Commented on 5.August 2011

re: WindowStyle=&quot;ToolWindow&quot;

Jesse
Yes, that will remove the icon, but it also changes the style of the buttons in the caption bar.
Chisholm

Name

E-Mail (optional)

Comment

Post Comment

RemoveIcon.html[2/16/2014 3:20:53 PM]


WPF Tutorial | Localization using Satelite Assemblies

Home
    Localization
    Localization using Satelite Assemblies Share... Feed About Christian Moser
   
     

Home

WPF Inspector

Getting started

Fundamentals

User Experience

Patterns

Controls
Localization using Satelite Assemblies
Custom Controls
MSDN Documentation about Localization

Layout
  ► Tutorial   ► Pro Engineer   ► Pro E CAD   ► Sketch Pro
Input

Data Binding
Last modified: 2010-02-25 07:57:28
Styling
Copyright (c) by Christian Moser, 2011.

Localization

Interaction

Resources

2D Graphics

3D Graphics

Animation

Multimedia

Documents

Windows 7

Interoperability

Performance

Expression Blend

Tools

UI Automation

LocalizationUsingSateliteAssemblies.html[2/16/2014 3:21:08 PM]

You might also like