ListBoxItem中的查找列表框指数(ItemsTemplate指定可视内容) [英] Finding Listbox Index of ListBoxItem (ItemsTemplate to specify Visual COntent)

查看:387
本文介绍了ListBoxItem中的查找列表框指数(ItemsTemplate指定可视内容)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何找到一个ListBoxItem的索引,如果它被设置一个DataTemplate作为一个TextBox控件内?这里是WPF:

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> 

当我获得文本框的焦点(文字,势必一个ObservableCollection),我不能简单地用SelectionChanged事件的列表框。我想知道我怎么能确定我在获得焦点的文本框的索引。

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.

感谢

推荐答案

您可以绑定 AlternationCount Script.Count 然后添加 AlternationIndex 的ItemsControl (列表框)的文本框 标签属性,因此你可以从你的的GotFocus 事件处理程序访问。

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.

例如:

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

这篇关于ListBoxItem中的查找列表框指数(ItemsTemplate指定可视内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