2013-08-23 14 views
0

如果在DataTemplate中將它設置爲Textbox控件,如何查找ListBoxItem的索引?這裏是WPF:查找ListBox ListBox索引(ItemsTemplate指定Visual COntent)

<ListBox Name="ScriptEditor" Margin="10" Height="291" ItemsSource="{Binding Path=Script}" SelectionChanged="ScriptEditor_SelectionChanged_1" > 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBox Text="{Binding Path=Command}"PreviewMouseDoubleClick="Command_DoubleClick" GotFocus="ScriptEditor_GotFocus" /> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
</ListBox> 

當我獲得文本框的焦點(文字,勢必一個ObservableCollection),我不能簡單地用SelectionChanged事件的列表框。我想知道我怎麼能確定我已經獲得焦點的文本框的索引。

感謝

回答

1

你可以綁定AlternationCountScript.Count然後從ItemsControl(列表框)添加AlternationIndexTextboxTag屬性,以便您可以從您的GotFocus事件處理程序中訪問。

例子:

<ListBox Name="ScriptEditor" Margin="10" Height="291" ItemsSource="{Binding Script}" AlternationCount="{Binding Script.Count}" > 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBox Text="{Binding ., Mode=OneWay}" GotFocus="ScriptEditor_GotFocus" 
         Tag="{Binding Path=(ItemsControl.AlternationIndex), Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" /> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 


    private void ScriptEditor_GotFocus(object sender, RoutedEventArgs e) 
    { 
     int index = (int)(sender as TextBox).Tag; 
    } 
+0

真棒,即做到了! – GCar89