Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF ItemsControl-添加项目时更改焦点_C#_Wpf_Dynamically Generated - Fatal编程技术网

C# WPF ItemsControl-添加项目时更改焦点

C# WPF ItemsControl-添加项目时更改焦点,c#,wpf,dynamically-generated,C#,Wpf,Dynamically Generated,我有一个ObservableCollectiong StringWrapper per命名段落绑定到ItemsControl,其ItemTemplate只是绑定到StringWrapper.Text的文本框 XAML 我试图做到这一点,当我在文本框中按enter键时,在绑定到当前聚焦的文本框的StringWrapper之后,我在ObservableCollection中插入一个StringWrapper,这将生成一个新的文本框。到目前为止,我的代码做到了这一点,尽管还有一些小问题需要解决 我的问

我有一个ObservableCollectiong StringWrapper per命名段落绑定到ItemsControl,其ItemTemplate只是绑定到StringWrapper.Text的文本框

XAML

我试图做到这一点,当我在文本框中按enter键时,在绑定到当前聚焦的文本框的StringWrapper之后,我在ObservableCollection中插入一个StringWrapper,这将生成一个新的文本框。到目前为止,我的代码做到了这一点,尽管还有一些小问题需要解决

我的问题是,如何设置新生成的文本框的焦点?据我所知,控件生成发生在插入字符串的函数返回之后

我查找了类似ItemsControl.ItemsSourceChanged事件的内容,但至少该名称不存在。我还尝试将处理程序附加到ObservaleCollection.CollectionChanged,但这似乎也是在生成文本框之前触发的。最后,由于ItemsControl.Template是StackPanel,我查找了StackPanel.ControlAdded事件,但也找不到


想法?谢谢

您可能必须处理CollectionChanged,然后使用优先级为Loaded的Dispatcher.BeginInvoke计划将来发生的焦点操作。这将使ItemsControl有机会生成容器并执行布局。

这就成功了!谢谢酷,将我的评论移动到一个答案,这样你就可以接受。我也有同样的问题,但无法真正得到解决。你能解释一下如何使用Dispatcher.BeginInvoke吗?抱歉,不是xaml开发人员,如果您用少量代码显示,将非常有帮助Dispatcher.BeginInvokeAction=>{if list.Count>0{var lastTextBox=list.Lastx=>x.Tag!=null&&x.Tag.ToString==MyTextBox;如果lastTextBox!=null{lastTextBox.Focus;}}}}},则DispatcherPriority.Loaded;
<ItemsControl Name="icParagraphs" Grid.Column="1" Grid.Row="7" ItemsSource="{Binding Path=Paragraphs, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}">
    <ItemsControl.Template>
        <ControlTemplate TargetType="ItemsControl">
            <StackPanel Orientation="Vertical">
                <ItemsPresenter />
            </StackPanel>
        </ControlTemplate>
    </ItemsControl.Template>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
                <TextBox Name="tbParagraph" TextWrapping="Wrap" AcceptsReturn="False" Text="{Binding Path=Text}" Grid.Column="0" KeyUp="tbParagraph_KeyUp" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
public class StringWrapper
{
    public string Text { get; set; }

    public StringWrapper()
    {
        Text = string.Empty;
    }

    public StringWrapper(string text)
    {
        Text = text;
    }
}