Subodh Pushpak’s Blog

Technical musings on .Net, silverlight, WCF and DLR

What’s the deal with dependency properties?

Posted by subodhnpushpak on December 13, 2009

With in a span of last few weeks; more people have asked me the same question over and over again –

Below is my rant on the same:

  • what’s the deal with dependency properties?

I seriously think that dependency properties is one thing which didn’t get the respect and attention it deserved. I mean when i first discovered it; i was in awe!!  Its such a strong concept that i was mesmerised by both its power and even based few of my “design” on its principle!! for a understanding on DPs consider my previous blog in DP!!

What is the difference between using methods and properties? Well; plain properties ARE at the end the days get_*() and set_*() methods;then why use a property? 

First and foremost; properties encapsulate calls to the methods (and thus make a piece of code a component!!) – that is well understood!! however; there is another way to look at it.

There is a need to invoke and declare component in some kind of serializable (declarable) standard (think aspx, XAML, XML) which “templatize” code without the need to explicitly write code to invoke methods from “code-behind”. The only answer is to make properties which can be use declaratively. For example: Animations can be defined declaratively in XAML itself because of DPs. Imagine if DPs was not around; we will be needing loads of “code behinds” to make things work!! Button, class for example have 78 out of Button’s 96 properties as dependency properties,… Properties can be easily set in XAML (directly or by Blend) without any procedural code

Even more intriguing is the fact how easily we can implement Inversion of Control (dependency Injection) using the same!! I have wondered that’s why it is called dependency property??for e.g.:

Attached properties like <Button Canvas.Top="10" />.

Instead of Canvas class deciding where the button should be placed, Button class is responsible for  positioning itself with respect to Canvas class… the dependencies have been reversed!! by the way in code behind the above code will be like: Button.SetValue(Canvas.TopProperty, (double)10.0);

by the way; I always had thought that i have a clear understanding of the Attached properties and dependency property and Attached property is a special case of dependency property until i came across this blog by silverlight Geek Jesse Liberty. I was convinced that the above is attached property; but as you can see in the blog; Tim Heuer prefers calling it an dependency property!! and it all depends how we look at it!!

  • why can’t CLR properties behave like DPs?

The difference is that CLR properties are understood by the compiler, they are part of the language, whereas DPs are purely implementation being part of the framework rather than the language. The compiler has no understanding of DPs hence there is no shorthand available. Notice “DependencyProperty.Register” while declaring a DP….

  • DP’s CLR property wrappers should  not contain any logic in addition to the GetValue/SetValue calls.

CLR property wrapper provide convenience at compile-time; At run-time XAML calls the underlying GetValue and SetValue methods directly!! Therefore, to maintain parity between setting a property in XAML and procedural code..

Consider below code:

