martedì 18 giugno 2013

[SL4] Settare pulsante di defualt

public class DefaultButton
{
    public static DependencyProperty DefaultButtonProperty = DependencyProperty.RegisterAttached("DefaultButton",
                                                                typeof(Button),
                                                                typeof(DefaultButton),
                                                                new PropertyMetadata(null, DefaultButtonChanged));
 
    private static void DefaultButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var uiElement = d as UIElement;
        var button = e.NewValue as Button;
        if (uiElement != null && button != null)
        {
            uiElement.KeyUp += (sender, arg) =>
            {
                var peer = new ButtonAutomationPeer(button);
 
                if (arg.Key == Key.Enter)
                {
                    peer.SetFocus();
                    uiElement.Dispatcher.BeginInvoke((Action)delegate
                    {
                        var invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
                        if (invokeProv != null)
                        {
                            if (button.IsEnabled)
                            {
                                invokeProv.Invoke();
                            }
                        }
                    });
                }
            };
        }
    }
 
    public static Button GetDefaultButton(UIElement obj)
    {
        return (Button)obj.GetValue(DefaultButtonProperty);
    }
 
    public static void SetDefaultButton(DependencyObject obj, Button button)
    {
        obj.SetValue(DefaultButtonProperty, button);
    }
}

XAML
<TextBox utility:DefaultButton.DefaultButton="{Binding ElementName=nomeBottone}"/>

Nessun commento:

Posta un commento