将焦点设置为新TabItem中的按钮 [英] Set focus to a button in a new TabItem

查看:71
本文介绍了将焦点设置为新TabItem中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用TabControl来显示项目列表.ItemView是我编写的单独控件.

I use a TabControl to display a list of items. The ItemView is a separate control I wrote.

       <TabControl SelectedItem="{Binding CurrentItem}"
                    IsSynchronizedWithCurrentItem="True"
                    ItemsSource="{Binding ItemList}">
            <TabControl.ContentTemplate>
                <DataTemplate>
                    <ctrls:ItemView/>
                </DataTemplate>
            </TabControl.ContentTemplate>
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding ShortItemDescription}"/>
                </DataTemplate>
            </TabControl.ItemTemplate>
        </TabControl>

如果用户按下Button,则将新的ViewModel添加到ViewModels列表中,并且TabControl将其显示为新的选项卡.添加新标签后,将被选中.

If the user presses a Button a new ViewModel is added to the list of ViewModels and the TabControl displays it as a new tab. After adding the new tab is selected.

       <Button Command="{Binding AddItemCommand}"
               Content="Add item"/>

在新视图内部是一个按钮,每次添加新选项卡时都需要将其聚焦.我曾尝试在ItemView中使用FocusManager和Initialized事件,但是只有在我第一次添加新标签时才调用它们.

Inside of the new View is a button that needs to be focused each time a new tab is added. I have tried to use the FocusManager and the Initialized event in the ItemView but these are only called for the first time I add a new tab.

<UserControl x:Class="ItemView"
         ...
         Initialized="ViewInitialized">
<Grid>
    ...

    <!-- Set focus to this button -->
    <Button Content="Search"
            Command="{Binding SearchCommand}"
            Name="SearchButton"
            Grid.Column="0"
            Grid.Row="0"/>
</Grid>
</UserControl>

有什么想法吗?

更新

ItemView中Initialize方法的内容目前是这样-可以正常工作... 第一次,然后再也不会

The content of the Initialize method in the ItemView is currently this one - which is working fine... for the first time and then never again

    public delegate void ChangeFocusDelegate();

    private void FocusSearchButton()
    {
        SearchButton.Focus();
    }

    private void ViewInitialized(object sender, EventArgs e)
    {
        ChangeFocusDelegate focusDelegate = FocusSearchButton;
        Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, focusDelegate);
    }

推荐答案

这应该是这样的(在您定义的UserControl初始化事件上):

This should be work like this (over your defined Initialized event of the UserControl):

private void ViewInitialized(object sender, System.EventArgs e)
{
    this.SearchButton.Focus();
}

这篇关于将焦点设置为新TabItem中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