Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET 4.5
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Amazon Web Services
Analysis Services
Android
Architecture
Arduino
ASP .NET Web API
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
BDD
Big Data
Bing
BizTalk
Book Excerpts
Build and Deploy
Business Intelligence
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE Framework Info - non Technical
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Debugger
Design Patterns
Development Process
Display Technologies
Distributed Computing
Document Database
DotNetNuke
DSL
Dynamic Languages
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
HTML 5
Internet Explorer 8.0
Interviews
IOS
iPhone
Iron Ruby
Java
Java Script
JavaScript
jQuery
JSON
Lightswitch
LINQ
Linux
LUA
Mac OS X
MDX
Messaging
Metro
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
MVVM
MySQL
Network
NHibernate
node.js
NOSQL
Nuget
Object Oriented Development
Objective C
Odata
OLAP
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
PHP
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Prolog
Python
Q&A
Rails
Rake
Razor
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Scheme
Search
Security
Services
SharePoint
SignalR
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server 2012
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
TFS
Tips
TypeScript
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 11
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio 2011
Visual Studio 2012
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WebMatrix
WF
Whitepapers
Windows 7
Windows 8
Windows Azure
Windows Live
Windows Phone 7
Windows Phone SDK
Windows Server
Windows Vista
WinForms
WinRT
Workflow
WPF
XAML
Xiine Documentation
XML
XNA
XSLT



LearnNow


XAMALOT
 


SSWUG

Reader rating:
Click here to read 1 comment about this article.
Article source: CoDe (2009 Jan/Feb)


Article Pages:  1  2 3 4 - Next >


Flexible and Powerful Data Binding with WPF, Part 2

All applications are dependent on data in some form and most developers find themselves writing reams of data access code. Microsoft has been building databinding frameworks for years. Each one promises to solve our databinding woes forever. We’re still waiting for the perfect one. In the Nov/Dec 2008 issue of CoDe Magazine you were exposed to programmatically controlling data binding mechanisms of WPF. Along with a programmatic interface, WPF also provides a declarative databining interface. This second article will introduce you to using the declarative data binding mechanisms contained in WPF.

XAML Binding

It’s possible to set up a binding in XAML only. The XAML parser understands how to parse and instantiate many of the WPF framework classes. It doesn’t know how to work with non-WPF classes unless they are registered with the parser. Therefore, the first step in using a custom data source is to associate an XML namespace with a CLR namespace. The following XAML snippet shows how to set up an xmlns “sys” namespace for the System namespace in mscorlib and a “local” namespace for a custom assembly:

<Page
xmlns:sys='clr-namespace:System;assembly=mscorlib'
xmlns:local='clr-namespace:MyLib' />

Next you need to create an instance of the type and store it in a discoverable location. In C#/Visual Basic you would create a variable and instantiate the type. In XAML you have to put the instance in a resources section. The XAML parser instantiates your type and adds the instance to the resource dictionary. You provide a key for the resource so that you can retrieve the instance later:

<Page.Resources>
  <!-- Instantiate a string
         and load into resource dictionary -->
  <sys:String x:Key='sample'>ABC 123 DEF 456
  </sys:String>
 
  <!-- Instantiate a employee
         and load into resource dictionary -->
  <local:Employee x:Key='emp'
                  FirstName='Jimmy'
                  LastName='Crickett'
                  Salary='2500'
                    />
</Page.Resources>

Now it is time to set up the binding in the main part of the page and employ the Source property for the configuration. Set the Source property to refer to an instance of an object, in this case the sample string declared in the Page.Resources section shown previously. Bind the first TextBlock directly to the string and use a Path for the second TextBlock to show the second Char in the String.Chars array:

<TextBlock
  Text="{Binding Source=
     {StaticResource sample}}" />
<TextBlock Text="{Binding
  Source={StaticResource sample},Path=[2]}" />

The next example shows comparable XAML for binding to the Employee object:

<TextBlock
     Text="{Binding Source=
        {StaticResource emp},Path=LastName}" />

Relative Source Binding

It’s not necessary or desirable to name every element in a WPF logical tree. This poses a problem when binding to other elements. Use the ElementName property to specify a named element as the source. There are times when you won’t know the element name but you’ll want to bind to it anyway.

Sometimes you just want to say; "Bind to my parent StackPanel" or "Bind to the previous item in this list". You may not know the names of these elements, but you want the data anyway. Another example is when you want to bind to a property on the same element. Could there be a way to configure this same element binding without requiring an element name?

Use the RelativeSource property when you need an element binding, but you can’t use the ElementName property. There are four modes available for RelativeSource bindings. I’ll explain two of the modes below (the other two aren’t relevant to this article):

Self: Reference any property on the current object. The next example shows some XAML that binds the TextBox Background property to the Text property on the same TextBox. Note the nesting of one markup extension within another in this example. Run the application and try typing “Red” or #FF336688 in the text box to see the background color change:

<TextBox  Text='#FF55FFCC'      
  Background='{Binding Text,
  RelativeSource={RelativeSource Self }}'/>

FindAncestor: Walk the tree of parent elements looking for a specific type of element. You must specify the AncestorType, a DockPanel in this example, for a successful binding. Use the AncestorLevel to skip over parent levels. For example setting AncestorLevel=2 will skip one generation. In the following example the TextBox Background will bind to the grandparent DockPanel and will be blue:

