4

在 WPF(MVVM,无代码隐藏)中,假设我有以下 xaml:

<StackPanel>
    <Button>Normal 1</Button>
    <Button>Special</Button> <!--This button should not tab focus, but still focus via arrow keys-->
    <Button>Normal 2</Button>
</StackPanel>

默认情况下,您可以 (1) 按钮之间的制表符或 (2) 按钮之间的向上/向下箭头。我想制作其中一个按钮——特殊按钮——不能通过选项卡聚焦,但仍然可以通过向上/向下聚焦。我试过IsTabStop="False"了,但这也阻止了通过定向导航(向上/向下箭头)聚焦该按钮。

如何从选项卡导航中删除单个按钮,同时继续允许定向导航对于所有其他控件,制表符和箭头应该不受影响。

我尝试了, 和的组合IsTabStop,但无济于事。也许我还没有找到合适的组合。或者也许还有另一种方法。想法?KeyboardNavigation.TabNavigationKeyboardNavigation.DirectionalNavigation


编辑:好的,我正在添加赏金。需要明确的是,我正在寻找一个 MVVM,没有代码隐藏方式来装饰控件(例如,通过样式、附加属性、附加行为等),以便将其从选项卡顺序中删除,同时保持有效的方向导航目标。将控件硬编码到窗口(或类似)中是不可接受的。这需要一个通用的、可重用的解决方案。类似的东西:<Button AllowDirectionalNavigationButPreventTabNavigation="True"/>

4

2 回答 2

12

那个选项怎么样。您将特殊按钮粘贴到另一个容器中,然后将 KeyboardNavigation.TabNavigation="None" 放在该容器上。我刚刚尝试过,看起来我可以实现你所需要的。

<StackPanel >
  <Button>Normal 1</Button>
  <StackPanel KeyboardNavigation.TabNavigation="None">
    <Button>Special</Button><!--This button should not tab focus, but still focus via arrow keys-->
  </StackPanel>
  <Button>Normal 2</Button>
</StackPanel>
于 2014-12-09T13:51:11.633 回答
0

我是怎么做到的:

<Window x:Class="MvvmLight1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ignore="http://www.ignore.com"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:command="http://www.galasoft.ch/mvvmlight"
    mc:Ignorable="d ignore"
    Height="300"
    Width="300"
    DataContext="{Binding Main, Source={StaticResource Locator}}">
<i:Interaction.Triggers>
    <i:EventTrigger EventName="KeyDown">
        <command:EventToCommand Command="{Binding Mode=OneWay,Path=KeyDownCommand}" PassEventArgsToCommand="True"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
<Grid x:Name="LayoutRoot">
    <StackPanel>
        <Button>Normal 1</Button>
        <Button>Special</Button>
        <!--Should not tab focus, yet still focus via arrow keys-->
        <Button>Normal 2</Button>
    </StackPanel>
</Grid>

我正在使用 mvvmlight,EventToCommand 用于拦截 KeyDown 事件并将其定向到 ViewModel 中的以下命令:

 private RelayCommand<KeyEventArgs> _keyDownCommand;
    public RelayCommand<KeyEventArgs> KeyDownCommand
    {
        get
        {
            return _keyDownCommand
                ?? (_keyDownCommand = new RelayCommand<KeyEventArgs>(
                (s) =>
                {
                    if (s.Key == Key.Tab)
                    {
                        s.Handled = true;
                    }
                }));
        }
    }
于 2014-12-05T23:08:27.823 回答