문제

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

도움이 되었습니까?

해결책

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;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top