Click to See Complete Forum and Search --> : Handling an event for a non-control object?


Jyncus
November 22nd, 2008, 09:00 PM
Using: c# 3.0 / .NET 3.5b
Hi!

This may sound like an elementary question, but I'm fairly new to c#. =] Is is possible to raise an event when say.. a property changes for a given object?

The property can be changed directly or indirectly by the user interacting with the form. The property I'm trying to "listen to" is the .Count on a List<T> object. The user has various GUI controls to add/remove items from the list which will obviously change the count. I'm attempting to perform some action (update the list data displayed on the form) dynamically by having an event raised when List.Count changes, and then using the event handler to immediately update the displayed List.

Thanks for the help.

Arjay
November 22nd, 2008, 11:26 PM
Are you using WPF or WinForms?

JonnyPoet
November 23rd, 2008, 04:42 AM
Simple create your event and add it into the Add and Remove Property like
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication2 {
public partial class Form1 : Form {
MyList<int> test;
public Form1() {
InitializeComponent();
test = new MyList<int>();
test.ListChanged += new ItemChangedDelegate(test_ListChanged);
}
void test_ListChanged(object sender, ItemChangedDelegateArgs e) {
if (e.Added ){
label1.Text = "Item was added to list";
}else{
label1.Text = "Item was removed from list";
}
}
private void add_Click(object sender, EventArgs e) {
test.Add(5);
}
private void remove_Click(object sender, EventArgs e){
test.Remove(5);
}
}
public delegate void ItemChangedDelegate(object sender, ItemChangedDelegateArgs e);
public class MyList<T> {
private List<T> myList;
public event ItemChangedDelegate ListChanged;

public MyList(){
myList = new List<T>();
}
public void Add(T item){
myList.Add(item);
OnListChanged(true);
}
private void OnListChanged(bool added){
if(ListChanged != null){
ListChanged(this, new ItemChangedDelegateArgs(added));
}
}
public bool Remove(T item){
bool result = false;
if(myList.Contains(item)){
result =myList.Remove(item);
}
if (result) {
OnListChanged(false);
}
return result;
}
}
public class ItemChangedDelegateArgs :EventArgs{
private bool _added;
public ItemChangedDelegateArgs(bool added) {
_added = added;
}
public bool Added {
get { return _added; }
}
}
}
Paste this in an empty project instead of Form1 and you can run this demo. (You need a button 'add' , a button 'remove' and 'Label1'
to do on your Form and adding the delegates to the buttons :D too !