<DockPanel Background='Blue'>
  <DockPanel Background='Green'>
    <TextBox Margin='20'
         DockPanel.Dock="Top"
         Background='{Binding Background ,
    RelativeSource={RelativeSource FindAncestor,
         AncestorType=DockPanel ,
         AncestorLevel=2}}' />
    </DockPanel>
</DockPanel>

The other two RelativeSource modes are TemplatedParent and PreviousData, which are not relevant to this article.

Binding Direction

When you configure a binding you can influence the direction that the data flows. A common binding direction is from the source to the target. This is implemented with the BindingMode.OneWay enumeration setting. In a OneWay binding, the target property is updated when the binding source changes. Remember that change notification only happens if the data source object notifies WPF about the changes. See the Change Notification section earlier in this article for details.

OneWay direction is common if the target is a non-editable element like a TextBlock or Label. Since the user cannot change the value, it’s not necessary for the data to flow back to the source:

<TextBlock Margin='20'
           Background='LightGray'
           Text="{Binding Source=
             {StaticResource emp},
              Path=FirstName,
              Mode=OneWay}" />

In a BindingMode.TwoWay binding, the target property is updated when the source property changes and vice versa. TwoWay is common when the target is an edit control like Slider or TextBox.

What if you don’t specify a value for the Mode property? What type of binding direction will you get? The answer is that it depends on the type author preferences. Each dependency property has a FrameworkPropertyMetadataOptions enumeration flag set. If you’ve set the BindsTwoWayByDefault value then the default is TwoWay, otherwise it will be OneWay. The TextBox default Mode is TwoWay. Most other controls are OneWay by default.

In a BindingMode.OneTime binding, the target property is updated once, when the system establishes the binding. The WPF dependency property system disconnects the binding after it sets the initial value and the system does not forward further changes. Usually you’ll use this mode to reduce overhead if you know the value won’t change in the source property.

In a BindingMode.OneWayToSource binding the data flows from the target property to the source property. It is still a single direction binding. In other words, no data flows back to the target. OneWayToSource exists to solve one particular problem in the WPF binding world. Data target properties are always dependency properties. There are no exceptions to this rule.

Occasionally you’ll run across an element that has a property that you want to use as a target, but you discover that it wasn’t implemented as a dependency property. The Run element is a classic example of this problem. A Run is a subsection of a FlowDocument. Run elements allow you to break a big document into manageable sections and apply formatting or modify the Run text from your code:

<StackPanel>
  <FlowDocumentPageViewer Height='300'>
    <FlowDocument>
      <Paragraph>
        <Run>Intro Text</Run>
        <Run x:Name='changeMeRun'>
           Lorem Ipsum</Run>
      </Paragraph>
    </FlowDocument>
  </FlowDocumentPageViewer>
  <Button x:Name='ChangeTextButton'
          Click='ChangeTextButton_Click'
          Content='ChangeText' />
</StackPanel>

In the code behind, change the Run as shown here.

In C#:

changeMeRun.Text = 
DateTime.Now.ToLongTimeString();

In Visual Basic:

changeMeRun.Text = DateTime.Now.ToLongTimeString()

Now imagine that you want to bind a TextBox to the Run element. Sorry, you can’t do that with a OneWay or TwoWay binding. Since Run.Text is not a dependency property, you’ll have to use a OneWayToSource binding instead. Here’s some XAML that demonstrates this binding:

<TextBox
  Text='{Binding
  ElementName=changeMeRun,
  Mode=OneWayToSource,
  Path=Text}' />
&

By: Walt Ritscher

Walt Ritscher has trained thousands of corporate developers during the last twelve years. An active speaker, his teaching schedule has taken him throughout the world providing developer training at corporations, universities, and software conferences. He has collaborated on several books and videos published for the developer market including early adopter .Net courses at Microsoft Press. Walt is currently consulting and teaching .NET and WPF classes for Wintellect. Walt's industry expertise has placed him on various national technology advisory boards. He is also deeply involved in the local developer community-founding the .NET Developers Association in Redmond, WA. Walt has accumulated plenty of experience as a developer and is currently a Microsoft MVP and a member of the Silverlight Insiders. As a Web programmer he has worked numerous projects including: EPA sites and the Microsoft Community Starter Kit.

waltonline@scandiasoft.com

Fast Facts

WPF is a complete rethinking of how to construct a UI development platform. Since Microsoft started with a blank slate, it provided the WPF architects with the opportunity to engineer interesting ideas into their binding engine.



Article Pages:  1  2 3 4 - Next Page: 'Binding Updates' >>

Page 1: Flexible and Powerful Data Binding with WPF, Part 2
Page 2: Binding Updates
Page 3: Business Class Validation
Page 4: ValidatesOnDataErrors

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
3.3 out of 5

11 people have rated this article.

Instantly Search Terabytes Of Text
“Lightning Fast”
– Redmond Mag
“Covers all data
sources” – eWeek
25+ fielded & full-text search options
dtSearch’s own document filters highlight hits in popular file types
Web Spider supports static & dynamic data
APIs for .NET, Java, C++, SQL, etc.
Win / Linux (64-bit & 32-bit)
www.dtSearch.com
 

      AppsWorld Europe

 

SSWUG