Steveluo’s Blog

Just another weblog

Back to Basics (2)

Posted by steveluo on March 8, 2009

see  MSDN’s Using Properties
“Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields.”

a)  Auto-Implemented Properties (C#3.0 and up) :
      “the compiler creates a private, anonymous backing field can only be accessed through the property’s get and set accessors.
      The compiler creates backing fields for each auto-implemented property. The fields are not accessible directly from source” code.
// Auto-Impl Properties for trivial get and set
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

b)  Implement an Immutable Class That Has Auto-Implemented 
  “with auto-implemented properties, both a get and set accessor are required. You make the class immutable by declaring the set accessors as private. However, when you declare a private set accessor, you cannot use an object initializer to initialize the property. You must use a constructor or a factory method.”


Posted in Uncategorized | Leave a Comment »

MVVM: How to

Posted by steveluo on March 1, 2009

I have learned the following best practices from thess great articles.

Karl Shifflet and Adam Kinney talk about ViewModel on Channel9:

  • Jeff Handley has a number of great post on ViewModel:[1]Introduction to Model/View/ViewModel pattern for building WPF apps  by John Grossman
    [2]Patttern MVVM  by Josh Smith
    [3]The ViewModel Pattern by David Hill

    1)  How to lay out Xaml files
    2) Relay Command
    3) Treeview’ double click  — 
    4) Datagrid  binding
    5) Flat to tree list
  • Posted in WPF | Tagged: | Leave a Comment »

    attached property

    Posted by steveluo on February 24, 2009


    treeview double click binding:
      a smart way to use double click …

    private static void OnMouseDoubleClickCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
               UIElement element = target as UIElement; if (element != null)
    if ((e.OldValue == null) && (e.NewValue != null))
    UIElement.MouseDownEvent, new MouseButtonEventHandler(UIElementMouseLeftButtonDown), true);
    //element.MouseLeftButtonDown += UIElementMouseLeftButtonDown;
    else if ((e.OldValue != null) && (e.NewValue == null))
    UIElement.MouseDownEvent, new MouseButtonEventHandler(UIElementMouseLeftButtonDown));
    /element.MouseLeftButtonDown -= UIElementMouseLeftButtonDown;

    private static void UIElementMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
                 // gets the sender is UIElement and check ClickCount because we want double click only



                  UIElement target = sender as UIElement;
    if (target != null && e.ClickCount > 1)
                     ICommand iCommand = (ICommand)target.GetValue(MouseDoubleClickCommandProperty);
    if (iCommand != null)
    RoutedCommand routedCommand = iCommand as RoutedCommand;
    // check if the command has a parameter using the MouseEventParameterProperty         
    object parameter = target.GetValue(MouseEventParameterProperty);

                                   // execute the command
    if (parameter == null)
                                 {       parameter = target;

                                 if (routedCommand != null)
                                         routedCommand.Execute(parameter, target);
                                       iCommand.Execute(parameter);                              }


                                      e.Handled =  true;






    Posted in WPF | Leave a Comment »

    WPF Resources

    Posted by steveluo on February 23, 2009


    Syncfusion FAQ
     Best WPF forums MSDN’s WPF forums
    Expression Blend forums to help style your WPF Apps
     Best WPF articles 1) xmal
    2) data binding
         Data Binding Overview (MSDN)
         Windows Presentation Foundation Data Binding Part1
         Windows Presentation Foundation Data Binding: Part 2
         Flexible and Powerful Data Binding with WPF ( CoDe : part1, part2 )
    3) Treeview 
         WPF treeviews on LINQ to SQL  
         LINQ AsHierarchy() extension method  part1 part2
    4)  MVVM Pattern & CAL
          WPF Apps With The Model-View-ViewModel Design Pattern

    Best WPF blogs *Beatriz Costa – WPF Data Binding
    Charles Petzold’s WPF book blog
    Fil Fortes
    *john gossman   — An architect of WPF 
    *Josh Smith
    Karsten Januszewski
    Kevin Moore’s Okoboji
    Lester Lobo
    Marcelo Lopez Ruiz
    Rich Application (e.g. US map in listBox)
    Rob Relyea
    Tim Sneath
    Windows Presentation Foundation SDK
    The WPF blog by Lee Brimelow (no longer blogging about WPF)
     Best WPF tutorials  MSDN .Net 3.5 WPF’s WPF tutorials – Lots of video tutorials, all WPF
    WPF: A Beginner’s Guide 1, 2, 3, 4, 5, 6
    A Guided Tour of WPF
     Best examples  1)  CodeProject
     2)  Chart: 
     Best Miscellaneous WPF resources The Application Portfolio on Channel9’s WPF Wiki
    The 3rd party controls list on Channel9’s WPF Wiki – An extension of resources provided on Channel9 – Expression Blend help for WPF application developers – A categorized WPF resource guide. – Yet another categorized WPF resource guide
         CheatSheet XAML for WPF Cheat Sheet 1.0
    WPF XAML Data Binding Cheat Sheet
    2008 WPF Boot Camp
    WPF Disciples

    Posted in WPF | Leave a Comment »

    the relationship among WPF properties

    Posted by steveluo on February 23, 2009

    Properties ( CLR properties),  DependencyProperty and  Attached properties (Attached  DependencyProperty)
    Attached properties are typically defined as a specialized form of dependency property that does not have the conventional property “wrapper”. (src)

    a DependencyProperty is a special form of property that has the feature of being able to interact with WPF (styling, data binding, animation, etc.).

    A DependencyProperty is always a property of an object derived from the DependencyObject class. Note that only Dependency Properties can be used as a binding target. A DependencyProperty is created using the static Register method of the DependencyProperty class.

    Common Language Runtime (CLR) property is: it is the classic .NET class property.

    an Attached DependencyProperty should be stored in a public static readonly field. This is to ensure its visibility to anyone wishing to use it.

    from  Attached Properties Overview,

    Posted in WPF | Leave a Comment »


    Posted by steveluo on February 22, 2009

    Exploring MSIL – Delegates and Events
    Exploring MSIL – Properties
    Exploring MSIL – Static and Instance Methods
    The lies of the C# compiler…

    Posted in C# | Leave a Comment »

    Back to Basics

    Posted by steveluo on January 18, 2009

    C#: Back to basics 
    1. Delegates( means hand over)
       C# introduced a keyword called delegate for utilizing such things as function pointers and call backs. 
       Delegates are interfaces to pass functionality from one object to another object

    My understanding is that delegate is  function pointer in C# implementation:   using the referense of the wrap-up object which contain that function only. so declartion use  hybrid class and method defination.
    Delegates can be used for a number of general purposes , including using them as callback methods, defining static methods, and using them to define events.

    Interesting facts about delegates: (src)

    • A delegate represents a class.            [should say ‘interface type’  class, the obj should have same signature]
    • A delegate is type-safe.
    • You can combine multiple delegates into a single delegate.
    • You can use delegates both for static and instance methods.
    • You can define delegates inside or outside of classes.
    • You can use delegates in asynchronous-style programming.
    • Delegates are often used in event-based programming, such as publish/subscribe.
    using System;
    namespace DelegatesSample
            // Define a delegate. class definition
            public delegate bool SampleDelegate(string name);     
           class SampleDelegateDriver
                 // A delegate variable declaration
                 private SampleDelegate m_sampleDelegate;           
             // You need this function to construct your delegate object
               private bool log(string text)
                      return true;
               public void start()
                      Console.WriteLine(“Testing a sample delegate”);                 
                      // Instantiating a simple delegate
                       m_sampleDelegate = new SampleDelegate(log);                  // Calling a simple delegate
                     bool returnCode = m_sampleDelegate(“A simple delegate call”);                 // Combining delegates
                     SampleDelegate d1 = new SampleDelegate(log);
                     SampleDelegate d2 = new SampleDelegate(log);
                     SampleDelegate compositeDelegate =
                                         (SampleDelegate)Delegate.Combine(d1, d2);                  //calling a composite delegate
                      returnCode =
                                  compositeDelegate(“Sample composite delegate”);

                       // operator overloading
                      compositeDelegate = d1 + d2;
                      returnCode =
                                  compositeDelegate(“Composite delegate,” +
                                                                            “using the + operator”);

                       // you can also remove delegates
                       // delegates are immutable
                      SampleDelegate resultingDelegate =
                         (SampleDelegate)Delegate.Remove(compositeDelegate, d2);
                       compositeDelegate(“Composite delegate” + ” after removing one of them”);
                       resultingDelegate(“Resulting delegate” +  ” after removing one of them”);

                       //target of a static method
                       if (m_sampleDelegate.Target == null)
                             log(“This delegate is pointing to a static method”);
                       // target of an instance method
                       log(“Casting the target to its object type”);
                      SampleDelegateDriver sdd
                                          = (SampleDelegateDriver)m_sampleDelegate.Target;

                      // Enquire targets type name
                     log(“Name of the class that is ” + “implementing the sample delegate: ”
                                       + m_sampleDelegate.Target.GetType().FullName);

                      // Finally see if the ToString method
                     // of your class is called
                     // when invoked on the target instance

                     Console.WriteLine(“TOSTR:” +

                      // walking through the delegate list
                      log(“Testing GetInvocation list”);

                       compositeDelegate = d1 + d2;

                       int i=0;
                       foreach(Delegate x in
                                log(“delegate ” + i + x.Method.ToString());

                // Method to test the target property of a delegate
               override public string ToString()
                     return “ToString called”;

              static void Main(string[] args)
                     SampleDelegateDriver sdd =
                                 new SampleDelegateDriver();







     namespace SimpleEvent
        /* ========= Publisher of the Event ============== */
        public class MyClass
            // Define a delegate named LogHandler, which will encapsulate
            // any method that takes a string as the parameter and returns no value

            public delegate void LogHandler(string message);
    // Define an Event based on the above Delegate

    public event LogHandler Log;

            // Instead of having the Process() function take a delegate
            // as a parameter, we’ve declared a Log event. Call the Event,
            // using the OnXXXX Method, where XXXX is the name of the Event.

            public void Process()
                OnLog(“Process() begin”);
    (“Process() end”);
            // By Default, create an OnXXXX Method, to call the Event
            protected void OnLog(string message)
                if (Log != null)

      public class TestApplication
            static void Logger(string s)
            static void Main(string[] args)
                FileLogger fl = new FileLogger(“process.log”);
                MyClass myClass = new MyClass();
                // Subscribe the Functions Logger and fl.Logger
                myClass.Log += new MyClass.LogHandler(Logger);
                // The Event will now be triggered in the Process() Method














       public delegate bool SampleDelegate(String name);
    C# compiler generates a class called  SampleDelegate in next column!  
        The Invoke() method has the same signature as our delegate declaration
    public class SampleDelegate : System.MulticastDelegate
             public SampleDelegate(object target, int method); //constructor 
        public virtual void Invoke(string name);
        public virtual IAsyncResult BeginInvoke(string name,
    AsyncCallback callback, object obj);
        public virtual void EndInvoke(IAsyncResult result);


    2)  Delegate with event
        The basic foundation behind C# eevnt model is the publisher and subscribers.
         publisher:    —  publish an event 
               1) declare a Delegate 
               2) declare an event based on the  Delegate   
               3)  fire the event
               subscribed event
              event handler

     See MSDN’s Handling and Raising Events

        Button Class  (event in GUI)     from 3.0 Spec 
    creates two Button instances and attaches event handlers to the Click events.

     Field-like events

    public delegate void EventHandler(object sender, EventArgs e);

    public class Button: Control
          public event EventHandler Click;

    public class LoginDialog: Form
         Button OkButton;
         Button CancelButton;

         public LoginDialog()
               OkButton = new Button(…);
               OkButton.Click += new EventHandler(OkButtonClick);
               CancelButton = new Button(…);
               CancelButton.Click += new EventHandler(CancelButtonClick);

         void OkButtonClick(object sender, EventArgs e) {
               // Handle OkButton.Click event

         void CancelButtonClick(object sender, EventArgs e) {
               // Handle CancelButton.Click event

    public delegate void EventHandler(object sender, EventArgs e);

    public class Button: Control
         //Click is used as a field within the Button class
         public event EventHandler Click;

         //The OnClick method “raises” the Click event
        // which equivalent to invoking the delegate represented by the event

         protected void OnClick(EventArgs e) {
               if (Click != null)
                       Click(this, e);

         public void Reset() {
               Click = null;

    class X
         public event D Ev;

    Which is compiled to :

    class X
         private D __Ev;  // field to hold the delegate

         public event D Ev {
               add {
                    lock(this) { __Ev = __Ev + value; }

               remove {
                    lock(this) { __Ev = __Ev – value; }

    Posted in C# | Tagged: | 1 Comment »