Search code examples
c#wpfbindinglistboxlistboxitems

Finding Listbox Index of ListBoxItem (ItemsTemplate to specify Visual COntent)


How do you find the index of a ListBoxItem if it is set within a DataTemplate as a Textbox control? Here is the WPF:

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

When I gain focus of the textbox (text is bound to an observableCollection), I cannot simply use the SelectionChanged Event on the ListBox. I would like to know how I can determine the index of the textbox I have gained focus in.

Thanks


Solution

  • You could bind the AlternationCount to the Script.Count then add the AlternationIndex from the ItemsControl(ListBox) to the Textbox Tag property so you can access from your GotFocus event handler.

    Example:

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