tags:

views:

12

answers:

2

I've got a XamlParseException in some code which is trying to select all the text in a TextBox.

Xaml:

Common:SelectAllTextOnFocus.IsTextSelectedOnFocus="True" />

Code behind:

public static class SelectAllTextOnFocus
{
    public static readonly DependencyProperty IsTextSelectedOnFocusProperty = DependencyProperty.RegisterAttached("IsTextSelectedOnFocus", typeof(bool), typeof(SelectAllTextOnFocus), new UIPropertyMetadata(false, OnIsTextSelectedOnFocusChanged));

    public static bool GetIsTextSelectedOnFocus(TextBox item)
    {
        return (bool)item.GetValue(IsTextSelectedOnFocusProperty);
    }

    public static void SetIsTextSelectedOnFocus(TextBox item, bool value)
    {
        item.SetValue(IsTextSelectedOnFocusProperty, value);
    }

    static void OnIsTextSelectedOnFocusChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
    {
        var item = depObj as TextBox;
        if (item == null)
        {
            return;
        }

        if (e.NewValue is bool == false)
        {
            return;
        }

        if ((bool)e.NewValue)
        {
            item.GotFocus += OnGotFocus;
        }
        else
        {
            item.GotFocus -= OnGotFocus;
        }
    }

I get a XmalParseException, with the message: The type initializer for 'Common.SelectAllTextOnFocus' threw an exception.

Any ideas what's causing this, or how to go about debugging it?

The inner exception is: 'IsTextSelectedOnFocus' property was already registered by 'SelectAllTextOnFocus'.

This is being registered on creation in a static class - so how can it be being registered twice?

+1  A: 

Assuming you've caught this in the debugger, look at the InnerException, which should show you the exception which cause the TypeInitializationException. That should give you a lot more of a hint of where to look.

I can only see one line which could be the problem though:

public static readonly DependencyProperty IsTextSelectedOnFocusProperty = 
    DependencyProperty.RegisterAttached("IsTextSelectedOnFocus",
        typeof(bool), 
        typeof(SelectAllTextOnFocus), 
        new UIPropertyMetadata(false, OnIsTextSelectedOnFocusChanged));

That's the only code which would execute in the type initializer.

I can't see what's wrong with it offhand, but then I'm not very familiar with registering dependency properties.

Jon Skeet
This was the problem - there was a second class which had clearly been copy-and-pasted which was still trying to register to the original class type.
Jackson Pope
@Jackson: Excellent - glad you found it :)
Jon Skeet
+1  A: 

The type intitializer (also known as a static constructor) runs the initializers for your static fields.

In other words, the IsTextSelectedOnFocusProperty initializer is throwing an exception.

SLaks