// ExtendedStackPanel  implementing a DP

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DP
{
    public class ExtendedStackPanel : StackPanel
    {
        public string MyProperty
        {
            get {
               MyProperty = "This is never executed!!";
                return (string)GetValue(MyPropertyProperty); }
            set {
                value = "changed value by writing code in CLR property encapsulating DP, who needs a callback for DP. But think when someone calls it from procedure code as object.SetValue() directly !!";
                SetValue(MyPropertyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc…
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(string), typeof(ExtendedStackPanel), new PropertyMetadata("default"));
    }
}

calling the above clas in main XAML as

<StackPanel x:Name="LayoutRoot">
       <DP:ExtendedStackPanel x:Name="sp" MyProperty="This is a heading set as DP!!" Background="Aqua">
           <ContentPresenter Content="{Binding ElementName=sp, Path=MyProperty}" ></ContentPresenter>
       </DP:ExtendedStackPanel>
       <DP:ExtendedStackPanel x:Name="sp1"  Background="AliceBlue">
           <ContentPresenter Content="{Binding ElementName=sp1, Path=MyProperty}" ></ContentPresenter>
       </DP:ExtendedStackPanel>
</StackPanel>

and code behind:

this.Loaded += new RoutedEventHandler((o,e)=>
            {
                // this will NOT call the wrapper property around DP!!
                sp1.SetValue(ExtendedStackPanel.MyPropertyProperty, "this is text value set from procedural code!! does NOT calls CLR property !! Code written in CLR property is not even executed!!");
            });
            // does not return "This is never executed!!"; as you will expect!!
            string s = sp.MyProperty;

I have uploaded the full code here for above code; in case you want to play around with it!!

All in all; XAML was a big leap forward on top of .net 2.0 because of “Eventing system” and “property system”. If it hadnt been for a strong concept like DPs; declarative languages like XAML would not have been possible.  I wish i could go on and on about use an efficient sparse storage system in DPs and use of static. But to keep focus on ONLY answering the question i must end here.

Please do provide your feedback…

Technorati Tags: ,

Posted in Uncategorized | Leave a Comment »

Silverlight 4.0 is here!!

Posted by subodhnpushpak on November 20, 2009

Silverlight has come to an age from WPF/E days and today 4.0 version was launched.

Features includes:

Support for enterprise applications:

Printing support: Silverlight application can print itself, how the content is formatted when printed, and determine the content that will appear. It even has capabilities to print a portion of the Silverlight content.

RichTextArea control / WebBrowser Control: The RichTextArea has Bi-Di support, allows hyperlinks, XAML content, and embedding of images. It also supports changing the font size, foreground color, and making text bold, italicized, and underlined as well as many other rich text features. The WebBrowser control displays HTML in the control when running Out-of-Browser

WCF RIA services: Exposes an object model on the server through an optimized .NET to .NET binary format as well as an open JavaScript Object Notation (JSON) format to Silverlight application. WCF RIA Services has features to assist with change tracking on the client in Silverlight, user authentication, and personalization ( a la EDM change tracking system for integration with DB!!!)..

MEF suuport: Deploy application in multiple Silverlight applications (XAP) files. This allows the XAP files to be dynamically downloaded at runtime. MEF allows applications to be context-aware where the available parts change based on the state of the application. It also improves the general maintainability of Silverlight applications by greatly introduce loose coupling between its components.

InBuilt support for MVVM: Command Property on ButtonBase and Hyperlink

IDataErrorInfo, INotifyDataErrorInfo : Get errors when (data) bindings fails.

Auto-Sizing Columns and Copy from DataGrid

Navigation Page Loading Extensibility: introduces MVC-style navigation

Excellent data binding support through XAML code: Binding to String Indexers / SelectedValue and SelectedValuePath on the Selector / StringFormat, TargetNullValue, FallbackValue:

Databinding Support for Dependency Objects: Allows bind properties on a DependencyObject (DO) and not just on FrameworkElements.

CompositeTransform for animations:

ObservableCollection<T> Constructor Accepts IList and IEnumerable :

Inbuilt MouseWheel Support:

Right Mouse Click:

Programmatic Clipboard Access:

Webcam and Microphone Support:

Offline Digital Rights Management

Notifications (Toast)

File System Access / COM automation for trusted applications: If both return true and Microsoft Office is installed, you can create an instance of an object such as Microsoft Word

Cross-Domain Networking Access: An Out-of-Browser Trusted Application can perform cross-domain network calls.

It could NOT have been better than this… i wished i had all these features for a silverlight application(currently in SL3) i am involved in and SL team has delivered!!

Will be blogging more on these once a have more time…

Technorati Tags:

Posted in Uncategorized | Leave a Comment »

Management is Doing Things Right, Leadership is Doing the Right Things

Posted by subodhnpushpak on September 26, 2009

 

I am recently involved in a project which involves reengineering a system which has out grown over more than 7 years.

I was having a tough time just comprehending such a task as most of the requirement was coming as “design” use cases of previous implementation. So here is what i referred to: Big write by Chad Fowler: Here is a reproduction of his work for reference:

"Make it do what it already does." That’s a tempting and simple way to view software requirements on a rewrite project. After all, the system already exists. The question of "what should it do when…" can presumably always be answered with: "what it already does".

There are two major problems with this assumption.

  • The first, and most disruptive, is that the programmers don’t know what questions to ask.
  • With the fragile safety net of an existing implementation, programmers can easily oversimplify the interface, and assume they know the capabilities of the system.

Solution:

  • If there is a  software that is complex enough that it needs to be rewritten, it’s probably also so complex that it’s not discoverable in this way.
    • This means that domain experts are going to have to be heavily involved.
      • It means that requirements are going to need to be communicated in much the same way they are on a green-field project.
        • And it means that, unless it’s only used as a supplement, the existing system is more a liability to the rewrite than an asset.

Optimistic programmers might think I’ve missed something important here. If you’re rewriting a system, you’ve already got the code. The code can serve as the spec, right? Probably not.

I will also like to quote another excellent book “The Mythical Man-Month” by Fred Brooks which states the “Second System Effect”, i am particularly wary about.

The second system that an architect designs is the most dangerous system he will ever design since he will tend to incorporate all of the additions he originated but did not add (due to the inherent time constraints) to the first system. Thus, when embarking upon a second system, an engineer should be mindful that he is susceptible to over-engineering it.

By the way the “The Mythical Man Month” also provides an estimation insight as in Brooks’s law [adding manpower to a late software project makes it later]

  • Group Intercommunication Formula: n(n − 1) / 2
  • Example: 50 developers give 50 · (50 – 1) / 2 = 1225 channels of communication.

i got into reading into Chad Fowler when i found “The Passionate Programmer: Creating a Remarkable Career in Software Development

That was when i realized that i was NOT enjoying my work as architect[as it was abstract with NO coding] and wanted to know what lies for people like me; specially in India. [Ironically, The first edition of the book was released as My Job Went to India: 52 Ways To Save Your Job ]. Anyway, I was immediately hooked to the book.

He says “The important thing to realize is that change is not only possible in your career but necessary. As a software developer, you would never want to pour yourself into developing something your client doesn’t want. Agile methodologies help prevent you from doing so. The same is true of your career. Set big goals, but make constant corrections along the way. Learn from the experience, and change the goals as you go.”

I chose AGILE. I choose to change and go for an organization which has ample of opportunities for coder in me over a “well-defined architect role” . And here i am spreading the word of AGILE following “Better Than Yesterday” methodology. I wish everyone could read Fred instead. After all, i am doing the right thing!! :D

Posted in Uncategorized | Leave a Comment »

Architect / leader / Manager or All-in-One??

Posted by subodhnpushpak on September 21, 2009

I stumbled on an article here, and could help but to agree more on the same. The thought is just awesome and almost echoes what i was thinking for long but i was always in loss of words.

Initially, I shunned the very thought of managing people and getting more into managing timelines, schedule and execution of the project. I looked for the role if Individual Contributor (IC) and quickly discovered that the role is almost non-existent for mere mortals like me!!

So, i decided to train myself in Leadership and while i am yet into it and get down to level of doing a part time MBA i figured out that there is much more work which i need to do than i imagined.

There is a set notion about architects:

  1. There is set architecture solution for every problem (its same n-layered architecture and yes i-know-we-have-MVC-in-Presentation-Layer syndrome).
  2. Architects know how to talk technologies. They are BAD business communicators. [So if you call a business flow a USE-CASE or stakeholders a ACTOR… You will have it!!! ]
  3. Architects DO NOT code. They define what technologies to use and what the latest jargon round the corner.

All the above points cannot be more incorrect from truth.

1. Every solution is diverse even if it is from 30,000 feet view. Architect need to to think beforehand about the problem in hand, the bottlenecks which may be there and a solution for that.

2. Architects are the bridge between the BIG chasm of business and the technology. They have to talk both the languages and somehow manage the collaboration among all the business and the technology stakeholders.

3. Architects certainly do POCs. They are smart coders who are always challenging code and push it to limits. While they must know new technologies; they need to have more deeper insight into technology.

4. Architect also need to provide more insights while providing time, effort estimates. They should also know team members strengths so they have best team on job while project is executing.

5. Architect need to be educate the client about the limitations of the technology and at the same time educate the developers about the power of the technology.

Keeping above in view i have followed the below mantras quite successfully. Its 12 Rules for Self management and leadership by Rosa Say.

12 rules for self-management

  1. Live by your values, whatever they are. You confuse people when you don’t, because they can’t predict how you’ll behave.
  2. Speak up! No one can "hear" what you’re thinking without you be willing to stand up for it. Mind-reading is something most people can’t do.
  3. Honor your own good word, and keep the promises you make. If not, people eventually stop believing most of what you say, and your words will no longer work for you.
  4. When you ask for more responsibility, expect to be held fully accountable. This is what seizing ownership of something is all about; it’s usually an all or nothing kind of thing, and so you’ve got to treat it that way.
  5. Don’t expect people to trust you if you aren’t willing to be trustworthy for them first and foremost. Trust is an outcome of fulfilled expectations.
  6. Be more productive by creating good habits and rejecting bad ones. Good habits corral your energies into a momentum-building rhythm for you; bad habits sap your energies and drain you.
  7. Have a good work ethic, for it seems to be getting rare today. Curious, for those "old-fashioned" values like dependability, timeliness, professionalism and diligence are prized more than ever before. Be action-oriented. Seek to make things work. Be willing to do what it takes.
  8. Be interesting. Read voraciously, and listen to learn, then teach and share everything you know. No one owes you their attention; you have to earn it and keep attracting it.
  9. Be nice. Be courteous, polite and respectful. Be considerate. Manners still count for an awful lot in life, and thank goodness they do.
  10. Be self-disciplined. That’s what adults are supposed to "grow up" to be.
  11. Don’t be a victim or a martyr. You always have a choice, so don’t shy from it: Choose and choose without regret. Look forward and be enthusiastic.
  12. Keep healthy and take care of yourself. Exercise your mind, body and spirit so you can be someone people count on, and so you can live expansively and with abundance.

12 rules for self-leadership:

  1. Set goals for your life; not just for your job. What we think of as "meaning of life" goals affect your lifestyle outside of work too, and you get whole-life context, not just work-life, each feeding off the other.
  2. Practice discretion constantly, and lead with the example of how your own good behavior does get great results. Otherwise, why should anyone follow you when you lead?
  3. Take initiative. Volunteer to be first. Be daring, bold, brave and fearless, willing to fall down, fail, and get up again for another round. Starting with vulnerability has this amazing way of making us stronger when all is done.
  4. Be humble and give away the credit. Going before others is only part of leading; you have to go with them too. Therefore, they’ve got to want you around!
  5. Learn to love ideas and experiments. Turn them into pilot programs that preface impulsive decisions. Everything was impossible until the first person did it.
  6. Live in wonder. Wonder why, and prize "Why not?" as your favorite question. Be insatiably curious, and question everything.
  7. There are some things you don’t take liberty with no matter how innovative you are when you lead. For instance, to have integrity means to tell the truth. To be ethical is to do the right thing. These are not fuzzy concepts.
  8. Believe that beauty exists in everything and in everyone, and then go about finding it. You’ll be amazed how little you have to invent and much is waiting to be displayed.
  9. Actively reject pessimism and be an optimist. Say you have zero tolerance for negativity and self-fulfilling prophecies of doubt, and mean it.
  10. Champion change. As the saying goes, those who do what they’ve always done, will get what they’ve always gotten. The only things they do get more of are apathy, complacency, and boredom.
  11. Be a lifelong learner, and be a fanatic about it. Surround yourself with mentors and people smarter than you. Seek to be continually inspired by something, learning what your triggers are.
  12. Care for and about people. Compassion and empathy become you, and keep you ever-connected to your humanity. People will choose you to lead them.

Do let me know your thoughts / comments. Keep discovering.

Posted in Architecture | Tagged: | Leave a Comment »

I am on Microsoft Stack!!

Posted by subodhnpushpak on September 3, 2009

I am visiting beautiful city of Nashvillie, TN, US and involoved in rather interesting project involving WCF, silverlight and SQL server 2008.

Also being used are

  • Search server (FAST) / Lucene .Net
  • Omniture (for Web analytics)
  • Integration with Community server, Twitter, Facebook
  • Velocity – Distributed caching.
  • MemCache – Web server Cache
  • I am also planning to use Nikhil’s MVVM Silverlight Fx at silverlight end  or MEF
  • LINQ / Enity framework – for ORM.

TechStack

That remind me of scenario where i had to register MIME type at IIS 7.0 server to get silverlight (Skecthflow) running. below is the list

  • .xaml             application/xaml+xml
  • .xap               application/x-silverlight-app
  • .xbap             application/x-ms-xbap
  • .deploy           application/octet-stream
  • .xps               application/vnd.ms-xpsdocument
  • .application     application/x-ms-application

I will be posting more details when i get a breather from the project :D . Of course, it will have some more architecture docs :D

Keep me posted !!

Posted in Uncategorized | Leave a Comment »

Silverlight 3.0, RIA services and MVVM

Posted by subodhnpushpak on July 20, 2009

MVVM == Model View ViewModel Pattern is a MUST follow pattern in Silverlight (WPF). here is why…

Problems it solves:

•Tight coupling of layers (ex a query in the UI)

•Unit testing is hard/impossible, only functional testing is possible

•Assures codes still works correct after a change

•ViewModel

•Provides View with data model and behavior

•View will bind to ViewModel

•Wraps data access entirely

In light of new technologies like RIA services (which provides CRUD) operations out of the box it is imperative that users are tempted to overlook MVVM for sake of simplicity!!! However, the goodies MVVM brings along holds good in RIA services well… So what the roadmap to have MVVM , silverlight and RIA services???? I havnt found much on google (& BING!!!) but here is my humble take on that.

I plan to write more in my forthcoming blog but here is one example using nInject.

nInject is lightweight DI framework and is helpful in injecting VIEWMODEL right into XAML code!!! here is how…

   1: Title="Home"

   2:   DataContext="{Binding Path=HomeViewModel, Source={StaticResource serviceLocator}}"

   3:   Style="{StaticResource PageStyle}">

Notice … the datacontext (VIEW MODEL) is injected using ServiceLocator!! the service locater is itself a resource defined in APP.xaml

   1: Application   

   2:   x:Class="SilverlightApp.App"

   3:   xmlns:local="clr-namespace:SilverlightApp.ViewModel"

   4:   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   5:   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

   6:  

   7:   <Application.Resources>

   8:   

   9:     <ResourceDictionary>

  10:       <ResourceDictionary.MergedDictionaries>

  11:         <ResourceDictionary Source="Assets/Styles.xaml"/>

  12:       </ResourceDictionary.MergedDictionaries>

  13:     </ResourceDictionary>

  14:         <local:ServiceLocator x:Key="serviceLocator" />

  15:     </Application.Resources>

  16:  

  17: </Application>

and Ninject code for Service Locater goes like…

   1: namespace SilverlightApp.ViewModel

   2: {

   3:     using Ninject.Core;

   4:     public class ServiceLocator

   5:     {

   6:         private static readonly IKernel kernel;

   7:  

   8:         static ServiceLocator()

   9:         {

  10:             if (kernel == null)

  11:             {

  12:                 kernel = new StandardKernel(new Module());

  13:             }

  14:         }

  15:  

  16:         public HomeViewModel HomeViewModel

  17:         {

  18:             get

  19:             {

  20:                 return kernel.Get<HomeViewModel>(); 

  21:             }

  22:         }

  23:  

  24:         public static T Get<T>()

  25:         {

  26:             return kernel.Get<T>();

  27:         }

  28:     }

  29: }

 

The commands are taken care by the SLExtensions. here is how…

I will be using and blogging about the following DI … Please feel free to write more… if you have anything to add..

1. Nikhil Silverlight FX… This is really good stuff; the only thing which is “does NOT” goes down well (to most of developers) is use of customized controls. Having said that i must say, personally, i love this approach and how Nikhil keep updating it with newest stuff!!!

2. CAB(Prism): I personally think it is more opt for WPF. Having said that it also follows “injection through interface” paradigm.. which sometimes introduces too much hassles…

3. MEF. Latest from Microsoft. Very promising, however yet to mature as a tool.

4. Caliburn: Excellent tool. I found it at codeplex…

 

My plan is to retest each of the above wrt SL3.0, RIA services abd MVVM in context abd post results on this blog.. and get more tractions on the results i get to..

Keep jotting your comments…

Technorati Tags: ,,

Posted in DesignPattern, Silverlight 3.0 | Tagged: , , | 3 Comments »

Silverlight 3.0 – TechEd on Roads

Posted by subodhnpushpak on July 20, 2009

I presented “What’s new in silverlight 3.0” at Teched, Delhi on roads and got overwhelming response for it. Actually there was two events. The venue for the first event was Microsoft office, Gurgaon, Delhi. I must admit i had to change gears because most of the attendees were new to “Silverlight” itself; and i was introducing them to Silverlight 3.0 version!!

So i was back to questions like

  • Why Silverlight?
  • What silverlight means to
    • Developer
    • Architect
    • Manager
    • End user

It did generated lots of interest and my deal on capturing user attention by hatching on to the psychology made it home to most of the users. Examples i gave was as simple as making a grid rotate (flip) to use the same screen space to display more data. OR blurring the grid so that user can concentrate on more relevant information on screen…

Both of the above were, interestingly speaking examples of new features of SL 3.0…

There was also this interesting bit about “what it takes to move to SL platform” and concerns like “I felt lots of resistance from developers in my team while moving away from ASP .net”

It took them a moment before that they realized that SL is actually easy to work on and most importantly its the same C#, VB.net model  developers leverage on. The results they get

  • looks awesome (UI is simply great)
  • Works on every browser and just the same(no more coding for each browser and its version)
  • coding actually is easy

Getting the resistance out is just a matter of fact to demonstrate “how convenient it is” to code in silverlight and the goodies (best practices) are just there out-of-the-box.

Attached the the presentation deck along with the demo.

the best part for me is the compliment from Bijoy (who himself is renowned Microsoft evangelist) on my comment ‘Good products need good evangelists’

Technorati Tags:

Posted in Silverlight 3.0 | Tagged: | Leave a Comment »

Twitter Tree in Silverlight

Posted by subodhnpushpak on June 23, 2009

At last i got some time to work on long pending “project: i have thought of. This one is about listing all twitter friends in a connected graph and see their statuses. It uses Twitter API and WCF service to feed the silverlight. WCF acts as an adapter to twitter service. The idea is to connect to other services like “orkut”, “facebook”, “Mayspace” etc in future.

It uses SL 3.0; so you must have it installed to run this:

Here are the snapshots of the running application.(Running in flock)!! You may see Tim heuer and Nikhil in the graph below… (I have learnt a lot from all these folks by following their blogs and twitter feeds) :D

image

While i still follow very selective list of people; here is graph of people following Nikhil ( Most of the people following him are really cool techies too!!)

image

And here is list for Tim!!!

image

If you want to play with the application here is the link

As a next step i am planning to move the same to AZURE!

Feedback / suggestions/ comments are welcome!!!

Technorati Tags: ,

Posted in .Net, Silverlight, Silverlight 3.0, Twitter | Tagged: , , | Leave a Comment »

Microsoft Azure, Bull Dog, Zurich ???

Posted by subodhnpushpak on May 28, 2009

Someone mentioned “Zurich” and I was again wondering how it was different from “Geneva” or “Zermatt”.

Finally searching got me into this very useful “codename” info.

And I thought only “open-source” can think of funny names.

Hope you will find it useful.

Hats off to Mary Jo Foley for compiling this… here is the list.

Technorati Tags: ,,

Posted in .Net, Azure | Leave a Comment »

Databinding in Silverlight and WPF

Posted by subodhnpushpak on May 27, 2009

Databinding in SL and WPF are interesting concepts and once mastered really solves many a issues with cleaner code. In XAML everything is dataaware.

Elements can be bound to data from a variety of data sources in the form of common language runtime (CLR) objects and XML.

In this post we will discuss about

  • Simple CLR Object binding using code
  • Simple CLR Binding using XAML only – Demo value converters
  • Control Binding – Slider and textbox
  • Implementing IValueConverter
  • Validation
  • Update Source Trigger
  • StaticResource / DynamicResource

Simple CLR Object binding using code

if we declare a class like below in C# code

   1: public class MyClass

   2:    {

   3:  

   4:        #region ID

   5:        /// <summary>

   6:        /// Gets or sets ID 

   7:        /// </summary>

   8:        public int ID { get; set; }

   9:        #endregion ID

  10:  

  11:  

  12:        #region Name

  13:        /// <summary>

  14:        /// Gets or sets Name 

  15:        /// </summary>

  16:        public string Name { get; set; }

  17:        #endregion Name

  18:  

  19:  

  20:        #region dob

  21:        /// <summary>

  22:        /// Gets or sets dob 

  23:        /// </summary>

  24:        public DateTime dob { get; set; }

  25:        #endregion dob

  26:  

  27:  

  28:    }

   1: public Window1()

   2:        {

   3:            InitializeComponent();

   4:            Validation.AddErrorHandler(txt3, (o, e) =>

   5:                {

   6:  

   7:                    MessageBox.Show((string)e.Error.ErrorContent, "Error");

   8:  

   9:                }

  10:  

  11:                );

  12:  

  13:            DummyData();

  14:        }

  15:  

  16:        public void DummyData()

  17:        {

  18:            MyClass ob = new MyClass() { ID = 1, Name = "abc", dob = new DateTime(1980, 06, 08) };

  19:            this.DataContext = ob;

  20:  

  21:        }

we can simply bind it by using following

<StackPanel DataContext={Binding}>

        <TextBox x:Name="txt1" Text="{Binding Path=Name}" ></TextBox>

</StackPanel>

Simple CLR Binding using XAML only

We can just use XAML to declare variables of the class and use databinding as below

   1: <Window.Resources>

   2:         <local:MyClass x:Key="ob1" ID="1" Name="abc"></local:MyClass>

   3:         <local:MyClass x:Key="ob2" ID="2" Name="Red1"></local:MyClass>

   4:  

   5:     </Window.Resources>

   6:    <StackPanel>

   7:         <TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=OneWay}"></TextBox>

   8:         <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=OneWay}"></TextBox>

   9:     </StackPanel>

