C# Event Relays

Events are a powerful mechanism to propagate changes within an application. Using custom add and remove handlers, you can even decide what happens when clients subscribe and unsubscribe, a feature I used extensively to “forward” subscriptions to other classes.

class Intermediate
{
    private readonly ISomeEventSource _source;

    public event EventHandler IntermediateEvent
    {
        add { _source.SourceEvent += value; }
        remove { _source.SourceEvent -= value; }
    }
}

If you’re working with events extensively, this is something you come across sooner or later. It is a simple mechanism to directly connect the subscriber of IntermediateEvent to the SourceEvent.

As soon as you have slightly more complicated setups, however, this approach becomes arduous. For example, there is no possibility to intercept the event propagation from the source to the client, because the client is connected to the source directly. Thus, you have no chance of modifying event arguments, dropping certain events or performing some custom handling in the Intermediate class.

Continue reading

View-Only Actions in WPF

About a year ago, I answered a question about WPF bindings on stackoverflow.com. The goal was to bind a button to the “close window” action. All answers involved writing some C# code to actually close the window, which is a rather cumbersome approach.

Recently, I was asked about a very similar problem at the project I’m currently working on, so I thought it may be worth to share an elegant solution to this, using only XAML code.

Continue reading