Pages

Friday, January 27, 2012

C# Event Handler / Delegates

My Notes:

Publishing Events:
Must determine what information to pass to an event within an EventArgs parameter.
Create a custom class that derives from EventArgs.

public class MyEventArgs : EventArgs
{
    public string myName { get; set; }
    public string newName { get; set; }
    public bool cancel { get; set; }
}

A custom class doesn’t have to be created. Any built-in types, which derive from EventArgs can be used, e.g. RoutedEventArgs.
.After creating a custom EventArgs class or using a built-in type deriving from EventArgs, create a public delegate.

Delegates

Delegates are similar to C pointers that reference methods from other classes.

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

Above delegate expects to reference methods that return void and passes an object and an EventArgs type. These are considered the signature, and the signature is with any method, which the delegate references.

Examples:

public delegate void BtnClickEventHandler(object sender, RoutedEventArgs e);
 
private delegate bool MyEventHandler(object sender, MyEventArgs e);

  • A delegate is an anonymous function.
  • A delegate’s name can be named anything.
  • Delegates have an invocation list
  • Methods with exact signature can be added to a delegate’s invocation list, which all methods add will be raised.
Events

An event manages delegates and are type safe. Events manages adding and removing of delegates. Only methods added to an invocation list can only be removed by who added it to the list.

Events are Public
public event BtnClickEventHandler BtnClick;
 
public event MyEventHandler My;


Create a Helper Function

Create a method with a signature matching the preferred delegate.

public void OnMy(string name, string newName) 
{
//Reference a new MyEventArgs 
 
MyEventArgs myEvtArgs = new MyEventArgs();
 
myEvtArgs.myName = name;
myEvtArgs.newName = newName;
myEvtArgs.cancel = false;
 
My(this, myEvtArgs);  //Raise the event
 
}




Top to Bottom

private class MyEventArgs : EventArgs
 {
     public string myName { get; set; }
     public string newName { get; set; }
     public bool cancel { get; set; }
 }
 
 private delegate void MyEventHandler(object sender, MyEventArgs e);
 public event MyEventHandler My;
 
 public void OnMy(string name, string newName)
 {
     if (My != null)  //Insure someone is handling the event
     {
         MyEventArgs evtArgs = new MyEventArgs();
         evtArgs.myName = name;
         evtArgs.newName = newName;
         evtArgs.cancel = false;
 
         My(this, evtArgs);
     }
 }
 public MainWindow()
 {
     OnMy("Kirk", "Tom");
 }









Wednesday, January 25, 2012

C# Class Implementation of INotifyPropertyChanged

A simple C# class implementing INotifyPropertyChanged:
INotifyPropertyChanged implements one event:
//Event raised anytime a property on the object changes.
public event PropertyChangedEventHandler PropertyChanged;

which is raised anytime a property on the object is changed.




With the class, include a helper function to handle any change with any object property. It can be name any generic name. When raised, it is passed the proptery name as a string.


//Write a helper function
public void OnPropertyChanged(string propertyName)
{
    //Anyone listening?
    if (PropertyChanged != null)
    {
        //Raise the event
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}


Raise the event in any property within the object.


public double password
{
    get { return _password; }
 
    set
    {
        if (value != _password)
        {
            _password = value;
 
            //Will raise the PropertyChanged event.
            OnPropertyChanged("password");
        }
    }
}

Now, when anytime an object’s property changes, the PropertyChanged will be fired.

Complete code below:


public class Person : INotifyPropertyChanged
{
    private double _password;
    public string username { get; set; }
    public double password
    {
        get { return _password; }
 
        set
        {
            if (value != _password)
            {
                _password = value;
                //Will raise the PropertyChanged event.
                OnPropertyChanged("password");
            }
        }
    }
 
    //Event raised anytime a property on the object changes.
    public event PropertyChangedEventHandler PropertyChanged;
 
    //Write a helper function
    public void OnPropertyChanged(string propertyName)
    {
        //Anyone listening?
        if (PropertyChanged != null)
        {
            //Raise the event
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Friday, January 20, 2012

Working with WPF TreeView Control

With C#, I recursively populated a WPF TreeView control. TreeView control will be populated with a directory listing with their respective files. The code is below:
On Page Load:

XAML:

<TreeView Name="Dir" Height="310">
</TreeView>

Initialize a recursive function call: treeViewItem(DirectoryInfo):

DirectoryInfo dir = new DirectoryInfo(@"C:\Kirk\Images");
Dir.Items.Add(treeViewItem(dir));

Recursive function:
private TreeViewItem treeViewItem(DirectoryInfo dir)
 {
     TreeViewItem tvi = new TreeViewItem();
     tvi.Header = dir.Name;
 
     foreach (DirectoryInfo dirInfo in dir.GetDirectories())
     {
         TreeViewItem t = treeViewItem(dirInfo);
         tvi.Items.Add(t);
     }
 
     IEnumerable<TextBlock> textBlock = dir.GetFiles().Select(f => new TextBlock {Text = f.Name} );
 
     foreach (TextBlock tb in textBlock)
     {
         tvi.Items.Add(tb);
     }
 
     return tvi;
 }

I use lambda expressions on any collection. Lambda expressions are extremely productive and tight.

My coding information.