the output is:

image

Similar to setting “text” property we may even set “Background” to the text peoperty like below:

<TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob1}, Path=Name}"

                 ></TextBox>

        <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob2}, Path=Name}"

                 ></TextBox>

the output changes to: :D . the name of color is also the background!!!

image

Notice as i write and into text box and then click else where the color also changes as below:

image

What will happen if i give a improper color name? An exception? WPF and SL gives into trace message in case something goes wrong with databining. IT DOES NOT GIVES AN EXPLICIT EXCEPTION. like below

image

Notice that there is a trace in output window stating that there is no color “Subodh” however, it does not give an error on UI.

If i want a Blue color everytime i write “Subodh”, then i can write a Converter.

Value converters

   1: public class MyValueConverter : IValueConverter

   2:     {

   3:  

   4:         #region IValueConverter Members

   5:  

   6:         public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   7:         {

   8:             string str = (string)value;

   9:             if (!string.IsNullOrEmpty(str))

  10:             {

  11:                 if (str == "Subodh")

  12:                 {

  13:                     return new SolidColorBrush(Colors.Blue);

  14:                 }

  15:             }

  16:             return value;

  17:         }

  18:  

  19:         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  20:         {

  21:             throw new NotImplementedException();

  22:         }

  23:  

  24:         #endregion

  25:     }

