Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, May 23, 2012

Versatile WPF Boolean to Visibility Converter

The BooleanToVisibilityConverter that cames with WPF has some weak points because it cannot handle Visibility.Hidden or it cannot work in 'inverse' mode.

Suppose you have two controls and you want only one of them to be visible based on some IsEditing dependency property. With the build in converter, there is no easy way for achieving this functionality.

The following BooleanToVisibilityConverter solves this issues:

To use it in the above scenario:


Now, when IsEditing is false, the text block is visible. When IsEditing is true, the text block becomes collapsed and the text box is visible.

If one needs to use the Visibility.Hidden value instead of Visibility.Collapsed, the FalseValue property on the BooleanToVisibilityConverter should be set to Visibility.Hidden.

Wednesday, May 4, 2011

Invoking anonymous methods in WPF

To execute some work on a Dispathcer, synchronously, the Dispatcher.Invoke method is used, which takes a Delegate as an argument representing the work to be done.

However, as stated on MSDN, the Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. The Delegate class is not considered a delegate type; it is a class used to derive delegate types. - Hence the need for the explicit cast to a derived-from-Delegate type.

Most languages implement a delegate keyword, and compilers for those languages are able to derive from the MulticastDelegate class; therefore, users should use the delegate keyword provided by the language.

Here are a few ways to synchronously invoke an anonymous method:

by declaring a delegate type and casting the delegate to it:

Starting with version 3.5, .Net contains an Action class that is defined like:

so it can be used:

by casting a delegate to an Action:

by casting a lambda expression to an Action:

by creating an instance of Action passing a delegate to its constructor:

Sunday, April 17, 2011

Removing EventHandler from itself

Lambda expression offers a great way to write less code for registering event handlers:

But what if we need to remove the event handler after the WriteLine call, from the event handler itself? It is possible, if the lambda expression delegate had a name:

One problem with this though, when initializing the handler variable, inside the code that initializes it, at the line button.Click -= handler we access the handler which at this point is not initialized yet! So, to fix this, simply initialize it with null first (which might look a little bit awkward):