0

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

4

1 回答 1

1

您可以将 绑定AlternationCountScript.Count然后将AlternationIndexItemsControlListBox)中的 添加到Textbox Tag属性,以便您可以从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;
    }
于 2013-08-23T01:00:22.667 回答