When this Converter is used in XAML, whenever is write “subodh” background will be blue. But for that i have declare the converter in XAML also like:

<Window.Resources>

        <local:Person x:Key="ob1" ID="1" Name="Subodh"/>

        <local:Person x:Key="ob2" ID="2" Name="Yellow"/>

        <local:MyValueConverter x:Key="myValueConverter"></local:MyValueConverter>

    </Window.Resources>

    <StackPanel Background="{DynamicResource solidColorBrush}">

        <TextBox Text="{Binding Source={StaticResource ob1}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob1}, Path=Name, Converter={StaticResource myValueConverter}}"

                 ></TextBox>

        <TextBox Text="{Binding Source={StaticResource ob2}, Path=Name,  Mode=TwoWay}"

                 Background="{Binding Source={StaticResource ob2}, Path=Name}"

                ></TextBox></StackPanel>

output:

image 

Control Binding:

We can bind two controls to each other value using XAML only code like:

if we define something like below.

<StackPanel>

            <ListBox x:Name="lst1" ItemsSource="{Binding Source={x:Static Sys:DateTimeFormatInfo.CurrentInfo}, Path=MonthNames}"></ListBox>

            <TextBox Text="{Binding ElementName=lst1, Path=SelectedItem}"></TextBox>

        </StackPanel>

