Wpf 在样式中定义输入绑定

Wpf 在样式中定义输入绑定,wpf,mvvm,dependency-properties,inputbinding,Wpf,Mvvm,Dependency Properties,Inputbinding,我正在使用MVVM设计模式创建一个WPF应用程序,并尝试扩展TabItem控件,以便在用户单击鼠标中键时关闭选项卡。我尝试使用InputBindings来实现这一点,在我尝试在样式中定义它之前,它工作得非常好。我了解到,除非使用DependencyProperty附加样式,否则无法向样式添加InputBinding。所以我跟随了这个类似的帖子,它很有效。。。几乎。我可以使用鼠标中键关闭一个选项卡,但它对任何其他选项卡都不起作用(所有选项卡都是在运行时添加的,并继承相同的样式) 所以我需要一些帮助

我正在使用MVVM设计模式创建一个WPF应用程序,并尝试扩展TabItem控件,以便在用户单击鼠标中键时关闭选项卡。我尝试使用InputBindings来实现这一点,在我尝试在样式中定义它之前,它工作得非常好。我了解到,除非使用DependencyProperty附加样式,否则无法向样式添加InputBinding。所以我跟随了这个类似的帖子,它很有效。。。几乎。我可以使用鼠标中键关闭一个选项卡,但它对任何其他选项卡都不起作用(所有选项卡都是在运行时添加的,并继承相同的样式)

所以我需要一些帮助。为什么这只是第一次起作用,而不是之后?显然,我可以创建一个从TabItem继承的自定义控件并使其工作,但我想弄清楚这一点,因为我可以看到它在我的项目中被扩展。我不是依赖财产方面的专家,所以请帮帮我。谢谢

风格:

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

没关系,我自己想出来的。我甚至没有使用上面的附加类。。。相反,我在ControlTemplate上为TabItem(它是一个边框)使用了InputBindings,所以看起来像这样。。。我不知道为什么我一开始没有想到这一点……)


...
...
你的“附加”课程对我来说很好! 如果有人需要,诀窍是使用如下样式,带有x:Shared修饰符:

<InputBindingCollection x:Key="inputCollection" x:Shared="False">
        <KeyBinding Key="Del" Command="{Binding DeleteItemCommand}"/>
</InputBindingCollection>

<Style TargetType="{x:Type TabItem}">
    <Setter Property="w:Attach.InputBindings" Value="{StaticResource inputCollection}" />
    ...
</Style>

...

谢谢

即使使用Daniel建议的代码,我也遇到了上面描述的确切问题。当使用上面的Attach类时,似乎有一些非常奇怪的事情,尤其是在样式中。我发现添加InputBindings时DataContext“有时”为null,因此当绑定发生时,它无法定位命令。我从未找到解决方案,但我最终复制了绑定,如下面的答案所示。
<ControlTemplate TargetType="{x:Type TabItem}">
    <Grid SnapsToDevicePixels="true">
        <Border x:Name="Bd" ...>
            <DockPanel>
                ...
            </DockPanel>
            <Border.InputBindings>
                <MouseBinding MouseAction="MiddleClick"
                              Command="{Binding CloseCommand}"/>
            </Border.InputBindings>
        </Border>
    </Grid>
    ...
</ControlTemplate>
<InputBindingCollection x:Key="inputCollection" x:Shared="False">
        <KeyBinding Key="Del" Command="{Binding DeleteItemCommand}"/>
</InputBindingCollection>

<Style TargetType="{x:Type TabItem}">
    <Setter Property="w:Attach.InputBindings" Value="{StaticResource inputCollection}" />
    ...
</Style>