Archives

Anticipation

  • No dates present

Conversion Filter

Finally, the last post in my series about conversion and the LookupConverter.

This is just a quick addition to extend the capabilities of the LookupConverter, specifically to allow it to run a bit of code to determine which resulting value to use. I’ve actually never used this in a real-world scenario myself (I’ve always found alternatives), since the goal of the LookupConverter in the first place was to avoid having to write code, and because for obvious reasons this will only work in a one-way scenario. But some people might find it useful.

To start with, the LookupConversion class from the previous post needs this added to it:

    /// <summary>
    /// If this accepts the incoming object, then the conversion applies.
    /// </summary>
    public event FilterEventHandler Filter;
    private void OnFilter(FilterEventArgs e)
    {
        var handler = Filter;
        if (handler != null)
        {
            handler(this, e);
        }
    }

Fairly basic event stuff. Finally, the Matches method needs to be changed to:

    public bool Matches(object value)
    {
        if (Filter != null)
        {
            // this little hack is because the irritating WPF designers gave it an internal constructor... (grumble)
            var e = (FilterEventArgs) Activator.CreateInstance(typeof(FilterEventArgs), BindingFlags.NonPublic,
                                                               null, new[] { value }, null);
            OnFilter(e);
            if (e.Accepted)
            {
                return true;
            }
        }
        if (From == DependencyProperty.UnsetValue) { return true; }
        return ConversionUtilities.EqualsWithConversion(From, value);
    }

One caveat with this is that since FilterEventArgs only has an internal constructor, full trust is required to create an instance via reflection instead (silly library designers!). This shouldn’t be an issue for most WPF apps, but if you’re targeting Silverlight or some other partial-trust scenario then you may need to create your own duplicate of the FilterEventArgs class and use that instead.

Well, that about wraps it up for this particular conversion topic. Next time, I can finally post that unrelated topic I’ve had sitting as a draft for over a year. 😉

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>