繁体   English   中英

在样式中定义InputBindings

[英]Defining InputBindings within a Style

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

所以我需要一些帮助。 为什么这只会在第一次工作,而不是以后呢? 显然,我可以创建一个继承自TabItem的自定义控件并使它工作,但是我想弄清楚这一点,因为我看到它在我的项目中得到了扩展。 我不是DependencyProperties的专家,所以请帮帮我。 谢谢!

样式:

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

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);
    }
}

您的“附加”课程对我来说效果很好! 如果有人需要,诀窍是使用带有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>

谢谢!

没关系,我自己弄清楚了。 我最终甚至没有使用上面的Attach类...而是在ControlTemplate上为TabItem(这是一个Border)使用了InputBindings,所以看起来像这样……我不知道为什么我没有想到首先是.. :)

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM