2014-10-20 78 views
0

我有一個ObservableCollectiong<StringWrapper>(StringWrapper每this post)命名段落綁定到一個ItemsControl的ItemTemplate只是一個文本框綁定到StringWrapper.TextWPF ItemsControl - 添加項目時更改焦點

XAML

<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> 

C#

public class StringWrapper 
{ 
    public string Text { get; set; } 

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

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

我想使它所以當我按在文本框中輸入,我的StringWrapper後,我的ObservableCollection插入StringWrapper綁定到當前聚焦的文本框,從而生成新的文本框。到目前爲止,我的代碼是這樣做的,儘管有一些小問題需要解決。

我的問題是,然後我如何設置焦點到新生成的文本框?據我所知,控件生成發生在插入字符串的函數返回後。

我查找了像ItemsControl.ItemsSourceChanged事件,但至少該名稱不存在。我也嘗試將一個處理程序附加到ObservableCollection.CollectionChanged,但在生成TextBox之前似乎也觸發了它。最後,由於ItemsControl.Template是一個StackPanel,我查找了一個StackPanel.ControlAdded事件,但找不到那個。

想法?謝謝!

+0

這個伎倆!謝謝! – dfoverdx 2014-10-20 18:04:18

+0

很酷,將我的評論移至答案,以便您接受它。 – 2014-10-20 18:05:00

+0

我有同樣的問題,但不能真正得到解決方案 – MSIslam 2015-03-31 22:32:19

回答

1

您可能必須處理CollectionChanged,然後安排將來使用Dispatcher.BeginInvoke優先Loaded進行焦點操作。這應該使ItemsControl有機會生成容器並執行佈局。

+0

請你介紹一下如何使用Dispatcher.BeginInvoke?對不起,不是一個xaml開發人員,如果你用很少的代碼顯示會非常有幫助 – MSIslam 2015-03-31 22:33:45

相關問題