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

百般思念 提交于 2019-12-12 02:33:04

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/18392835/finding-listbox-index-of-listboxitem-itemstemplate-to-specify-visual-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!