for the above you may need

xmlns:Sys="clr-namespace:System.Globalization;assembly=mscorlib"

then the output is like :

image

Notice how we are binding MonthNames and then each selected item is displayed in the textbox… All using XAML!!!

If i require the list box items change according to the textbox at runtime and vice versa then i need to inherit my datasource using ObservableCollection as

   1: /// <summary>

   2:     /// Interaction logic for Window2.xaml

   3:     /// </summary>

   4:     public partial class Window2 : Window

   5:     {

   6:         public Window2()

   7:         {

   8:             InitializeComponent();

   9:             personTeam = new PersonTeam() { new Person() { ID = 1, Name = "sdS" }, new Person() { ID = 2, Name = "def" } };

  10:             this.DataContext = personTeam;

  11:         }

  12:         PersonTeam personTeam;

  13:         private void Button_Click(object sender, RoutedEventArgs e)

  14:         {

  15:             personTeam.Add(new Person() { ID = 1, Name = "zzz" }); ;

  16:         }

  17:     }

  18:  

  19:     public class PersonTeam : ObservableCollection<Person>

  20:     { 

  21:         

  22:     }

Now in XAML i may write

   1: <StackPanel DataContext="{Binding}">

   2:            <ListBox x:Name="lst2" ItemsSource="{Binding}">

   3:                <ListBox.ItemTemplate>

   4:                    <DataTemplate>

   5:                        <TextBox Text="{Binding Path=Name, Mode=TwoWay}"></TextBox>

   6:                    </DataTemplate>

   7:                </ListBox.ItemTemplate>

   8:            </ListBox>

   9:            <TextBox Text="{Binding ElementName=lst2, Path=SelectedItem.Name, UpdateSourceTrigger=PropertyChanged }"></TextBox>

  10:            <!--<Button Content="Add" Click="Button_Click"></Button>-->

  11:        </StackPanel>

here are the effects

image

Whenever i change something in either of the test box; the value changes in both!!!

I will blog the validations part in the next series.

Here is the code for the above and the ppt slides.

Please let me know you thoughts / comments.

Technorati Tags: ,

Posted in Silverlight, Silverlight 3.0, XAML | Leave a Comment »