简体   繁体   English

专注于列表框中的第一个元素

[英]Focus on first element in listbox

I am facing the following issue. 我正面临以下问题。 When i am removing the first element from a list box which has keyboard focus(by refreshing the item source) the keyboard focus is moving to the parent window. 当我从具有键盘焦点的列表框中删除第一个元素时(通过刷新项目源),键盘焦点移到了父窗口。 I want to retain the keyboard focus on the fist listbox item. 我想将键盘焦点保持在拳头列表框项上。 So i came up with the following code 所以我想出了以下代码

<Grid.Resources>
<Style TargetType="{x:Type ListBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding FirstRowDeleted}" Value="True">
            <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=MyListBox}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

Using this code i am able to move the focus to the list box itself. 使用此代码,我可以将焦点移到列表框本身。 How can i move the focus to the first listbox item? 如何将焦点移到第一个列表框项目? MyListBox[0] does not seem to work. MyListBox [0]似乎不起作用。 Any suggestions? 有什么建议么?

Thanking you Kaddy 谢谢你凯迪

I found answer here: How do you programmatically set focus to the SelectedItem in a WPF ListBox that already has focus? 我在这里找到了答案: 如何以编程方式将焦点设置到已经具有焦点的WPF ListBox中的SelectedItem?

var listBoxItem = (ListBoxItem) MainListBox
    .ItemContainerGenerator
    .ContainerFromItem(MainListBox.SelectedItem);
listBoxItem.Focus();

Thanks for @Jeff for the answer. 感谢@Jeff的回答。

This code applies the focus function to the first input text when the page loads. 当页面加载时,此代码将焦点功能应用于第一个输入文本。 try it out 试试看

$(document).ready(function () {

                $("#input:text:visible:first").focus();


            });

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

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