silverlight-4.0attached-propertiesdefaultbutton

Silverlight 4 Default Button Service


For a few months I have been successfully using David Justices Default Button example in my SL 3 app. This approach is based on an attached property.

After upgrading to SL4, the approach no longer works, and I get a XAML exception:

Unknown parser error: Scanner 2148474880

Has anyone succesfully used this (or any other) default button attached behaviours in SL4?

Is there any other way to achieve default button behaviour in SL4 with the new classes that are available?

Thanks, Mark


Solution

  • I extended David's approach by allowing a custom key (defaulted to Enter) to be set in an additional property:

        public static DependencyProperty ButtonKeyProperty = DependencyProperty.RegisterAttached(
             "ButtonKey",
             typeof(Key),
             typeof(Defaults),
             new PropertyMetadata(Key.Enter, ButtonChanged));
    
        public static void SetButtonKey(DependencyObject dependencyObj, Key key)
        {
            dependencyObj.SetValue(ButtonKeyProperty, key);
        }
    
        public static Key GetButtonKey(DependencyObject dependencyObj)
        {
            return (Key)dependencyObj.GetValue(ButtonKeyProperty);
        }
    

    I modified the original property to then leverage this property:

        Key key = GetButtonKey(dependencyObj);
        if (button.IsEnabled && keyEvent.Key == key)
            ...
    

    So now, for example, I can use Escape as the key if I want (note I changed the named of the classes and properties):

        ... UI:Defaults.Button="{Binding ElementName=myButton}" UI:Defaults.ButtonKey="Escape" ...