Defining InputBindings within a Style

Posted by Brent on Stack Overflow See other posts from Stack Overflow or by Brent
Published on 2010-04-18T01:37:21Z Indexed on 2010/04/18 1:43 UTC
Read the original article Hit count: 589

I'm creating a WPF app using the MVVM design pattern, and I'm trying to extend the TabItem control so that it closes the tab when the user clicks the middle mouse button. I'm trying to achieve this using InputBindings, and it works very well until I try to define it within a style. I've learned that you cannot add InputBindings to a style unless you attach it using a DependencyProperty. So I followed this similar post here... and it works... almost. I can close one tab using the middle mouse button, but it won't work on any of the other tabs (all of the tabs are added at runtime and inherit the same style).

So I need some help. Why would this only be working the first time, and not after? Obviously I could create a custom control that inherits from a TabItem and make it work, but I'd like to figure this out as I can see this being expanded in my projects. I'm no expert on DependencyProperties, so please help me out. Thanks!

Style:

<Style TargetType="{x:Type TabItem}">
    <Setter Property="w:Attach.InputBindings">
        <Setter.Value>
            <InputBindingCollection>
                <MouseBinding MouseAction="MiddleClick" 
                              Command="{Binding CloseCommand}"/>
            </InputBindingCollection>
        </Setter.Value>
    </Setter>
    ...
</Style>

Class

public class Attach
{
    public static readonly DependencyProperty InputBindingsProperty =
        DependencyProperty.RegisterAttached("InputBindings", typeof(InputBindingCollection), typeof(Attach),
        new FrameworkPropertyMetadata(new InputBindingCollection(),
        (sender, e) =>
        {
            var element = sender as UIElement;
            if (element == null) return;
            element.InputBindings.Clear();
            element.InputBindings.AddRange((InputBindingCollection)e.NewValue);
        }));

    public static InputBindingCollection GetInputBindings(UIElement element)
    {
        return (InputBindingCollection)element.GetValue(InputBindingsProperty);
    }

    public static void SetInputBindings(UIElement element, InputBindingCollection inputBindings)
    {
        element.SetValue(InputBindingsProperty, inputBindings);
    }
}

© Stack Overflow or respective owner

Related posts about wpf

Related posts about mvvm