【问题标题】:Xaml Listbox item focus issueXaml Listbox 项目焦点问题
【发布时间】:2015-06-03 09:54:14
【问题描述】:

我正在使用 xaml UserControl 作为 WPF 应用程序的一部分。我创建了一个列表框,其中填充了来自文本搜索的数据。该数据出现在用于从搜索中选择用户所需选项的按钮上。

<ScrollViewer HorizontalScrollBarVisibility="Auto"
    VerticalScrollBarVisibility="Auto"
    Margin="2">

    <ListBox ItemsSource="{Binding Path=CrewOptions}"
        HorizontalContentAlignment="Stretch"
        BorderThickness="0"
        SelectionMode="Multiple"
        Name="CrewOptionsListBox">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button x:Name="irrelevant"
                    Height="28px"
                    Background="#F4F3E9"
                    Margin="2,2,2,2"
                    Content="{Binding irrelevant1, TargetNullValue={x:Static sys:String.Empty}}"
                    Command="{Binding irrelevant2}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}"
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</ScrollViewer>

这很好用,但是当我从文本框进入列表框,然后使用箭头键选择一个选项时,回车键不会选择按钮。相反,在按 Enter 选择它之前,我必须再次点击以关注按钮。

有什么方法可以避免必须按最后一个 Tab 键来聚焦按钮?

对 Xaml 和 C# 解决方案开放(最好是 MVVM)

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    您好,您可以在 ListBox 中添加以下代码,这将解决 ListBoxItem 的焦点问题。

        <ListView.ItemContainerStyle>
            <Style TargetType="ContentControl">
                <Setter Property="Focusable" Value="False"/>
            </Style>
        </ListView.ItemContainerStyle>
    

    【讨论】:

    • 完美!非常感谢!
    【解决方案2】:

    这样做的原因是您有级联控件。当您使用箭头键时,列表框是活动控件,因此所有事件都将基于列表框而不是按钮触发。

    一种方法是在所选项目上分配一个按键事件,然后启动将由按钮触发的功能。

    类似:

    listBox_keyPressed()
    {
       if(selecteditem)
       {
          DoSomethingFor(selectedItem);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-10-04
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      相关资源
      最近更新 更多