Professional Documents
Culture Documents
Index of Locally Available Projects:: WPF Tutorials 2
Index of Locally Available Projects:: WPF Tutorials 2
© 2008 Xavier Roche & other contributors - Web Design: Leto Kauler.
Home
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
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.
Introduction to WPF
Home
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
Grid Panel
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;"><StackPanel<span style="color: #800000;">></span></span></span>
<span style="color:
#800000;"><span style="color: #800000;"><TextBlock</span> <span style="color: #ff0000;">Margin</span>=
<span style="color: #0000ff;">"20"</span><span style="color: #800000;">></span></span>Welcome
to the World of XAML<span style="color: #800000;"><span style="color: #800000;"></TextBlock<span
style="color: #800000;">></span></span></span>
<span style="color: #800000;"><span style="color:
#800000;"><Button</span> <span style="color: #ff0000;">Margin</span>=<span style="color:
#0000ff;">"10"</span> <span style="color: #ff0000;">HorizontalAlignment</span>=<span style="color:
#0000ff;">"Right"</span><span style="color: #800000;">></span></span>OK<span style="color:
#800000;"><span style="color: #800000;"></Button<span style="color: #800000;">></span></span></span>
<span style="color: #800000;"><span style="color: #800000;"></StackPanel<span style="color: #800000;">>
</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;">(</span><span style="color:
#000000;">)</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;">(</span><span style="color:
#000000;">)</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;">(</span><span style="color:
#FF0000;">10</span><span style="color: #000000;">)</span>;
textBlock.<span style="color:
#0000FF;">Text</span> <span style="color: #008000;">=</span> <span style="color: #666666;">"Welcome to
the World of XAML"</span>;
stackPanel.<span style="color: #0000FF;">Children</span>.<span style="color:
#0000FF;">Add</span><span style="color: #000000;">(</span>textBlock<span style="color: #000000;">)
</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;">(</span><span style="color:
#000000;">)</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;">(</span><span style="color:
#FF0000;">20</span><span style="color: #000000;">)</span>;
button.<span style="color:
#0000FF;">Content</span> <span style="color: #008000;">=</span> <span style="color:
#666666;">"OK"</span>;
stackPanel.<span style="color: #0000FF;">Children</span>.<span style="color:
#0000FF;">Add</span><span style="color: #000000;">(</span>button<span style="color: #000000;">)
</span>;
</pre></div><p>As you can see is the XAML version much shorter and clearer to read. And that's the power
of XAMLs expressiveness.</p>
<h2>Properties as Elements</h2>
<p>Properties are normally written inline as known
from XML <code><Button Content="OK" /></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;"><Button<span style="color: #800000;">></span></span></span>
<span style="color: #800000;">
<span style="color: #800000;"><Button</span>.Content<span style="color: #800000;">></span></span>
<span
style="color: #800000;"><span style="color: #800000;"><Image</span> <span style="color:
#ff0000;">Source</span>=<span style="color: #0000ff;">"Images/OK.png"</span> <span style="color:
#ff0000;">Width</span>=<span style="color: #0000ff;">"50"</span> <span style="color:
#ff0000;">Height</span>=<span style="color: #0000ff;">"50"</span> <span style="color:
#800000;">/></span></span>
<span style="color: #800000;"><span style="color:
#800000;"></Button</span>.Content<span style="color: #800000;">></span></span>
<span style="color:
#800000;"><span style="color: #800000;"></Button<span style="color: #800000;">></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;"><Border</span> <span style="color:
#ff0000;">BorderBrush</span>=<span style="color: #0000ff;">"Blue"</span> <span style="color:
#ff0000;">BorderThickness</span>=<span style="color: #0000ff;">"0,10"</span><span style="color:
#800000;">></span></span>
<span style="color: #800000;"><span style="color: #800000;"></Border<span
style="color: #800000;">></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;"><TextBox</span> <span style="color: #ff0000;">x:Name</span>=<span
style="color: #0000ff;">"textBox"</span><span style="color: #800000;">/></span></span>
<span
style="color: #800000;"><span style="color: #800000;"><Label</span> <span style="color:
#ff0000;">Content</span>=<span style="color: #0000ff;">"{Binding Text, ElementName=textBox}"
</span><span style="color: #800000;">/></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;"><Window</span> <span style="color: #ff0000;">xmlns</span>=<span
style="color: #0000ff;">"http://schemas.microsoft.com/winfx/2006/xaml/presentation"</span></span>
<span style="color: #800000;"><span style="color: #ff0000;">xmlns:x</span>=<span style="color:
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;">{</span> <span style="color: #008000;">#region
Dll imports</span> <span style="color: #000000;">[</span>DllImport<span style="color: #000000;">(
</span><span style="color: #666666;">"user32.dll"</span>, CharSet <span style="color: #008000;">=
</span> CharSet.<span style="color: #0600FF; font-weight: bold;">Auto</span><span style="color: #000000;">)
</span><span style="color: #000000;">]</span> <span style="color: #000000;">[
</span>ResourceExposure<span style="color: #000000;">(</span>ResourceScope.<span style="color:
#0000FF;">None</span><span style="color: #000000;">)</span><span style="color: #000000;">]</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;">(</span>HandleRef hmonitor,
<span style="color: #000000;">[</span><span style="color: #0600FF; font-weight: bold;">In</span>, <span
style="color: #0600FF; font-weight: bold;">Out</span><span style="color: #000000;">]</span>MonitorInfoEx
info<span style="color: #000000;">)</span>; <span style="color: #000000;">[</span>DllImport<span
style="color: #000000;">(</span><span style="color: #666666;">"user32.dll"</span>, ExactSpelling
<span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span
style="color: #000000;">)</span><span style="color: #000000;">]</span> <span style="color:
#000000;">[</span>ResourceExposure<span style="color: #000000;">(</span>ResourceScope.<span
style="color: #0000FF;">None</span><span style="color: #000000;">)</span><span style="color:
#000000;">]</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;">(
</span>HandleRef hdc, IntPtr rcClip, MonitorEnumProc lpfnEnum, IntPtr dwData<span style="color:
#000000;">)</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;">(</span>IntPtr monitor, IntPtr hdc, IntPtr lprcMonitor, IntPtr
lParam<span style="color: #000000;">)</span>; <span style="color: #000000;">[
</span>StructLayout<span style="color: #000000;">(</span>LayoutKind.<span style="color:
#0000FF;">Sequential</span><span style="color: #000000;">)</span><span style="color: #000000;">]
</span> <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #2b91af; font-weight:
bold;">struct</span> Rect <span style="color: #000000;">{</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;">}</span> <span style="color:
#000000;">[</span>StructLayout<span style="color: #000000;">(</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;">)</span><span style="color: #000000;">]</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #2b91af; font-weight:
bold;">class</span> MonitorInfoEx <span style="color: #000000;">{</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;">(</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;">(</span>MonitorInfoEx<span style="color:
#000000;">)</span><span style="color: #000000;">)</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;">(</span><span style="color: #000000;">)
</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;">(</span><span style="color:
#000000;">)</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;">[</span>MarshalAs<span style="color: #000000;">(</span>UnmanagedType.<span
style="color: #0000FF;">ByValArray</span>, SizeConst <span style="color: #008000;">=</span> <span style="color:
#FF0000;">32</span><span style="color: #000000;">)</span><span style="color: #000000;">]</span>
<span style="color: #0600FF; font-weight: bold;">internal</span> <span style="color: #2b91af; font-weight:
bold;">char</span><span style="color: #000000;">[</span><span style="color: #000000;">]</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;">[</span><span style="color:
#FF0000;">32</span><span style="color: #000000;">]</span>;
<span style="color: #000000;">}</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;">(</span><span style="color: #0600FF; font-
weight: bold;">null</span>, IntPtr.<span style="color: #0000FF;">Zero</span><span style="color: #000000;">)
</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;">{</span> get; <span style="color: #0600FF;
font-weight: bold;">private</span> set; <span style="color: #000000;">}</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;">{</span> get; <span style="color: #0600FF; font-weight: bold;">private</span> set; <span
style="color: #000000;">}</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span
style="color: #2b91af; font-weight: bold;">string</span> Name <span style="color: #000000;">{</span> get;
<span style="color: #0600FF; font-weight: bold;">private</span> set; <span style="color: #000000;">}</span>
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;">{</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;">(</span><span style="color: #2b91af;
font-weight: bold;">string</span> propertyName<span style="color: #000000;">)</span>
<span style="color:
#000000;">{</span>
<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color:
#000000;">(</span>PropertyChanged <span style="color: #008000;">!=</span> <span style="color: #0600FF;
font-weight: bold;">null</span><span style="color: #000000;">)</span>
<span style="color: #000000;">{
</span>
PropertyChanged<span style="color: #000000;">(</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;">(
</span>propertyName<span style="color: #000000;">)</span><span style="color: #000000;">)</span>;
<span style="color: #000000;">}</span>
<span style="color: #000000;">}</span>
<span style="color:
#000000;">}</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;">{</span>
<span
style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight:
bold;">readonly</span> List<span style="color: #008000;"><</span>ITrackable<span style="color:
#008000;">></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;"><</span>ITrackable<span style="color:
#008000;">></span><span style="color: #000000;">(</span><span style="color: #000000;">)</span>;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #2b91af; font-weight:
bold;">bool</span> HasChanges
<span style="color: #000000;">{</span>
get <span style="color:
#000000;">{</span> <span style="color: #0600FF; font-weight: bold;">return</span> _trackableItems.<span
style="color: #0000FF;">Any</span><span style="color: #000000;">(</span>i <span style="color:
#008000;">=></span> i.<span style="color: #0000FF;">HasChanges</span><span style="color: #000000;">)
</span>; <span style="color: #000000;">}</span>
<span style="color: #000000;">}</span>
<span
style="color: #0600FF; font-weight: bold;">public</span> IModificationTracker ModificationTracker <span
style="color: #000000;">{</span> get; set; <span style="color: #000000;">}</span>
<span style="color:
#0600FF; font-weight: bold;">protected</span> TrackableValue<span style="color: #008000;"><</span>T<span
style="color: #008000;">></span> RegisterTrackableValue<span style="color: #008000;"><</span>T<span
style="color: #008000;">></span><span style="color: #000000;">(</span><span style="color: #2b91af; font-
weight: bold;">string</span> propertyName, T defaultValue <span style="color: #008000;">=</span> <span
</span>
<span style="color: #0600FF; font-weight: bold;">public</span> T <span style="color: #0600FF; font-weight:
bold;">this</span><span style="color: #000000;">[</span><span style="color: #2b91af; font-weight:
bold;">int</span> index<span style="color: #000000;">]</span>
<span style="color: #000000;">{</span>
get <span style="color: #000000;">{</span> <span style="color: #0600FF; font-weight: bold;">return</span>
_list<span style="color: #000000;">[</span>index<span style="color: #000000;">]</span>; <span
style="color: #000000;">}</span>
set
<span style="color: #000000;">{</span>
var oldItem <span
style="color: #008000;">=</span> _list<span style="color: #000000;">[</span>index<span style="color:
#000000;">]</span>;
_modifyCallback<span style="color: #000000;">(</span><span style="color:
#000000;">(</span><span style="color: #000000;">)</span> <span style="color: #008000;">=></span>
<span style="color: #000000;">{</span>
_list<span style="color: #000000;">[</span>index<span
style="color: #000000;">]</span> <span style="color: #008000;">=</span> value;
ItemAdded.<span
style="color: #0000FF;">Notify</span><span style="color: #000000;">(</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;"><
</span>T<span style="color: #008000;">></span><span style="color: #000000;">(</span>value<span
style="color: #000000;">)</span><span style="color: #000000;">)</span>;
<span style="color:
#000000;">}</span>, <span style="color: #000000;">(</span><span style="color: #000000;">)
</span> <span style="color: #008000;">=></span>
<span style="color: #000000;">{</span>
_list<span
style="color: #000000;">[</span>index<span style="color: #000000;">]</span> <span style="color:
#008000;">=</span> oldItem;
ItemRemoved.<span style="color: #0000FF;">Notify</span><span style="color:
#000000;">(</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;"><</span>T<span style="color: #008000;">>
</span><span style="color: #000000;">(</span>oldItem<span style="color: #000000;">)</span><span
style="color: #000000;">)</span>;
<span style="color: #000000;">}</span>, OnCollectionModified<span
style="color: #000000;">)</span>;
<span style="color: #000000;">}</span>
<span style="color:
#000000;">}</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color:
#0600FF; font-weight: bold;">void</span> OnCollectionModified<span style="color: #000000;">(</span><span
style="color: #000000;">)</span>
<span style="color: #000000;">{</span>
CollectionChanged.<span
style="color: #0000FF;">Notify</span><span style="color: #000000;">(</span><span style="color: #0600FF;
font-weight: bold;">this</span>, EventArgs.<span style="color: #0000FF;">Empty</span><span style="color:
#000000;">)</span>; <span style="color: #000000;">}</span>
<span style="color: #000000;">}
</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
<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;">(</span><span style="color: #000000;">)
</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;">(</span><span style="color: #000000;">)</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;">(</span><span style="color:
#000000;">)</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;">(</span><span style="color:
#FF0000;">1</span>,GridUnitType.<span style="color: #0000FF;">Star</span><span style="color: #000000;">)
</span>;
grid.<span style="color: #0000FF;">ColumnDefinitions</span>.<span style="color: #0000FF;">Add</span>
<span style="color: #000000;">(</span>col1<span style="color: #000000;">)</span>;
grid.<span
style="color: #0000FF;">ColumnDefinitions</span>.<span style="color: #0000FF;">Add</span><span style="color:
#000000;">(</span>col2<span style="color: #000000;">)</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;"><Button<span style="color: #800000;">></span></span></span>
<span style="color: #800000;"><span style="color: #800000;"><StackPanel</span> <span style="color:
#ff0000;">Orientation</span>=<span style="color: #0000ff;">"Horizontal"</span><span style="color:
#800000;">></span></span>
<span style="color: #800000;"><span style="color: #800000;"><Image</span>
<span style="color: #ff0000;">Source</span>=<span style="color: #0000ff;">"speaker.png"</span> <span
style="color: #ff0000;">Stretch</span>=<span style="color: #0000ff;">"Uniform"</span><span
style="color: #800000;">/></span></span>
<span style="color: #800000;"><span style="color:
#800000;"><TextBlock</span> <span style="color: #ff0000;">Text</span>=<span style="color:
#0000ff;">"Play Sound"</span> <span style="color: #800000;">/></span></span>
<span style="color:
#800000;"><span style="color: #800000;"></StackPanel<span style="color: #800000;">></span></span>
</span>
<span style="color: #800000;"><span style="color: #800000;"></Button<span style="color:
#800000;">></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
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;"><RichTextBox<span
style="color: #800000;">></span></span></span> <span style="color: #800000;"><span style="color:
#800000;"><RichTextBox</span>.ContextMenu<span style="color: #800000;">></span></span> <span
style="color: #800000;"><span style="color: #800000;"><ContextMenu<span style="color: #800000;">></span>
</span></span> <span style="color: #800000;"><span style="color: #800000;"><MenuItem</span> <span
style="color: #ff0000;">Command</span>=<span style="color: #0000ff;">"Cut"</span><span
style="color: #800000;">></span></span> <span style="color: #800000;"><span style="color:
#800000;"><MenuItem</span>.Icon<span style="color: #800000;">></span></span> <span style="color:
#800000;"><span style="color: #800000;"><Image</span> <span style="color: #ff0000;">Source</span>=<span
style="color: #0000ff;">"Images/cut.png"</span> <span style="color: #800000;">/></span></span>
<span style="color: #800000;"><span style="color: #800000;"></MenuItem</span>.Icon<span style="color:
#800000;">></span></span> <span style="color: #800000;"><span style="color: #800000;"></MenuItem<span
style="color: #800000;">></span></span></span> <span style="color: #800000;"><span style="color:
#800000;"><MenuItem</span> <span style="color: #ff0000;">Command</span>=<span style="color:
#0000ff;">"Copy"</span><span style="color: #800000;">></span></span> <span style="color:
#800000;"><span style="color: #800000;"><MenuItem</span>.Icon<span style="color: #800000;">></span>
</span> <span style="color: #800000;"><span style="color: #800000;"><Image</span> <span style="color:
#ff0000;">Source</span>=<span style="color: #0000ff;">"Images/copy.png"</span> <span style="color:
#800000;">/></span></span> <span style="color: #800000;"><span style="color:
#800000;"></MenuItem</span>.Icon<span style="color: #800000;">></span></span> <span style="color:
#800000;"><span style="color: #800000;"></MenuItem<span style="color: #800000;">></span></span></span>
<span style="color: #800000;"><span style="color: #800000;"><MenuItem</span> <span style="color:
#ff0000;">Command</span>=<span style="color: #0000ff;">"Paste"</span><span style="color:
#800000;">></span></span> <span style="color: #800000;"><span style="color:
#800000;"><MenuItem</span>.Icon<span style="color: #800000;">></span></span> <span style="color:
#800000;"><span style="color: #800000;"><Image</span> <span style="color: #ff0000;">Source</span>=<span
style="color: #0000ff;">"Images/paste.png"</span> <span style="color: #800000;">/></span></span>
<span style="color: #800000;"><span style="color: #800000;"></MenuItem</span>.Icon<span style="color:
#800000;">></span></span> <span style="color: #800000;"><span style="color: #800000;"></MenuItem<span
style="color: #800000;">></span></span></span> <span style="color: #800000;"><span style="color:
#800000;"></ContextMenu<span style="color: #800000;">></span></span></span> <span style="color:
#800000;"><span style="color: #800000;"></RichTextBox</span>.ContextMenu<span style="color:
#800000;">></span></span> <span style="color: #800000;"><span style="color:
#800000;"></RichTextBox<span style="color: #800000;">></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;"><RichTextBox</span> <span style="color: #ff0000;">IsEnabled</span>=<span
style="color: #0000ff;">"False"</span> ContextMenuService.<span style="color:
#ff0000;">ShowOnDisabled</span>=<span style="color: #0000ff;">"True"</span><span style="color:
#800000;">></span></span> <span style="color: #800000;"><span style="color:
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;"><Window</span> </span>
<span style="color: #800000;"> xmlns:d =<span style="color:
#0000ff;">"http://schemas.microsoft.com/expression/blend/2008"</span></span>
<span style="color:
#800000;"> <span style="color: #ff0000;">xmlns:mc</span>=<span style="color:
#0000ff;">"http://schemas.openxmlformats.org/markup-compatibility/2006"</span></span>
<span
style="color: #800000;"> <span style="color: #ff0000;">mc:Ignorable</span>=<span style="color:
#0000ff;">"d"</span> <span style="color: #800000;">/></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;"><UserControl</span></span>
<span style="color: #800000;"> <span
style="color: #ff0000;">xmlns</span>=<span style="color: #0000ff;">"http://schemas.microsoft.com/..."
</span></span>
<span style="color: #800000;"> <span style="color: #ff0000;">xmlns:x</span>=<span style="color:
#0000ff;">"http://schemas.microsoft.com/winfx/2006/xaml"</span></span>
<span style="color:
#800000;"> <span style="color: #ff0000;">d:DesignWidth</span>=<span style="color: #0000ff;">"640"
</span> <span style="color: #ff0000;">d:DesignHeight</span>=<span style="color: #0000ff;">"480"
</span> <span style="color: #800000;">></span></span>
<span style="color: #800000;"><span style="color:
#800000;"><UserControl</span> <span style="color: #800000;">/></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;"><Border</span> <span style="color: #ff0000;">Height</span>=<span style="color:
#0000ff;">"250"</span> <span style="color: #ff0000;">Width</span>=<span style="color:
#0000ff;">"160"</span> <span style="color: #ff0000;">d:LayoutOverrides</span>=<span style="color:
#0000ff;">"Width, Height"</span> <span style="color: #800000;">></span></span>
<span
style="color: #800000;"><span style="color: #800000;"></Border<span style="color: #800000;">></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
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
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
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
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
Hi
Thank U :)
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.
Camila
he forgot
syed farooq...
hi.. i m new i want to learn wpf and wcf with in 2 week ... is it possible
mukund
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.
soumya
plz sir help me.thnx
from...
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.
nice
vipin
Zhang Zhi very cool... this article is useful.. thank you for sharing... hope to see next article soon.
Ren
Great job!!
walter
:)
kata
it's really useful! but hopefully you can finish the remaining days we really appreciate your help! God
chao
bless you!
Ankita its really good training.. i want to learn wcf also sir..
Johnson
Name
E-Mail (optional)
Comment
Post Comment
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.
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.
very good...
pragati
It really gud :)
Haritha
Good one
bhanu
Thank you..I think its more helpful for the beginners in WPF
sreejith
there is an sql error on the tutorials like user desing process...please fix it out asap...thankyou
kartik
Thanks Sir, thank you so much for all notes and example of WPF.........
Sweta Pandey
Dhruvangini
Thanks
that is wonderful
BoYu Gao
Cool.. been looking for a nice WPF intro and this is by far the best and coolest... thanks
RobertS
really...good one
Roshan
Good one
Nithya
What a intro?????
Mukesh
very useful
pradeep
Name
E-Mail (optional)
Post Comment
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:
Multimedia
Frozen columns
Headers Visibility
Documents How to template autogenerated columns
Windows 7
Interoperability
<DataGrid ItemsSource="{Binding Customers}" />
<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Image}" />
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" />
<DataGrid ItemsSource="{Binding Customers}"
CanUserReorderColumns="True" CanUserResizeColumns="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>
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.
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>
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
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}" />
Good tutorial...
Sreekumar
Shail
Let�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.
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
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..
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
which control equel datagridview in window app to wpf vs2010 reason i new in wpf vs 2010
patel...
eshao
THe datagrid don't have the "command" property like button,
if u use the datagrid wirh mvvm, u must do lot extra work that will hit u out off earth.
eshao
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?
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?
How did you made the View Source option disable on this page?
Dev
What should I do if I want another node directioned from the costumers class?
Luis
e.g.
public class Customer : INotifyPropertyChanged
.
}
//where:
thanks
What should I do if I want another node directioned from the costumers class?
Luis
e.g.
public class Customer : INotifyPropertyChanged
.
}
//where:
thanks
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.
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
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.
Would anyone know, how to make the grids look a bit more stylish as opposed to the normal windows
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?
Ruslan
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?
Ruslan
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?
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...
Name
E-Mail (optional)
Comment
Post Comment
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
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.
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Adobe Photoshop
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,,,,,,,,,,
Anjum
Its too esy to understand
Thanks !
Anjum
Its too easy to understand .
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.
oooooo
grege
you Are very smart
good demo
ankit
worst example i didn't find need to demonstrate here. we can do in windows form only...
siva
worst example i didn't find need to demonstrate here. we can do in windows form only...
siva
mahesh
Thanks for providing
Thank you very much. It was my 1st WPF sample.... Thanks again..... :)
Vinay
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..
kishore
KISHORE
After creating an application I am not getting any control on toolbox to add on .xaml page.I need help.
Sumantra
kalaivanan
very useful!:-)
Lokesh...
Really nice. I am the beginner for learning Dot net but like to learn more
MMS
Name
E-Mail (optional)
Comment
Post Comment
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
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>
<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
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
Nice...
Ganesh
nice
AT
Rahul
Thanks!
When I can understand a new subject in a few minutes that means that it is "clear and
Jack Shasha
concise" as I like it. I am a technical writer and always striving to achieve a similar effect. Thanks.
Screw the WPF chapt in my C#2010 for dummies, this is how a proper tutorial should be.
OSK
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.
krishna
Mahesh
Thank U
Very cool tutorial. Is there a way though that you could put forward and next buttons? Thanks.
Jason
bibin tv
Hello! kfedfaa interesting kfedfaa site! I'm really like it! Very, very kfedfaa good!
Pharme195
Hello! fdkcgae interesting fdkcgae site! I'm really like it! Very, very fdkcgae good!
Pharmg537
Thanks. A very good and succint read. Waiting for more articles.
Atif Hussain
Fantastic Notes
LampGlow...
Thanks A Lot......
Baljinder
great ..
innocent...
Name
E-Mail (optional)
Comment
Post Comment
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
The size can be specified as an absolute amount of logical units, as a percentage value or automatically.
<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>
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>
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"/>
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>
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.
► Tutorial ► Adobe InDesign ► InDesign CS3 ► Adobe Print
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="Stretch" 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="True" also does not help...
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.
Superb.........,
Om Prakash
I Heart fully,
Om Prakash Bishnoi
Software Engineer ,
DotSquare, Jaipur(RAj.)
This is my firts time to use WPF, It is a great help. Keep it up man! Thanks
Dennis
Ray Akkanson
Ra Akkanson
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.
Good One...........:-)
Manoj
Nice one
J
btf..nice article
Ashu
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)
Nice
Vijay
Good to learn
sreenivas
Hi,
Gagan M
I just found a typo. Will be better if you can get it rectified since it might be confusing for others.
'The following example shows a grid with three rows and two columns.' (Instead there are four rows
and two columns in the example)
Thanks.
Randy
Name
E-Mail (optional)
Comment
Post Comment
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.
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.
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.
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.
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.
// 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)
{
DependencyPropertyDescriptor textDescr = DependencyPropertyDescriptor.
FromProperty(TextBox.TextProperty, typeof(TextBox));
if (textDescr!= null)
{
textDescr.AddValueChanged(myTextBox, delegate
{
// Add your propery changed logic here...
});
}
button1.ClearValue( Button.ContentProperty );
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
Very Goooddddd !!
Ali
Thanks.
Could you please put a XAML sample of the binding to the property developed in the code? Thanks.
Adriano
The only article that does not confuse readers on Dependency Properties
Jay
YES !
Rene
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.
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 .
Thank you very much.i was looking like this type of article
mahanth
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
Very nice explanation on dependency properties............finally understood the concept ! Thanks for
Maya
posting this.
I m the beginner of WPF. wow! thts really great to have site like this. Thanks. its helping me a lot.
Cryptic
why is the dependency property declared as readonly if you are also using the SetValue method
blah!!!blah!!!
Rithuu Content is Precise and well defined. Thanks for writing this article.
Mangala
seyed
There is an miistake on Readonly DependencyProperties section. Wrapper method is defined as 'int'
but DependencyProperty is already as 'bool'.
Can you explain some more info about it? Where i must insert these codes?
Thank's again :)
Hi Christian
Ohad
Thanks for your detailed explanation!
1. At the begining when you expalnied about the advantages one of them was "Reduced
memory footprint" u wrote that when using DP it reduces memory storage compare to Normal
Properties because it "only stores modified properties in the instance & The default values
are stored once within the dependency property".
I understand that when storring only changes it reduces memory storage but what does it mean that
the default values are "stored within the dependency property"? i mean they must be
stored somewhere when application runs, so where would that be?
so why DP takes less memory than Normal Property?
i wanted to know how is this fact empowers DP compared to normal Prop'. why is it
better?
3.I understood that there are "Readonly DP" but i have noticed that when using the
shortcutin Visual Studio for creating regular DP (propdp) a
so what is the difference when adding "readonly" statement in regular DP and ReadOnly
DP?
Hi Christian
ohad
Thanks for your detailed explanation!
1. At the begining when you expalnied about the advantages one of them was "Reduced
memory footprint" u wrote that when using DP it reduces memory storage compare to Normal
Properties because it "only stores modified properties in the instance & The default values
are stored once within the dependency property".
I understand that when storring only changes it reduces memory storage but what does it mean that
the default values are "stored within the dependency property"? 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 "Readonly DP" but i have noticed that when using the
shortcutin Visual Studio for creating regular DP (propdp) a
so what is the difference when adding "readonly" statement in regular DP and ReadOnly
DP?
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?
hello
dsd
E-Mail (optional)
Comment
Post Comment
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
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.
Tank you!
ali
its nice information its very very easy to understand that you presented
balaraman
good one...
sarath
Very good website for giving initial and advance knowledge of WPF and how to implement in any
Jamil Akhtar
Application.
Datla
why dont you add next page/previous page button.
Coole Website:
Sedat
Werde jetzt mal den Inhalt checken.
thanks a lot
alireza
Thanks!!!
Siva
good one...
satyawan
Sagar
.......
it is realy good
Zeeda
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???
Neelam Great Job!!! Kindly post some tutorials for learning .net framework 3.5
Sharma
Sang
thank you ,it is good for beginners,it makes me to complete the following
Hanan
Awesome tutorial
Santosh
Name
E-Mail (optional)
Comment
Post Comment
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).
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.
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Brushes
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!
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
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
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.
@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.
@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
jhon
using wpf, pls view me some sample or give me some sites that can
help me in developing may programm..thanks..
nice work
Rohatash
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:
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!
suresh
I learn wpf basic easily..this is great.
ramasamy
Hi Borislav,
Christian
the problem has been fixed in version 0.9.8. You can download it directly from codeplex.
Moser
It's great site who are working on WPF for the first time .
Debashish...
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.
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.
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.
Greets
Tobi
Hi,
Rohit
WPF Inspector is an awesome stuff for a wpf developer. But i'm facing an issue with it.
Thanks,
Sir please give demo video how to work on this? i am not able to know this one.Its showing empty.
shankar
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.
Good
Sai Govind.N.K
E-Mail (optional)
Comment
Post Comment
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
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
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
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
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Brushes
Mani
http://avalondock.codeplex.com
Please update.
FluidKit
pcdny
http://www.codeplex.com/fluidkit
FluidKit
pcdny
http://www.codeplex.com/fluidkit
Bala
http://www.syncfusion.com/
can nebody telme wer i can get the freeware software for datagrid in wpf
pooja
TKundNobody
very informative
Abirami
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
Is WPF Window forms have Help Button(?) ?. pls let me know.Its very urgent.
Ranjan
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.
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.
Is there anyone test performance of grids that contains blinking, changing layout, painting (like real
yunus
time feed) with large data?
Is there anyone test performance of grids that contains blinking, changing layout, painting (like real
yunus
time feed) with large data?
componenArt.. componentone, and syncfusion which one is most good.. i want to purchase one
AFtab
anyone guide me
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
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
Sofa (Open Source), A wrapper for previously mentioned AvalonDock (Open Source) in the docking
WPF Sofa
libraries category, http://sofawpf.codeplex.com
TEAM
FYI,I have used AM Chart component to display the large data in charts.Its having zooming features in
Ravi P
linecharts,bar charts.
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)
GOOD ONE
James
Die ESRI WPF/Silverlight controls könnte man noch als GIS-Controls aufnehmen.
Jay
http://help.arcgis.com/en/webapi/silverlight/index.html
Name
E-Mail (optional)
Comment
Post Comment
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;
}
► Tutorial ► Dreamweaver CS4 ► WebPage Templates ► Web Design Books
Name
E-Mail (optional)
Comment
Post Comment
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
3D Graphics
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
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.
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.
"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.
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.
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.
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.
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.
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Adobe Photoshop
UjJEVY http://cgE8hcmk9Vvqlosr5wcBa6nk.com
melony
hi,
neo
can any one send above mentioned books links plzzz
Hi could any one send me the free ebooks which can be downloaded
sirisha Gundala
Hey sajan, varsha and sirisha..!! Download the books free of costs..!!
Mohanish
Can some one let me know, where i can found the freeversion of above books.. thanks
Praveen
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
Hi everyone....
jehanzeb afridi
Nice article..
Regards
Jehanzeb afridi
Wow !!!
suvo
er.... all those people asking for free versions of the books. The authors didn't write them for free you
author
know!
Try in torrents..
Arka...
This is Excellent.....
Abhishek
Good work. How about a -next page - so I don't have to keep going back to the menu to proceed
akalan
http://www.mediafire.com/?vyjzln0mnjj (Windows.Presentation.Foundation.Unleashed)
BAd
wow,thx Bad :)
Not Bad
you can download from google. just type the title of book and &pdf in keyword search
whiteTry
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
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!
hhgh
hg
I started with Wrox, it is not really good no really action. Like the tutorial all ready :)
bole
Name
E-Mail (optional)
Comment
Post Comment
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
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
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;
public class TrackableValue<T> : ITrackable
{
private readonly string _propertyName;
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Brushes
Name
E-Mail (optional)
Comment
Post Comment
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
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
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
Kumar
UI Automation
Name
E-Mail (optional)
Post Comment
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
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
Performance
Comment
Expression Blend
UI Automation
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
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?
Farooq
Azam
Would love to subscribe to this site.
great site. been here for two weeks. thank you for the wonderful tutorial!
UandI
Nice Website.
vinay
and i want to learn WPF and WCF Plz help me.
kasera
Name
E-Mail (optional)
Comment
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
Resources
2D Graphics
3D Graphics
Animation
Multimedia
Documents
Windows 7
Interoperability
Performance
Expression Blend
Tools
UI Automation
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
Multimedia
Documents
Windows 7
Interoperability
Performance
Expression Blend
Tools
UI Automation
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
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
Multimedia
Documents
Comments on this article
Windows 7
Show all comments
Interoperability
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
Post Comment
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
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:
UI Automation ► Tutorial ► Adobe InDesign ► InDesign CS3 ► InDesign Template
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)
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.
wpf
andre
Name
E-Mail (optional)
Comment
Post Comment
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
Resources
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
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
Resources
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
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
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
Comment
Tools
UI Automation
Post Comment
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
UI Automation Name
E-Mail (optional)
Comment
Post Comment
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
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
Is there any possiblity to develop Very Much Heavy CAD application with help of Directx and WPF but
olive
not opengl.
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
combobox en wpf
pedro
Name
E-Mail (optional)
Comment
Post Comment
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
Resources
3D Graphics
Show all comments
Animation
Commented on 4.February 2011
Multimedia
it`s looking awesome
chinni
Documents
Performance
Name
Expression Blend
E-Mail (optional)
Tools
Comment
UI Automation
Post Comment
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
Multimedia jk
Documents thanks
Windows 7
Commented on 16.May 2009
Interoperability
We are interest in multimedia application with WPF.
Peter
Performance
Tools
Is it possible to capture real-time Firewire stream with it? How ?
Rychard
UI Automation
Commented on 3.November 2009
Name
E-Mail (optional)
Comment
Post Comment
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
Resources
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
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
Resources
2D Graphics
Documents
Name
Windows 7 E-Mail (optional)
Interoperability Comment
Performance
Expression Blend
Post Comment
Tools
UI Automation
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
Performance
Expression Blend
Can you provide more details on interoperability. Like how to use OCX files, Active X DLL created in
Veerendra...
VC++ in WPF applications.
Name
E-Mail (optional)
Comment
Post Comment
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?
I don't understand what you mean by "cached resource dictionaries" can you please provide a small
faraya hot lebanon lebanese klynn k-lynn fashion show model lingerie snow mzar
y78dha7
<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
Name
E-Mail (optional)
Comment
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
Resources
2D Graphics
3D Graphics
Animation
Multimedia
Documents
Windows 7
Interoperability
Performance
Expression Blend
Tools
UI Automation
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
good
Interoperability P
Performance
Name
Expression Blend
E-Mail (optional)
Tools
Comment
UI Automation
Post Comment
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
dadasdasddasd
shaikjsdkalsd
DSP
Boringgg!!!!
Sush
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)));
: base(ribbonButton)
{ }
return true;
return "RibbonButton";
return "ribbonButton";
return AutomationControlType.Button;
return this;
get
return (UiAutomationRibbonButton)base.Owner;
MyOwner.RaiseEvent( newEventArgs );
}
#endregion
void IInvokeProvider.Invoke()
XAML Code :
<Window x:Class="WpfRibbonControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ribbon="clr-
xmlns:UIRibbon ="clr-
namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ribbon:Ribbon x:Name="Ribbon">
<ribbon:Ribbon.ApplicationMenu>
<ribbon:RibbonApplicationMenu SmallImageSource="Images\SmallIcon.png">
x:Name="MenuItem1"
ImageSource="Images\LargeIcon.png"/>
</ribbon:RibbonApplicationMenu>
</ribbon:Ribbon.ApplicationMenu>
<ribbon:RibbonTab x:Name="HomeTab"
Header="Home">
<ribbon:RibbonGroup x:Name="Group1"
Header="Group1">
<UIRibbon:UiAutomationRibbonButton x:Name="Button1"
LargeImageSource="Images\LargeIcon.png"
<UIRibbon:UiAutomationRibbonButton x:Name="Button2"
SmallImageSource="Images\SmallIcon.png"
<UIRibbon:UiAutomationRibbonButton x:Name="Button3"
SmallImageSource="Images\SmallIcon.png"
<UIRibbon:UiAutomationRibbonButton x:Name="Button4"
SmallImageSource="Images\SmallIcon.png"
</ribbon:RibbonGroup>
</ribbon:RibbonTab>
</ribbon:Ribbon>
</Grid>
</Window>
I am trying to perform automation testing on my app which contains ribbon control.The ribbon buttons
venkatesh
static UiAutomationRibbonButton()
DefaultStyleKeyProperty.OverrideMetadata(typeof(UiAutomationRibbonButton), new
FrameworkPropertyMetadata(typeof(UiAutomationRibbonButton)));
: base(ribbonButton)
{ }
return true;
return "RibbonButton";
return "ribbonButton";
return AutomationControlType.Button;
return this;
get
return (UiAutomationRibbonButton)base.Owner;
MyOwner.RaiseEvent( newEventArgs );
}
#endregion
void IInvokeProvider.Invoke()
XAML Code :
<Window x:Class="WpfRibbonControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ribbon="clr-
namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
xmlns:UIRibbon ="clr-
namespace:WpfCustomControlLibrary1;assembly=WpfCustomControlLibrary1"
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ribbon:Ribbon x:Name="Ribbon">
<ribbon:Ribbon.ApplicationMenu>
<ribbon:RibbonApplicationMenu SmallImageSource="Images\SmallIcon.png">
x:Name="MenuItem1"
ImageSource="Images\LargeIcon.png"/>
</ribbon:RibbonApplicationMenu>
</ribbon:Ribbon.ApplicationMenu>
<ribbon:RibbonTab x:Name="HomeTab"
Header="Home">
<ribbon:RibbonGroup x:Name="Group1"
Header="Group1">
<UIRibbon:UiAutomationRibbonButton x:Name="Button1"
LargeImageSource="Images\LargeIcon.png"
<UIRibbon:UiAutomationRibbonButton x:Name="Button2"
SmallImageSource="Images\SmallIcon.png"
<UIRibbon:UiAutomationRibbonButton x:Name="Button3"
SmallImageSource="Images\SmallIcon.png"
<UIRibbon:UiAutomationRibbonButton x:Name="Button4"
SmallImageSource="Images\SmallIcon.png"
</ribbon:RibbonGroup>
</ribbon:RibbonTab>
</ribbon:Ribbon>
</Grid>
</Window>
Sounds good..............
daniel
Name
E-Mail (optional)
Comment
Post Comment
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
Documents
Windows 7
Interoperability
Performance
Expression Blend
Tools
UI Automation
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.
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.
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
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
For UI prototyping you can use balsamiq mockup http://balsamiq.com/products/mockups very nice
Victor
tool.
wah g wah
papu
For free Life insurance information round the clock anywhere in the world call
Sneha
Sneha +91-9096273779
Darshan S....
Darshan S....
YEPPPEEEEEEEEEEEEEEEEEEEEEEE
RX100
very good
castro
Great!!!!
new_programmer
Good Info......
Deepu
not gud
jay
it's free??
Joe
amazing
nency
amazing
nency
good
drishya
Good explanation.
Pranjal R Nigam
Nice Article
Shubhangi
Good ma
shahul
Name
E-Mail (optional)
Comment
Post Comment
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" />
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);
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.
Nice article
Karthick
prabhu
THANK YOU....
Janynne
Gomes
Tnx!
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.
Really Nice Article for Beginners. Thanks for this helpful article . Thank you guys..
spencer
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.
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
wonderful article
Amihai
It was good but still it needed few practicle examples to elaborate Visual Trees
Sanjay Patolia
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.
chengila
madhav
joshi
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!
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.
DockPanel
+ListBox
+Border
+...
+VirtualizingStackPanel
+ListBoxItem
+Button
+Border
+....
Hallo Herr Mosers, vielen Dank für Ihre tolle Arbeit bei den Tutorials. Sehr gut gemacht
Marcus Galka
und sehr verständlich. Hat mir sehr geholfen.
This is very good article and explained in simple words and realy very good for beginners
Rajshekar...
Thanks bro... you made my day :) please continue your good work....
Ravi Kurapati
Thanks a lot..! :)
Girish
ghiwany
thanks for all
Name
E-Mail (optional)
Comment
Post Comment
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
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
I just needed a quick refresher and for that this was excellent. Thanks.
Basarat
I just needed a quick refresher and for that this was excellent. Thanks.
Basarat
I just needed a quick refresher and for that this was excellent. Thanks.
Basarat
I just needed a quick refresher and for that this was excellent. Thanks.
Basarat
Every man and his bloody dog have written "tutorials" on this, and not ONE shows you how to do it.
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).
wow you guys are really that impressed by mosers copy and pasting
thedirty
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;
//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 :)
great thanks.......
Anand Rajak
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
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
What is the Use of the Routed Event in WPF or Silverlight. Why can't we achive the same using ordinary
Jothimnai V
event
nice description
Sushil
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!
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:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
</Button>
</StackPanel>
</Window>
Nice one but should have one proper example to get clear practical understanding of all the routing
sanjay
strategy
patoliaa
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.
Nice one but Need more practical example to get clear understanding.
ms
To make these tutorials, even more useful, give some downloadable simple example.
Jay
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
really great.
Om Prakash
Name
E-Mail (optional)
Comment
Post Comment
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
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.
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
Assalam-o-alaikum
Mustansar
A lot help for beginners, I am gona present it to my fellows tomorrow :)
Awewsome article!
gdemmi
Nice one it really gives good idea about using layout panels and use best practise out of it. :)
Sanjay Patolia
Om Prakash
Thanks Sir G
Regard :
Om Prakash Bishnoi
Great stuff to make us understand the usefullness of layout panel in a simpler way.
manmohan
nice
rahul
nice article
Raj
Very informative post. Thanks for taking the time to share your view with us.
zeceTeddy
Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo
Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo
Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo
Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo
Could you please explain me how to add a toolbar into a grid by writing code in .xaml.cs file?
Jo
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
Excellent
MEE
Name
E-Mail (optional)
Comment
Post Comment
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 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
Nice one..
upa
After studying this tutorial, i think WPF is intresting topic..
hi evryone!!!
Everyone...
Prabodha Nice
Eranga
Niceone
Sreenivas
2 Mukesh horizontalalligment=center
in4man
nice article...Thanks!!
Sandeep...
cappuccino
me
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>
sbuxboy
nice article :)
Can we take stackpanel inside a grid panel???? i tried but its nt wrking.. im new to WPF .. please help
Swat
thanx this
ray akkanson
article helped me a lot.
Please put some forward and back buttons on these pages. It would make the UX of the tutorial so
Al
much better.
Christian
Is there a way to extend the last Element to the End of the Stackpanel?
Nice Article
Saravanan
Nice turorial.
VeeraPratap...
hi guys
peter ka bap
you know I can still smell wee and a little poo too
ping
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
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,
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;
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.
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?
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.?
Your site is really helpful! Looking forward to more posts!! Well Done.
Hi! How do you do that, but instead of an internal control (CheckBox) a local var, as in, Visibility="
JC
{Binding (MyClass.myVar)}"? I tried a lot of solutions, but none come with good results.
good
gg
Good article
subhash
nice one
nice one
good, nice.
skynet
but i m confused with how can we use databinding with listbox , i get little solution about it in http://get-
Mohit
solution.in
but i m confused with how can we use databinding with listbox , i get little solution about it in http://get-
Mohit
solution.in
FIT
noor
thx a lot bro ... very cool tuto ina very simple way
SamTheDev
nice
sari
I have a few more examples like some have asked for here:
Jared
<a href="http://www.rhyous.com/2011/02/22/binding-visibility-to-a-bool-value-in-
wpf/">Binding Visibility to a bool value in WPF</a>
Very Nice..!!
Sandip
Very Nice..!!
Sandip
Name
E-Mail (optional)
Comment
Post Comment
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.
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}">
<ListBox.GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</ListBox.GroupStyle>
</ListBox>
► Tutorial ► Learn Quick Books ► Data Networking ► Basics
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.
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
It'd be really helpful if you indicated which files each code snippet pertains to...
jyanks
Ehhm, where does the GetCustomers() method come from? Or am I to inexperienced to realize this...
Tomas
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.
Christian
Nigel
Stratton
I think your snippet needs a couple of changes, adding "new EventHandler(" and the "void" return type.
Regards,
Nigel
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! :)
Just write whatever function or data source you like since the only thing that matters is that it returns results in
form GetCustomers() returns.
Thomas
but i still have a question, how can you get the number of visible items in your filtered CollectionView ?
I'm trying to bind and sort and filter images.. how can i posibly do this?
Mutia
(http://mutiarar06.student.ipb.ac.id)
lol
Tod
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this from
Christian M
another website
alimbada
_customerView = CollectionViewSource.GetDefaultView(customers);
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
_id = d
_family = fm
End Sub
Get
Return _family
End Get
_family = value
End Set
End Property
Get
Return _id
End Get
_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")}
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
With g.HeaderTemplate.VisualTree
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)
I understood Itemsource property bindings but Why we use source property while we create collection view in
Sanjay
View(XAML).
Patolia
"I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this from
KC
another website" - Chritian M
Nice!!!
I like it.
[b] John[/b].
Name
E-Mail (optional)
Comment
Post Comment
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
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)
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.
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.
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
johnmc
What's the difference between MVVVM, MVP and MVC?
Gaffar
Hey, great article. Shouldn't the arrow on the MVC picture go from the view to the model? Cheers
Michal
Yes, I agree Michal, the arrow should point from the view to the model.
Guilhermejs
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.
Tanx #
shahrooz
Thanx dude. This is one of the best pattern explanations I've ever seen.
Arie Baba
Explain why is the flow in the MVVM diagram showing a V->VM->M, when the name suggests
Del
M->V->VM
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
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?
Hi, Christian I found one small grametical mistake please correct it. Its here
Rajneesh
�The view-model can even be reused, in sone special cases (this is usually not
Verma
recommended)
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
Great Article. But the Arrow should point from View to Model in MVC as model normally does not
S.Manikandan
know anybody else.
Great Article, it would be great if you attach some samples to explain them. i mean samples with UI
Michael
and DataBinding.
Thanks Christian, your material got me up and running with wpf in a few hours.
dtinsley
Umesh .A Thank you Christian, Good Article. Gets me started on WPF MVVM.
Bhat
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.
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
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);
}
<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>
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)
<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>
<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>
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
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.
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.
Thanks Ceri, that was a better example and with source code and solution file to understand
Sandy
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.
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.
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.
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!!
Plz post the complete Window1.xaml content... Important things are missing.
kap
Error:
Error
This is wrong: Template={StaticResource TextBoxErrorTemplate}>
Now it works!
Is it possible to use DataAnnotations with xaml and if so, any chance of a short example code?
Klara
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
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,...
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...
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?
good , but why there is no simpler way as in winforms for a common thing like validation
sudheer...
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" />
its nice
venky
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.
<Grid.RenderTransform>
</Grid.RenderTransform>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="OpenStates">
<VisualStateGroup.Transitions>
<VisualTransition GeneratedDuration="0"/>
<Storyboard>
<DoubleAnimation.EasingFunction>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</VisualTransition>
</VisualStateGroup.Transitions>
<VisualState x:Name="Closed">
<Storyboard>
</VisualState>
<VisualState x:Name="Open">
<Storyboard>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border CornerRadius="2">
UseLayoutRounding="True"
Foreground="White" Background="Transparent" Margin="8,4,8,4" ItemsSource="{Binding
(Validation.Errors),BindsDirectlyToSource=True}" >
<ListBox.ItemTemplate>
<DataTemplate>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
</Grid>
</ControlTemplate>
---------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.Windows.Markup;
---------------------
Hidden note:
Beauty
You have a mistype in the last parameter of this line:
---------------------
---------------------
Problem:
Beauty
I tried to define <sys:String x:Key="emailRegex">
but got the error that the TYPE "sys:String" NOT FOUND.
After a while I found the solution:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Name
E-Mail (optional)
Comment
Post Comment
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,
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,
► Tutorial ► Converters ► Photoshop CS4 ► Photoshop Action
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
Great article
Farzad
just a typo:
Ralph
correct?
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.
How do I use the MarkupExtension, when the Converter is in another NameSpace than the consumer code?
Patrik
owsome
Bill
Name
E-Mail (optional)
Comment
Post Comment
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
The behavior appears as an child element in the visual tree. By clicking on it you can configure the properties of the behavior.
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>
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;
}
};
}
}
Zoom Behavior
Glass Behavior
Shake Behavior
Transparency Behavior
SWEET!!
Martin Ortiz
Learning WPF, and heard about behaviors.
SWEET!!
Martin Ortiz
Learning WPF, and heard about behaviors.
SWEET!!
Martin Ortiz
Learning WPF, and heard about behaviors.
hi..can u tellme how i can add additional behavoiurs like glass behaviour into my project.....
pooja
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)
yep, what Ever said. some please explain how to solve this, was not able to figure that out yet. thanks in
martin
advance
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
C-MOSEY
from another website
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>
AssociatedObject.RenderTransform = transform;
mouseStartPosition = parent.PointToScreen(e.GetPosition(parent));
AssociatedObject.CaptureMouse();
};
AssociatedObject.ReleaseMouseCapture();
elementStartPosition.X = transform.X;
elementStartPosition.Y = transform.Y;
};
if (AssociatedObject.IsMouseCaptured)
};
</code>
Also, remove the "(AssociatedObject as TextBlock).Text = ..." lines as they are only for debugging :)
Edvald
Sorry about the spam, please delete the comments above, here's a cleaned up version:
Edvald
AssociatedObject.RenderTransform = transform;
mouseStartPosition = e.GetPosition(parent);
AssociatedObject.CaptureMouse();
};
AssociatedObject.ReleaseMouseCapture();
elementStartPosition.X = transform.X;
elementStartPosition.Y = transform.Y;
if (AssociatedObject.IsMouseCaptured)
};
Great Article
RItty
Great Article
RItty
Name
E-Mail (optional)
Comment
Post Comment
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.
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
Graciassss!
Ricardo
<Window.Resources>
Ashish J
<Style x:Key="myStyle" TargetType="Button">
</Style>
</Style>
</Style>
</Window.Resources>
</StackPanel>
<Window.Resources>
Ashish J
<Style x:Key="myStyle" TargetType="Button">
</Style>
</Style>
</Style>
</Window.Resources>
</StackPanel>
Superb tutorial..
Ravikumar...
I like this tutorial, by this only i came to know how to use style in the WPF application. Thanks a lot
Asha.MP
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
Hi sir, i have small doubt.Can i add css to wpf applications? and can i add styles for windows. means in
shankar
ResourcesDictionary?
Very nice
Rajesh
Wonderful straight forward and easy tutorial. And previous comments assisted me as well to get it
ShoneenJvV
working first time!
Sajjad...
is it possible to only change the name of theme and styles get applied?
Rajesh
Hi, I have applied Styles to all buttons to have a certain heights, margins, but buttons inside my
YH
Thanks
Thanks!
Anon
avi
<Button Background=\"Orange\" FontStyle=\"Italic\"
Padding=\"8,4\" Margin=\"4\">Styles</Button>
</StackPanel>
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.
<Window>
<Window.Resources>
</Style>
</Window.Resources>
</StackPanel>
</Window>
fsfsfdfdgd
<Button Background="Orange" FontStyle="Italic"
Padding="8,4" Margin="4">Styles</Button>
</StackPanel>
bri
<Button Background="Orange" FontStyle="Italic"
Padding="8,4" Margin="4">Styles</Button>
</StackPanel>
Aly Thank's..Great... :)
Sangadji
Name
E-Mail (optional)
Comment
Post Comment
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.
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
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.
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
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 !
seems really interesting thanks for your efforts to make this material available for us
i
Nice one
Arjun
Asha.MP
in the above properties we can specify the colors also, what is the meaning of TemplateBinding in the
above property??
nice...
siva
very nice.
bala
good one
Tejas
So Clear nice
bm
I want to create Template for TextBox. How can I aceess RelativeSource TEXT property.
Alibaba
@Alibaba: If I am understanding you correctly, you would not use RelativeSource to bind to the text
stigma
property. You would use "{TemplateBinding Text}". For example:
Using a TextBox inside a TextBox ControlTemplate, however, I have found to be very unhelpful. Try
using: <ScrollViewer x:Name="PART_ContentHost"/> If you name the ScrollViewer
exactly as I have here, the text will be bound to it. No other work required.
Life Saver :)
Ziad
Viva linux!!
Gonzalo
Name
E-Mail (optional)
Comment
Post Comment
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
<!-- 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>
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;
}
<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
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.
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.
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.
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?
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?
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?
WOW
tim
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...
Great article, just what I was looking for. Great web site.
Nikola
Nice
Bala
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.
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?
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!
good chaka...
jhon
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
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.
<DataTemplate x:Key="DefaultDataTemplate">
<StackPanel Orientation="Horizontal">
<tree:RowExpander />
</StackPanel>
</DataTemplate>
<my:ResultCellTemplateSelector x:Key="templateSelector"
DefaultDataTemplate="{StaticResource DefaultDataTemplate}"/>
<Grid>
<tree:TreeList x:Name="tlResults">
<tree:TreeList.View>
<GridView>
<GridView.Columns>
</GridViewColumn>
</GridView.Columns>
</GridView>
</tree:TreeList.View>
</tree:TreeList>
</Grid>
sorry, it's my mistake, I used the template from another control. It's working fine now, thank you very
unruledboy
much!
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 "SELECT LOOKUP_VALUE FROM LOOKUP
WHERE LOOKUP_KEY = 'CAR_MFG'", which will return a list like: Toyota, Ford, Nissan, Honda, VW,
BMW, ...
If I have > 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
Thank you,
I run example solution with VS 2010 and .NET 4. It starts but when scrolling I am getting following error:
Mikhail
jones
Try this with the Property DependencyPropertyInfo.Value in DependencyPropertyInfo.cs:
I suppose the error occures, because the Comboboxes have no item selected...
Name
E-Mail (optional)
Comment
Post Comment
Home
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
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).
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.
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!
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
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
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.
@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.
@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
jhon
using wpf, pls view me some sample or give me some sites that can
help me in developing may programm..thanks..
nice work
Rohatash
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:
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!
suresh
I learn wpf basic easily..this is great.
ramasamy
Hi Borislav,
Christian
the problem has been fixed in version 0.9.8. You can download it directly from codeplex.
Moser
It's great site who are working on WPF for the first time .
Debashish...
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.
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.
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.
Greets
Tobi
Hi,
Rohit
WPF Inspector is an awesome stuff for a wpf developer. But i'm facing an issue with it.
Thanks,
Sir please give demo video how to work on this? i am not able to know this one.Its showing empty.
shankar
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.
Good
Sai Govind.N.K
E-Mail (optional)
Comment
Post Comment
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
Nice..!
pradeep
very nice..
Naik
Great Videos............
uday
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 "Super presentations...". Come on!
Nice article !
Ajay Jamwal
@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
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-
<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/>
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>
<!-- XAML 2006 -->
Guid id = Guid.NewGuid();
<!-- XAML 2009 -->
<Guid x:FactoryMethod="Guid.NewGuid" />
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Adobe Photoshop
Nice Article
pallavi
se
lll
yak................dirty
rahul
Kiran
When i am using this markup
<Label Target="{x:Reference firstName}">FirstName</Label>
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:
Above Example and Definition is very good & sort and sweet.
vishal
basavaprasad
thank you for mentioning, but VS2010 doesnt offer a namespace url like
orhor
"http://schemas.microsoft.com/winfx/2009/xaml"
This still does not work with WPF and VS 2010 !!!
DNM
mmmm
kkk
please provide the examples along with the syntax.you can provide the link to the example.
kamlendra
It's very nice feature.. Keep it up...It's very useful for beginer.
Mohit Jethva
Good one
Deepthi
Tim http://msdn.microsoft.com/en-us/library/ee792002.aspx
Valentine
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.
Rajeev I did not get the topic.Can you please explain it little bit more.
Kumar
Name
E-Mail (optional)
Comment
Post Comment
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
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
itz fabricated
baba
Tom
Thats no way
@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... :)
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
nice
golden
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
CHRISTIAN
from another website
eeekkk, you really should reference any websites you copy from. Thats someones elses knowledge
Shane
Rajesh
These are requirement recommended by seller.
The minimal hardware requirements for wpf application depends on the Media effects & codings
Lahiru
.The application should test with the deployed environment
Jayalath
nice article but mention the requirement for a more robust graphics and animations too....
Manvendra
Shane: also it's obvious that's some troll posting in the comment section.
Gunnar
Name
E-Mail (optional)
Comment
Post Comment
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
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
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
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
Good
Helix
Great work...!
Qutub
Great work...!
Qutub
Great work...!
Qutub
Great work.!
subramani
Name
E-Mail (optional)
Comment
Post Comment
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.
public class MainWindow : Window
{
[Dependency]
public MainWindowViewModel ViewModel
{
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Brushes
awesome !!
chinnappa
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.
thanks..
mukesh
sagar This is think i m looking from long time. Architecture wise WPF make sense isn't it?
tambe
@Sagar
Jeremy
DI was around LONG before WPF. You should look at Martin Folwers articles from the beginning of
this decade.
great job...
rashmin
Good Explanation
Manish K
can we have source code to download?
we can make good ny having code , from where we can have this souce code
San
we can make good practice having code , from where we can have this souce code
San
What a great idea, palagarize other peoples material, have ads and make money.. who says crime
JIm
doesn't pay.
Great work...
Viral Dave
Why MainWindow knows about the view Model(have logical reference though property)
Gopal
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
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
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.
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?
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.
chala bagundhi....
nagarjunareddy
thanks my dear!
alireza
Name
E-Mail (optional)
Post Comment
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;
Good artical!
lan
If with an example is better
YJ
A lot simple, but it could help.
Good artical!
Ganesh
but no any example need eample for all property as like your wcf article
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
C-MOSE
from another website
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?
=> 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.
Hi,
dct
if you would like to use this class with WPF4 you have to remove the override keywords.
Take care
Hi,
Hitesh
Good article. Override keyword not needed.
Thanks
Hi Christian,
Catalin
Manoliu
A better example I suggest is this RelayCommand:
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030
Regards,
Catalin
Hi
costas...
the override bool CanExecute and the override void Execute has no override...
Name
E-Mail (optional)
Comment
Post Comment
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:
3D Graphics
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 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 DisplayMode="Year" />
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Brushes
How to make a google calendar like calendar? i.e. an interactive one tt I can add events or tasks to it...
z
smruti
that great.
morteza
good luck
Hi, There is not calendar control in vs2008. In this case how to create calendar control
Sachin
Ganesh Kumar
I have a problem for you. My visual studio toolbox is not showing calender control.
gimme reply.
Thank You.
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.
veer.k
Hi christian,
Madhu Kumar
i do not know how to implement ajax for calender.plz give me reply
K.S
I am getting an error as Error The name 'InitializeComponent' does not exist in the current context
Dorababu
could you please help me
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..
Siva
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.
Hi Christian
Christof
Ammann
Sorry for my question where I asked if I only could set the "Days of the month".
Greez Christof
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?
The event arguments passed by this control (Calendar Control) event has a property of what we need.
hi, thanks...
prem tiwary
it's very.........good
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
Post Comment
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
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
@Kyaw Wunna
chet
you must reference the namespace
xmlns:l="clr-namespace:[namespace of ItemsControlHelper]"
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?
Don
itemsControl.ItemContainerGenerator.StatusChanged = null
missing. Not the finest method to clear the events, but it works.
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:
if (element != null)
element.BringIntoView();
return null;
Name
E-Mail (optional)
Comment
Post Comment
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
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">
► Tutorial ► Flash Player 5 ► Flash SlideShow ► Adobe Flash
Its so nice.
Ganesh
Nice!
Don
But i think, OnDropDownOpenChanged - Method is useless ?
If i comment it out, nothing changes
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,,,
To Good
Rita
jb
pradeep
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
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.
I got the same exception "DialogResult can be set only after Window is created and shown as dialog"
Doaa
while clicking OK button"
You need to call ShowDialog() method of this window class to show it.
Alex Che
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
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.
I working in wpf with vb.net , i used this code but a gives exception
rahul
so plz how to used
bhojane
getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
suma
clicking OK button :( ..What to Do
DialogResult:
chet
Gets or sets the dialog result value, which is the value that is returned from the
System.Windows.Window.ShowDialog() method.
getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
gopichandan
clicking OK button :( ..
getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
Ramakanta
clicking OK button :( ..
getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
aadsd
clicking OK button :( ..
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
yossharel
you have to remove the StartupUri="Window1.xaml" from App.xaml and to App.xaml.cs this:
w.ShowDialog();
base.OnStartup(e);
w1.ShowDialog();
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...
Thanks.
getting an exception "DialogResult can be set only after Window is created and shown as dialog" while
karthik
clicking OK button :(
add another page and create the function dialogueresult(). call this function using the object of that
smera
where function defined.
Getting Errer -
Damitha
DialogResult can be set only after Window is created and shown as dialog.
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
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
UI Automation
Commented on 12.August 2009
Rick, you could try using common sense and adding the missing '>' yourself, don't you think?
Mark
rofl
David
su
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.
lol
bbbbbbbbbbbb...
good site
Happy
Aarti Varadkar
Check out this link for WPF Slider control:http://nayyeri.net/slider-control-in-windows-presentation-
foundation
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...
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.
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
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
Multimedia
Documents
Comments on this article
Windows 7
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
It's nice..
Kalpesh
Kalpesh
Vekaria
http://www.tatvasoft.com/
Anand
it's great.
Elan...
http://www.elantechnologies.com
Dear All,
Nitin Sharma
http://www.c-sharpcorner.com/UploadFile/mahesh/WPFPopup08172008075339AM/WPFPopup.aspx
Ramu
dotnetwithexamples.blogspot.com
its good
Ebha
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
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" />
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;
► Tutorial ► Flash Player 5 ► Flash SlideShow ► Adobe Flash
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.
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.
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.
rahul
Great thanks
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"?
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).
atul
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...
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.
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.
Hi,
swapnil
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
Thanks in advance.
Swapnil
Hi,
swapnil
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
Thanks in advance.
Swapnil
@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.
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
</ControlTemplate>
</Setter.Value>
</Setter>
Lee.
"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.
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
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.
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.
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.
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.
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.
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
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>
<Button ToolTip="Saves the current document"
ToolTipService.ShowDuration="20"
Content="Save">
</Button>
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...)?
Hi Christian
Bolshoi Booze
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition .. />
<Condition .. />
</MultiDataTrigger.Conditions>
<Setter Property="ToolTip>
<Setter.Value>
<Grid>
</Grid>
</Setter>
</MultiDataTrigger>
</Style>
Thanks
Hi Christian
Bolshoi Booze
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition .. />
<Condition .. />
</MultiDataTrigger.Conditions>
<Setter Property="ToolTip>
<Setter.Value>
<Grid>
</Grid>
</Setter.Value>
</Setter>
</MultiDataTrigger>
</Style>
Thanks
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.
Greetings
Christian
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>
</StackPanel>
</ToolTip>
</Button.ToolTip>
</Button>
Hi
someone
How can I set this tooltip (with stackpanel etc) in style file?
<Setter.Value>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="ToolTip">
<Setter.Value>
<StackPanel>
</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?
Nice Explanation..
durga
I'm also interested in styled tooltips like commentator from "21.August 2010"
Alex
Nice sample
Sanjay Patolia
Wonderful!
YuZhoufeng
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
Terry
This xaml displays button but you can't click on it.
Thanks
Terry
Ex:
<ComboBox.ToolTip>
</ToolTip>
</ComboBox.ToolTip>
Name
E-Mail (optional)
Comment
Post Comment
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)
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.
thnks
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.
thnks
this is good .
ebrahimi
thanks .
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!!!
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
Christian
from another website
Give him a break. Even if some of it is copy and paste, it's laid out very nicely with nice graphics
andy
screenshots.
hi! I need detect when user pulse intro, Someone knows how to do this? I'm using mvvm
Victor
I Heart fully,
Ayyappan
Thank you for your nice Material
warm regards,
Ayyappan,
Software Engineer ,
Chennai,
Tamil Nadu.
http://www.banyansoft.blogspot.com/
Javed Khan
thanks
Alexander
Regards
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 "WPF
Tutorial"
I'm using VS-2008[Framework 3.5]. Spell checking functionality perfectly works for English language. But
Karthik
it�s not working with Spanish, German and French language dictionaries. Please guide me
and where I�m making the mistake. Following language code are used in my application.
Name
E-Mail (optional)
Comment
Post Comment
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
<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.
<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...'");
}
<Menu>
<Menu.Resources>
<Style x:Key="ThemeMenuItemStyle" TargetType="MenuItem">
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
What do I need to do if I want the Help menu item on the right-hand side?
Victor
Thanks!!
bar
Mehul
Very Helpful
Special Thanks !!!!!!!!!
Nice.. Thanks!
esha
Hey Christian,
Shweta Patel
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.
Jitendra
thanks
Jitendra
thanks
@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.
vinay
and there is define in both language XML and C#.
Again Thanks.
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 "True". 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
Jesse B
<MenuItem Header="_Copy" Command="Copy">
You then right click on Paste_Click and select "Navigate to Event Handler".
Thanks
Deepak
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?
Hola soy nueva en esto tengo una duda...Es posible llamar un MainWindow de un submenu como se
izel
isiera en un windownForm
Thamk you!
Designer_my
nice written
babu
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'
saber
Name
E-Mail (optional)
Comment
Post Comment
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
The Tutorial was not a tutorial, but there were some interesting comments on what posters wanted and possible
mike c
solutions.
nice work
chintu
Nice Article. But how to make the expander to expand and close slowly. kindly help
Ismail
How does one make the the header a gray color so one can tell it apart from the other content?
Xarzu
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?
<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"
<Window.ContextMenu>
<ContextMenu/>
</Window.ContextMenu>
<Grid x:Name="LayoutRoot">
<StackPanel>
<Canvas>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.342*"/>
<ColumnDefinition Width="0.658*"/>
</Grid>
</Canvas>
</Expander>
<Canvas>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.342*"/>
<ColumnDefinition Width="0.658*"/>
</Grid.ColumnDefinitions>
</Grid>
</Canvas>
</Expander>
</StackPanel>
</Grid>
</Window>
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!
I want to know can we change the position of exapnder pointer without effecting the internal things in expander
Vishal Pandit
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,
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
bollocks
Bob
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.
Xclnt.
ESmile
Xclnt.
ESmile
Hi. I would like to know how I can open a Page.xaml in a browser. Can you pls help? Thanks
Anju
how to Control Move Down When Expender is Expend Down. also hw to reset ???
M Shariq
Name
E-Mail (optional)
Comment
Post Comment
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
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)
http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html
► Tutorial ► Learn Quick Books ► Coding Learning ► Basics
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.
twerwetr
wert
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?
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?
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?
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?
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
on cp tell ur kids
flyinghippie
nice.. concentrate
ameen sheriff
Good
Divya
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.
http://www.rhyous.com/2011/04/08/wpf-navigationservice-blanks-passwordbox-password-which-
breaks-the-mvvm-passwordhelper/
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
For my understanding this code can never run, because calling SetPassword will reset the binding. I
karle
see this in the debugger. (?!)
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...???
good work ;)
Abraham
Took me a while to figure this out, but here is a bit more complete bit of XAML showing how to bind.
Joe
"UserPass" is the dependency property on the backend that I bind to:
<StackPanel>
</StackPanel>
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:)
that's good
Rakesh
Name
E-Mail (optional)
Comment
Post Comment
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>
<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>
<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>
private void OpenContextMenu(FrameworkElement element)
{
if( element.ContextMenu != null )
{
element.ContextMenu.PlacementTarget = element;
element.ContextMenu.IsOpen = true;
}
}
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
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.
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.
Ritesh
<TextBox.ContextMenu>
<ContextMenu >
<MenuItem Command="Copy"/>
<MenuItem Command="Paste"/>
<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.
Nice Example...
RaviGogu
hallow word...
JOSE...
this script not work for me.
article is best
mat
<script language="javascript">
hi
window.document.href("http://www.google.com");
</script>
Useless as always...you should branch out to childrens books - - I wish Google would stop finding this
Adam
site!
Thank you!
Mickey
It was very fast help!
Very user-full.
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)
cm.Items.Add("Expand")
cm.Items.Add("Collapse")
ContextMenuService.SetShowOnDisabled(Me, True)
Me.ContextMenu = cm
End Sub
You could use the same handler and just use a case statement but here is one way of adding your
Mr Helpful
event handler.
miExpand.Header = "Expand"
cm.Items.Add(miExpand)
miCollapse.Header = "Collapse"
cm.Items.Add(miCollapse)
ContextMenuService.SetShowOnDisabled(Me, True)
Me.ContextMenu = cm
End Sub
Me.IsExpanded = True
End Sub
Me.IsExpanded = False
End Sub
These samples are a bit misleading at times. Ok if your bumbling about with WPF but not if your a
Taz
professional developer.
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???
Mik
It works as I expected!
Superb... i have used this in my custom control and its working fine...nice
Jigar...
hi.. i have used this in custom control and its working fine..
Jigar...
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="" with many values and nothing changes.
Name
E-Mail (optional)
Comment
Post Comment
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
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Brushes
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.
Errors:
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'
-------------------------------- code :
<Window
x:Class="WpfDataTemplate.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<Window.Resources>
</Border>
<DataTemplate.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type
ListBoxItem}},Path=IsSelected}" Value="True">
</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>
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=
</DataTrigger>
specify all the teram u have used in this. just a expamle.. i mean in breif need more discription.
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
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"
<Window.Resources>
<StackPanel Orientation="Horizontal">
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<ListBoxItem>New York</ListBoxItem>
<ListBoxItem>Los Angeles</ListBoxItem>
</ListBox>
</Window>
arrayss
pls give example
rajasekar
Hello.
<ListBox.ItemTemplate>
<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.
@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.
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
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
cxvxvcx
gffd
nadidbadid
The header image induces that you are standing at the horizon of success
Nice design ;)
Name
E-Mail (optional)
Post Comment
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
UI Automation
Mohamed Can you please any example with most of the properties used for listview.
Harris
Jaydev
How to implement paging in ListView in WPF? Please let me know with an example.
Rakesh
Mallarapu..S...
sri.mallarapu09@gmail.com
sdfsdf
sd
hi
parth
doin my msc it
parth kamani
atmiya
parth kamani
Mohssen
I Write This But Don't Show SubMenu Of "aaaaaaa".
<Grid ShowGridLines="True">
<MenuItem Header="aaaaaaa">
<MenuItem Header="ddddddddddd"></MenuItem>
<MenuItem Header="wwwwwwwwwww"></MenuItem>
</MenuItem>
<MenuItem Header="oooooooooooo"></MenuItem>
</Grid>
Tank You.
Rajesh
Rajesh Mallela
hello
ghfghfghfghfg
ListView
thanks
nice site
him
Name
E-Mail (optional)
Comment
Post Comment
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
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.
It is very good & very useful to beginners to learn WPF from base.
Name
E-Mail (optional)
Comment
Post Comment
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
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
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
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
very good...........
parvendra
@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.
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.
It's good
suresh
Pretty good, but needs much more elaboration. Thanks for the good site though!
Fred
thanks
sathish
thanks
sathish
Thanks
Parshuram...
Mamtha
Cheers
thanks
Arinal
asfghjkl
asdfdfasdf
Name
E-Mail (optional)
Comment
Post Comment
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
Multimedia
2. Create Project Structures
Documents
Windows 7
Interoperability
Performance
Expression Blend
Tools
UI Automation
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.
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.
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)));
}
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
Content follows...
► Tutorial ► C# WPF Example ► WPF Datagrid ► WPF UI Controls
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!
can you pls also go ahead and explain how to use this control in the wpf application?
Nayak14
Nice ....
Harendra
Keep in post new things.
kumar
To my question:
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.
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:
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.
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:
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.
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.
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.
George
Dmithrov
Keep on posting new things.
Please add more content to this article. May be how to modify the derived control.
Mohamed
NewDeveloper
Can i use the same control to edit and search too ?
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.
"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?
Alessandro
I dont think it is in no way helpful for beginners. Incomplete articles. total waste of time.
x
How much longer untill you finish what you started? This was posted June 2009???
Wesley De...
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?
worthless
!!
Name
E-Mail (optional)
Comment
Post Comment
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
<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>
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
<DockPanel>
this.doesn't...
<Button DockPanel.Dock="Top">dock 2.1</Button>
</DockPanel>
How can i use the docking mechanism, like in VisualStudio 2008 with WPF.
Somebody
Thanks for reply
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.
Is where any way to create some other windows that be dockablle on main window, like in Visual studio
Zzr1400Huray
or Photoshop?
Hello,
JJ
It is possible to dock a wpf window to the screen edge and to a second wpf window like in Winamp?
Thanks.
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?
crazyTequila
Cheers
Coooooooooool man
Sunil
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?
@Raman - when you say 'hide the top group box' is that using Visibility="Hidden"? If so, try using
lukearl
Visibility="Collapsed" instead.
Good...
Thanks a LOT!
Matthias
MAK
Khaniya
and be more if added runtime cs code to achieve same
thanks
Is it possible to dock a wpf form from one application to another wpf application?
Louie
Is it possible to dock a wpf form from one application to another wpf application?
Louie
Good one
Liza
<DockPanel>
nn
<Button DockPanel.Dock="Top">dock 2.1</Button>
</DockPanel>
<script>alert(\"S\");</script>
example
<DockPanel LastChildFill="True">
gfgfgf
<Button Content="Dock=Top" DockPanel.Dock="Top"/>
<Button Content="Dock=Left"/>
<Button Content="LastChildFill=True"/>
</DockPanel>
<button>bla</button
x
Name
E-Mail (optional)
Comment
Post Comment
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>
<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>
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...
I'm a born again Christian and I don't believe in WPF. It's the devil's work.
Saphron
I am an isreali and I am claiming a birthright to use WPF. I will not tolerate any native developers
Andrew
making similar claims.
nice one
Arvinth
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!!!!!!!!!
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.
Nice Explanation
Shrinivas
good
Rajasekar N
Its Nice
Rajesh
Good one
Amit
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?
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?
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
Hi,
noone
I want to use a canvas panel to be editable after running the WPF application.
k
k
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???
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???
"I want to position controls in various places throughout the form for the look and feel I
ocsirf
desire." --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
Name
E-Mail (optional)
Comment
Post Comment
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>
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
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!
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.
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
In the second paragraph under "Introduction," it begins, "The StackPanel can be used..." -- I think you
Joel
meant, "The WrapPanel can be used...."
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.
Thanks for the help. What panel would you use to hold images for a photo gallery?
Betsy
very nice
raman
<WrapPanel Orientation="Horizontal">
4545
<Button Content="Button" />
</WrapPanel>
Nice article.
Prasanta
very nice
suma
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?
I have a wrap Panel. Now I want to add 1000 000 buttons into it. I write the method
CuongDV
private void AddButtons()
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
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.
Miu
Thanks for to the point and simple description! Simplicity is rare! :)
Thanks,Nice artical.....
Gourav
Name
E-Mail (optional)
Comment
Post Comment
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
Textwrapping is not working with Viewbox.. I tried lots of.. please let me know if any solution or
Ujval
alternative
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.
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.
How can i set the background color of a VeiwBox? There is no property available for it :|
Raul
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
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!!!
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.
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.
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
C-MOSE
from another website
Hi, Can the viewbox tool display Pictures? and if the answer is yes, How to do so?
SHeeDeED
...
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..
<Border>
<ViewBox>
<TextBlock/>
</ViewBox>
</Border>
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 "Object reference not set". Can anybody help me out to
overcome it..?
dfsgbdfsgdf
dfghsdfhsd
i m fine
boom
hi,
Prathyusha
Name
E-Mail (optional)
Comment
Post Comment
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)
TreeMap Panel
Animating Tile Panel
Radial Panel
Element Flow Panel
Ribbon Panel
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
Good example..
Venu
you should call Measure on each of the children before getting their DesiredSize - you forgot to do
that.
Hi Ido,
Christian
thanks for the feedback. I really forgot to call Measure(). I corrected it in the example.
Moser
You're also not returning the values in the methods. This wont compile
Chris
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
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
UI Automation
is it really working ?
nandy
Can WPF application windows can process mouse events through SendMessage() notifications (with or
KingMarcusVi...
without mouse pointer hovering above its window)?
Christian
Did you register the eventhandler? TextInput += MyControl_TextInput;
Moser
Do you receive the entered text in the _text string?
Mr Sda
Your a boss eyed jack ass.
Oh, good joke) Why do birds fly south for the winter? It's quicker than driving.
tarahgiv
___________________________
TextBox will mark the key press as handled, use PreviewTextInput event.
Phil
2 things:
COPYRIGHT
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!!!
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
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" />
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
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
<MenuItem Header="Cut" Command="Cut" CommandTarget="
{Binding Path=PlacementTarget,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}}}"/>
► Tutorial ► Dreamweaver CS4 ► WebPage Templates ► Web Design Books
ads
a
Now that is the best idea I've read all day. Thank you for posting it.
speed
Super!
Dario
thanks
Thank you. Your post really helped me. I've been looking into this problem for 2 days, and your post
Kai
answered my question.
thanks :)
serine
Name
E-Mail (optional)
Comment
Post Comment
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
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
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?
It really works!
balaji
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.
Nice tut.
Brandon
Name
E-Mail (optional)
Comment
Post Comment
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
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".
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);
}
}
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Adobe Photoshop
WoW,oh my god
saman
You mentioned "emulates multitouch on a normal PC" .Will it work for normal monitor(any pc
Bala
monitors)?
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.
Ok...Thanks. Josep :)
Bala
no props
heman
hi ..
Mohammed
FBI
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
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
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
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
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
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).
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;
► Tutorial ► C Sharp Tutorial ► ASP Net Tutorial ► VB Net
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
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?
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.
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.
very useful
Elia
Salam :)
MAF
No you can't, you can use LINQ to XML or use an instance of XmlDataProvider.
Fantastic. You should work for MS and this should be in MSDN Library!
Tony Wall
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.
Ricibald: Can you post an example of how this is done? Also will all this work with Silverlight 4.0?
Eric
Hi Christian,
Bala
Could you please let me know how and where Path=ActualWidth is getting is used in the above
example 2
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.
Thank you very much for this cool idea. To ensure that the ValueConverter is indeed "reached", use the
WPF-Coder
following data binding:
Cheers, Ingo.
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.
i am new to wpf.i think their is no proper decoupling between code behind and design code
vv
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!):
/// <summary>
/// Public method Convert(object value, Type targetType, object parameter, CultureInfo culture)
/// </summary>
/// <returns></returns>
if (Debugger.IsAttached)
Debugger.Break();
else
return value;
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
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.
► Tutorial ► After Effects ► Book Binding ► Book Printing
I have gases
Yo
THANKS A LOT
Atul Raina
More examples
More
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:
{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.
Binding a System.Data.DataTable
Tod
{Binding Path=[my_column_name]}
Nice post
Vikas
why it's look different then what i know?but thanks for the post
loque
Name
E-Mail (optional)
Comment
Post Comment
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
</ObjectDataProvider.MethodParameters>
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#.
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.
Anubisascends
http://www.ageektrapped.com/blog/the-missing-net-7-displaying-enums-in-wpf/
test
tesdt
Name
E-Mail (optional)
Comment
Post Comment
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 )
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;
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>
Jared
Http://www.rhyous.com
What about using Reflection, like "MethodBase.GetCurrentMethod", for giving name of the
Manu Reva
property.
Do we expect performance issue ? or it is just too ugly :-)
Name
E-Mail (optional)
Comment
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.
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
Tools
UI Automation
Comments on this article
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
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
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:
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}" />
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.
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
{
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
@Gnought: Your solution is working, because the "removeListener" isn't executed, isn't it?
Sebastian
if (disposing)
LanguageChangedEventManager.RemoveListener(TranslationManager.Instance, this);
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?
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
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
Steven
xmlns:resx="clr-namespace:MyApp.Properties"
Text="{x:Static resx:Resources.Title}
Doc
But I still wonder, is there an easy way to create this {Translator Resource Binding} dynamically in the code?
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.
Wonderful article.
Griz
Griz
};
which both methods were taken from the Translate classes in the sample.
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 :(
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
Is there a reason why in your sample project the languages are displayed in the combobox as 'German' and
Hi
Klaus
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 "Number of records: 123" where "Number of records:"
comes from the extension and "123" is the number of records in a datagrid on the same window
Regards
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 <Run> within a <TextBlock> to combine fragments to one
string.
Greetings
Christian
I like that very much - Small, lean straight forward. Thanks a lot for sharing - learned some new concepts on your
Stefan
code!
Nice work Christian. Can you tell me, though, why the languages in my sample-project display in the ComboBox
James
as "en" and "de" while they display in your project as "English" and
Hurst
"German"? 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
"de" and "en" 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?!
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:
<ComboBox.ItemTemplate>
<DataTemplate>
</DataTemplate>
</ComboBox.ItemTemplate>
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.
A great article.
I have one question on the use of this markup extension with binding.
For ex.
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
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?
تا�ات�ات�
ا تئنت
Hi Christian,
apo
Hi Christian,
apo
How about if i want to use the translation manager in different assemblies (which consists of different resource
Great
files?
article.
Example:
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?
Name
E-Mail (optional)
Comment
Post Comment
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
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;
}
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);
}
}
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 ?
Very Good.
ZeePrime
Warning with the if, you miss a couple of brackets as && has precedence over ||
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.
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.
Regards
I agree with Olivier as for the missing parentheses in the mouseMove conditions. You should correct it in
david
the main article :p
Hi Christian,
NIkhil
Thanks in advance
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.
on line
listView.Items.Add(contact); ??
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!
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!
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.
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!
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!
Tom Pester
Firstname = firstname;
Lastname = lastname;
To get the code working I had to change the code from (this is a bug IMO)
to
if (e.LeftButton == MouseButtonState.Pressed &&
(
I also got null reference exceptions and had to check the listViewItem for null:
ListViewItem listViewItem =
FindAnchestor<ListViewItem>((DependencyObject) e.OriginalSource);
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.
Hi!
Lasoty
Please show mi how look the Contact class.
TXH
Hi!
Lasoty
Please show mi how look the Contact class.
TXH
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
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
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
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
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
Hi,
Raman
I have tried this program, just used the class "People" instead of "Contact" and it
wors fine. Here is the code that I have tried for the "People":
set
_name = value;
this._name = name;
this._relationshipType = relationshiptype;
public People()
Regards
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
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.
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">
"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
{
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
AVEbrahimi
I've very long startup time in my big WPF project...
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.
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".
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.
Sergey
Andrew, could you share an example of using your class?
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.
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.
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
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?
jep
_sourceUri = new Uri(value.OriginalString); allows garbage collection.
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?
If you want use the MergedDictionary and working Designer, just implement this :
EinMitleser
get
return
(bool)
DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty,
typeof(DependencyObject)).Metadata.DefaultValue;
Hello,
EinMitleser
if you want to use this class in your project without loosing the designer, just impemelent this static
prop into the class:
get
return (bool)
DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty,
typeof(DependencyObject)).Metadata.DefaultValue;
if (IsInDesignMode)
return base.Source;
return _sourceUri
if (IsInDesignMode)
base.Source = value;
return;
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...
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.
I'm also trying to get this working in SL4. Anyone know of a good example?
Coop
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
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.
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.
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.
Name
E-Mail (optional)
Comment
Post Comment
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.
It would have been nice if you took a example and explained step by step. But still its a good article
Goo
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
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
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
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.
Name
E-Mail (optional)
Comment
Post Comment
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
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;
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Adobe Photoshop
Name
E-Mail (optional)
Comment
Post Comment
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
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.
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.
Matrix m = PresentationSource.FromVisual(this)
.CompositionTarget.TransformToDevice;
double dpiFactor = 1/m.M11;
Pen scaledPen = new Pen( Brushes.Black, 1 * dpiFactor );
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.
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.
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.
Sam
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:
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!
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
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.
I have a problem with life. Can you help me out with that?
Mzithra D....
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
Take the time to add a signup system to keep idiots take away from what is a great site
x
Hi Sam,
HatemAmin
You can use the "DrawingBrush" to do such thing, please visit http://msdn.microsoft.com/en-
us/library/aa480159.aspx
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.
Nebogipfel
dc.PushGuidelineSet(gs);
Brush b = 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
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
Hmmm, I checked a "popular" article and reading without comprehension on a mini language, then I
x
noticed the search engine deceiving comments :D
can you please tell me the logic for this? i want to implement this in a vector drawing application
wpf
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/
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.
<StackPanel OverridesDefaultStyle=\"True\">
hi
<Button>
<Button.Background>
</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>
</Button>
</StackPanel>
even my 3 year old child would created this type of scrap application.
rude
Name
E-Mail (optional)
Comment
Post Comment
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;
}
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));
}
var flippedImage = new TransformedBitmap(originalImage, new ScaleTransform( -1,1));
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Adobe Photoshop
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?
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.
Greetings
Christian
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.
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!
memorystream.close();
memorystream.Dispose();
memorystream = null;
ps.: Some Websites recomment that you freeze() the Bitmaps to confirm that the memory is beeing
released after use
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
Ayyappa
We need elaborate description and Examples.
INDIA
Greetings,
Ayyappan,
INDIA,
banyansoft.blogspot.com
Name
E-Mail (optional)
Comment
Post Comment
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
Sachin
Thanks.
Name
E-Mail (optional)
Comment
Post Comment
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
► Tutorial ► Draw ► Adobe Illustrator ► Photoshop Vector
lklkl
m,m,
lklkl
m,m,
nice one
shweta
Name
E-Mail (optional)
Comment
Post Comment
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
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.
<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>
► Tutorial ► Java Web Tutorial ► Learn Quick Books ► Coding Learning
Debug
how now how to paint Star or polygon in the code (in WPF) and I have only
Thank
Debug.....
This is good i think this help to all developer who want to work on WPF
Shekhar
Great work !!
Achilles
This is good. But I like to know how to design 3D objects using Expression Blend.
Jawahar
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...
232
rer
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
Caro,
Rafael
podes me ajudar?
tenho uma serie de pontos e preciso plotar uma superfÃcie e rotaciona-la e aplicar zoom.
No aguardo.
Friend,
Rafael
can you help me?
I have a series of plot points and need a surface and rotate it and zoom.
i want to write the PROPEQUITY in 3d and import XAML, can you tell me wht is the xaml code. pls ....
Chetan
Supa nice
Johnson
<Viewport3D>
kondsreddy
<Viewport3D.Camera>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup>
<GeometryModel3D>
<GeometryModel3D.Geometry>
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.Material>
<DiffuseMaterial Brush="Red"/>
</GeometryModel3D.Material>
</GeometryModel3D>
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
hmm
at
jenny
i tried to create simple 2 buttons in Viewport3D, like this:
--------------------------------------------------------------
<Viewport3D.Children>
<Viewport2DVisual3D>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D
TriangleIndices="0,1,2 2,3,0"
/>
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True"
Brush="Red"/>
</Viewport2DVisual3D.Material>
</Canvas>
</Viewport2DVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
<Viewport3D.Camera>
<PerspectiveCamera FarPlaneDistance="20"
LookDirection="0,0,-1"
UpDirection="0,1,1"
NearPlaneDistance="1"
Position="0,0,5"
FieldOfView="45"
/>
</Viewport3D.Camera>
</Viewport3D>
----------------------------------------------------------------------
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 "two" height from 60 to 100 , button
"one" becomes smaller???
tnx jenny
jenny
i tried to create simple 2 buttons in Viewport3D, like this:
--------------------------------------------------------------
<Viewport3D.Children>
<Viewport2DVisual3D>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D
TriangleIndices="0,1,2 2,3,0"
/>
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True"
Brush="Red"/>
</Viewport2DVisual3D.Material>
</Canvas>
</Viewport2DVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
<Viewport3D.Camera>
<PerspectiveCamera FarPlaneDistance="20"
LookDirection="0,0,-1"
UpDirection="0,1,1"
NearPlaneDistance="1"
Position="0,0,5"
FieldOfView="45"
/>
</Viewport3D.Camera>
</Viewport3D>
----------------------------------------------------------------------
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 "two" height from 60 to 100 , button
"one" becomes smaller???
tnx jenny
jenny
i tried to create simple 2 buttons in Viewport3D, like this:
--------------------------------------------------------------
<Viewport3D.Children>
<Viewport2DVisual3D>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D
TriangleIndices="0,1,2 2,3,0"
/>
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True"
Brush="Red"/>
</Viewport2DVisual3D.Material>
</Canvas>
</Viewport2DVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
<Viewport3D.Camera>
<PerspectiveCamera FarPlaneDistance="20"
LookDirection="0,0,-1"
UpDirection="0,1,1"
NearPlaneDistance="1"
Position="0,0,5"
/>
</Viewport3D.Camera>
</Viewport3D>
----------------------------------------------------------------------
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 "two" height from 60 to 100 , button
"one" becomes smaller???
tnx jenny
jenny
i tried to create simple 2 buttons in Viewport3D, like this:
--------------------------------------------------------------
<Viewport3D.Children>
<Viewport2DVisual3D>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D
TriangleIndices="0,1,2 2,3,0"
/>
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True"
Brush="Red"/>
</Viewport2DVisual3D.Material>
</Canvas>
</Viewport2DVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
<Viewport3D.Camera>
<PerspectiveCamera FarPlaneDistance="20"
LookDirection="0,0,-1"
UpDirection="0,1,1"
NearPlaneDistance="1"
Position="0,0,5"
FieldOfView="45"
/>
</Viewport3D.Camera>
</Viewport3D>
----------------------------------------------------------------------
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 "two" height from 60 to 100 , button
"one" becomes smaller???
tnx jenny
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
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
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
I have a question
alan
@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
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
UI Automation
Show all comments
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:
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
Nice tutorial
Iyappan Mani
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
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
Does a round gauge control (controls for WPF) uses animation to move the indicator??? thanks
Qualitatserz...
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
MOSER
from another website
I apprieciate your feedback but I cant explain it anymore in depth because I just copy and pasted this
MOSEY
from another website
Good
subbu
Rev
Cool Article, but I have real big problem with animations.(its about framrates)
Hi
raj
Cool Article, but I have real big problem with animations.(its about framrates)
GOOD TUTORIAL..
shivraj...
Name
E-Mail (optional)
Comment
Post Comment
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'
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
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Adobe Photoshop
0
o
aa
Aa
MooningGloub
Name
E-Mail (optional)
Comment
Post Comment
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"
Thanks
Soundar
thanks
tarun
Thanks !!
Anil
Hi!Thanks
ngocanhk6apro
Name
E-Mail (optional)
Comment
Post Comment
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... :-(
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
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?
pretty much
cortisol
You could release the source code of this application (screenshot) for
Flavio
download?
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
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??????
Hi,
Sreekumar
Can you please complete this article........
Danke für den Link zur Windows7api.pdf, war sehr hilfreich. Spitzen Homepage, immer
Tiberius
ein Quell an Inspiration für mich!
Lmaa
There is Code for you
Can u please complete this atical, and show how to use it.
Ahtesham
reagrds thanks.
Name
E-Mail (optional)
Comment
Post Comment
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
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
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. (???)
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!!
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.
Greetings
Christian
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.
Hi Tim,
Christian
Moser
check out this Expression Blend Behavior: http://gallery.expression.microsoft.com/en-us/GlassBehavior
Greetings
Christian
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
Implementation in VB.NET:
Ankit
Malhotra
Imports System.Drawing
Imports System.Runtime.InteropServices
<DllImport("dwmapi.dll", CharSet:=CharSet.Auto)> _
End Sub
'End Structure
InitializeComponent()
border_extensions.Bottom = 300 'amount of border extension required from the bottom border
DwmExtendFrameIntoClientArea(Me.Handle, border_extensions)
End Sub
'' painting the areas in client regions in black..if these fall in the margins described u would get
'' glass effect!
End Sub
End Class
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.
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..??
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?
thank,s
saman
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?
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
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.
cxv
vcxv
There are a couple of lines of code missing in your example to make it perfect.
Evans
First:
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
source.AddHook(new HwndSourceHook(WndProc));
Name
E-Mail (optional)
Comment
Post Comment
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
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
{
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
Andira
how about Form?
Muttakim
Andira
how about Form?
Muttakim
It does also work in Windows Forms under a .NET 4.x and Win7 environment.
Mario Fraiß
Martin
e.g. Have a command on the list (Red) that changes the background color of the form to Red?
can jumplist support custom event like just calling a method inside the owner
K
Name
E-Mail (optional)
Comment
Post Comment
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.
► Tutorial ► Learn Quick Books ► Basics ► Coding Learning
oyeeee
After you couldn't find 50 performance tips, you switched to a Top 10.
Roman
And now you're showing us a Top 9 ??
Hi Roman,
Christian Moser
sorry for that. I added the missing 10th :-)
Great article, keep up the good work, your blog is a very informative and useful.
Ben Dover
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.
Radenko Zec
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.
How much cash .. mind sharing..lol..J/K.. keep up the hunting for us. you should call this WPF HUB
Mysticool
It works in Silverlight
Denis
12. x:Name only the elements you need to use from code-behind or want to "Control2Control" bind.
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
Which will be better ?...to write code in c# or xaml to get good peformance
Tinoy Malayil
hi
Tip 5: What is the word Thow? Pretty sure this doesnt even exist in the americanized incorrect version
Darren Bruce
of the english language
small correction in 6:
Musab Ahmed
ScrollViewer.CanContentScroll="False" instead of CanContextScrol="True"
Ali
Tip 4: "setting AllowsTransparency to true can cause WPF to render the UI in software on
len
Windows XP, which is much slower." -- Is it still true for now? Is there any fix for it?
good
adee.
Name
E-Mail (optional)
Comment
Post Comment
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
Twain, stopping the transaction and extracting a confession, then leaving Twain bound in Pseudoderm. ,
Mr.Carrot67
Name
E-Mail (optional)
Comment
Post Comment
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
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.
5. Blend imports the file now. Each layer will create a new Image or Path element. The images will automatically be added to
To convert imported Path objects to Geometry objects that can be consumes as resources you have to do the following steps:
2. Create a StreamGeometry object and paste the content between the opening and closing tag. Give the geometry a
unique key.
3. Open the Options Dialog in "Edit->Options->Clipboard(XAML)" and choose if you want to export shapes as Canvas or
Resource Dictionaries.
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.
► Tutorial ► Adobe Photoshop 6 ► Photoshop CS4 ► Photoshop Brushes
Again, your tutorials are imbued with visuals making it extremely easy to read and understand. Excellent
Jeffrey
work!
nice work
satish v
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!!!
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
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
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.
Wire-up navigation
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...
► Tutorial ► Photoshop Brushes ► Tablet Drawing ► Photoshop Vector
Excellent work...
Mukesh
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
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!
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!
Thank you - this was very helpful in getting me started. Clear, concise and just enough info to point me in
Shazzas
the right direction.
Orale Carlitos! Me parece una buena introduccion a esto. Me parece que es una buena manera de darle
El Gran...
un pepinillo al cliente.
Very nice post! I'm loving WPF more and more because of you! Thank you very much!
Genesis
SilverBlend
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
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
Windows 7
Interoperability
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
Hi Austin,
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..
shuchita
kindly help me.
saxena
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
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.
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
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
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
Tools Bjoneskc
http://www.dotnetuidevelopment.com/aurora.htm
UI Automation
Name
E-Mail (optional)
Comment
Post Comment
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
Documents
Windows 7
Is there any Free Online Book .for Web Application through WPF.
Kuldeep
Name
E-Mail (optional)
Comment
Post Comment
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
2D Graphics
3D Graphics
Comments on this article
Animation
UI Automation
Rakesh Dora , plz maintain sanctity of the forum and behave urself.
Ramesh
hello, i work as a Business Analyst, but i have the task to prototype using an external IDE by Mobiform's
mumshad
Thanks In Advance
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
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.
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
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.
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
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 !
seems really interesting thanks for your efforts to make this material available for us
i
Nice one
Arjun
Asha.MP
in the above properties we can specify the colors also, what is the meaning of TemplateBinding in the
above property??
nice...
siva
very nice.
bala
good one
Tejas
So Clear nice
bm
I want to create Template for TextBox. How can I aceess RelativeSource TEXT property.
Alibaba
@Alibaba: If I am understanding you correctly, you would not use RelativeSource to bind to the text
stigma
property. You would use "{TemplateBinding Text}". For example:
Using a TextBox inside a TextBox ControlTemplate, however, I have found to be very unhelpful. Try
using: <ScrollViewer x:Name="PART_ContentHost"/> If you name the ScrollViewer
exactly as I have here, the text will be bound to it. No other work required.
Life Saver :)
Ziad
Viva linux!!
Gonzalo
Name
E-Mail (optional)
Comment
Post Comment
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
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".
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>
► Tutorial ► Learn Quick Books ► Data Networking ► Coding Learning
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.
useless.
Avishek
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.
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.
Yogesh
Also how it is binded to Employee objects?
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).
A good example to create a data template for a beginner. But how to set the template to the listbox.
Mukil
'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".'
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.
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.
would there be any sample for same..? though it looks like gud sample but may be difficult for a
crazycopboy
beginner..
sirs, this is what i wants. can you please send all the code to me please
IndianBoy
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!
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 :)
very good
babu
Name
E-Mail (optional)
Comment
Post Comment
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>
<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
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.
Hi,
Patrick
How can i apply animation for a selected listitem? Such as the zone out the selected itme.
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>
</Grid.ColumnDefinitions>
</Grid>
Hi I followed the example on this page to get right aligned in a text box, but having troubles
someone
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
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>
<Grid x:Name="LayoutRoot">
<ListBox Style="{StaticResource myListboxStyle}" />
</Grid>
► Tutorial ► Photoshop CS4 ► Photoshop Brushes ► Photoshop Editing
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.;
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!
kpatil
To add more, If you want to change the TextColor use
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
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...
@Homer:
Neztnerol
No, it only replaces the system color key for the control that uses the style template "myListboxStyle"
Style="{StaticResource myListboxStyle}"
I,
Gally
I'm looking for an other solution on windows phone 7 with Silverlight because <Style.Resources>
doesn't exist.
Just what I was looking for and so neatly done. Thanks Christian
Karin
GRANDE!!!!
Alfredo...
Exactly what I was looking for! New to WPF and your site is the main site when I need to out figure
Mustafa
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).
...
</SolidColorBrush>
...
Armando
Rocha
Thanks
Aditya Kiran...
Hey Thanks alot.. your site is damn good. it is very helpful.
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 ?
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
Post Comment
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
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.
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Brushes
good
janu
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">
</Application.Resources>
</Application>
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
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")]
► Tutorial ► Photoshop CS4 ► Photoshop Action ► Photoshop Vector
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
Does it work in Windows versions less then Vista (XP, Server 2003)?
konstantin
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.
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
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
RomanK
Do you by chance also know how to remove the window title?
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">
The SendMessage solution does not remove the icon in VisualStudio 2010 in XP.
Gorkster
a trick of lazy:
Max
WindowStyle="ToolWindow"
midspace
Requires both SetWindowLong and SendMessage.
re: WindowStyle="ToolWindow"
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
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