65.9K
CodeProject is changing. Read more.
Home

The missing Generic CancelEventHandler Delegate in the BCL

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Mar 4, 2010

CPOL
viewsIcon

8210

Provides an easy way to make generic Cancel Event Handles. normaly used for pre changing event.The Delegate:[Serializable][HostProtection(SecurityAction.LinkDemand, SharedState = true)]public delegate void CancelEventHandler(object sender, TCancelEventArgs e) where...

Provides an easy way to make generic Cancel Event Handles. normaly used for pre changing event. The Delegate:
[Serializable]
[HostProtection(SecurityAction.LinkDemand, SharedState = true)]
public delegate void CancelEventHandler<TCancelEventArgs>(object sender, TCancelEventArgs e) where TCancelEventArgs : CancelEventArgs;
The inherited CancelEventArgs:
public class CancelSwapEventArg<T> : CancelEventArgs
{
    private T fo = default(T);
    public T FromValue
    {
        get { return fo; }
    }

    private T to = default(T);
    public T ToValue
    {
        get { return to; }
    }

    internal CancelSwapEventArg(T fromValue, T toValue) : base()
    {
        fo = fromValue;
        to = toValue;
    }

    internal CancelSwapEventArg(T fromValue, T toValue, bool cancel)
       : base(cancel)
    {
        fo = fromValue;
        to = toValue;
    }
}
Using the code:
public class MyClass
{
    public event CancelEventHandler<CancelSwapEventArg<int>> SomePropertyChanging;

    private int _SomeProperty;
    public int SomeProperty
    {
        get { return _SomeProperty; }
        set { SetProperty(ref _SomeProperty, ref value); }
    }

    private void SetProperty(ref int property, ref int value)
    {
        if (SomePropertyChanging != null)
        {
            CancelSwapEventArg<int> ResponseArg = new CancelSwapEventArg<int>(property,value);
            SomePropertyChanging(this, ResponseArg);
            if (!ResponseArg.Cancel)
                property = value;
        }
        else
            property = value;
    }

    public MyClass()
    {
        _SomeProperty = 10;
    }
}

public class MyProgram
{
    MyClass myc = new MyClass();

    public MyProgram()
    {
        myc.SomePropertyChanging += new CancelEventHandler<CancelSwapEventArg<int>>(myc_SomePropertyChanging);
        myc.SomeProperty = 9; //this will be canceled.
        myc.SomeProperty = 11; //this will be accepted, and the value of the SomeProperty is now 11.
    }

    private void myc_SomePropertyChanging(object sender, CancelSwapEventArg<int> e)
    {
        //here we say if the new value is smaller than the one already in, then cancel the operation.
        //else set the value.
        e.Cancel = (e.FromValue > e.ToValue);
    }
}