首页 > 解决方案 > 在代码隐藏中聚焦最后一个 ListBoxItem

问题描述

我正在向我添加一个新项目,ObservableCollection用作listBox.ItemsSource

ObservableCollection<MySrc> mySrc;
// in window constructor
mySrc = App.Database.GetSrc();
listBox.ItemsSource = mySrc;

单击按钮时,我想将新项目添加到 ObservableCollection 并关注新添加的项目。我的控件模板包含TextBox元素。我希望 TextBox 获得一个光标(如果它默认获得焦点,就会发生这种情况)

    private void AddButton_Click(object sender, RoutedEventArgs e) {
        MySrcnewMatch = MySrc.PopulateMySrc("Default name", true, true);
        this.mySrc.Add(mySrc);

        listBox.SelectedIndex = listBox.Items.Count-1;
        ((ListBoxItem)listBox.SelectedItem).Focus();
    }

不幸的是,我收到一个错误:

Unable to cast object of type 'Namespace.Model.MySrc' to type 'System.Windows.Controls.ListBoxItem'.

ListBoxItem将最后一个焦点集中在的正确方法是什么ListBox

标签: wpf

解决方案


推荐阅读