【问题标题】:how to get or set the the item index of a textbox in a listview如何在列表视图中获取或设置文本框的项目索引
【发布时间】:2017-12-25 19:32:24
【问题描述】:

我已经搜索了又搜索了,但我似乎无法找到我(可能错误地)认为是一个非常简单的问题的答案。

我有列表视图,用户可以使用按钮和 OpenFileDialog 将项目添加到其中。这行得通。

问题如下:

列表视图中的一列包含一个文本框。我希望用户能够向文本框添加(数字)值,并且该值将与项目(在该行中)相关联。我在其中一列中创建了一个文本框,经过非常广泛的搜索后,我添加了 LostFocus 选项以获取它的值(即文本框值)。现在的问题是 listview 中的 selecteditem 的索引并不总是设置(可能是因为在 lostfocus 调用之前选择了该项目)。这导致 selectedindex 为-1,所以我不知道哪个项目应该与文本框中的文本相关联。

我也尝试过使用鼠标单击事件来帮助我选择正确的项目,但这也没有成效。

我正在使用 listviewwpf,所以我遇到的许多解决方案似乎都无关紧要。此外,我对 wpf 非常陌生(也是一名业余程序员),所以我无法理解复杂的解决方案......但是,我相信这个问题可能并不像看起来那么复杂。

请帮忙。

这是我的代码:

<ListView.View>
    <GridView>
        <GridViewColumn Width="30" Header="Num" DisplayMemberBinding="{Binding Num}" />
        <GridViewColumn Width="100" Header="Name" DisplayMemberBinding="{Binding Name}" />
        <GridViewColumn Width="50" Header="FromPage">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <TextBox x:Name="txt_TBFromPage" LostFocus="txt_FromPage_LostFocus" Text="{Binding SelectedItem, Mode=TwoWay, ElementName=txtValue}"/>
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
    </GridView>
</ListView.View>

这是c#部分:

private void txt_FromPage_LostFocus(object sender, RoutedEventArgs e){
    int Index = MyListView.SelectedIndex;

    Index = MyListView.Items.IndexOf(MyListView.SelectedItem);

    try {
        //Get cell value by using sender Object
        string TextValue = ((System.Windows.Controls.TextBox)sender).Text;

        MyItem item = (MyItem)MyListView.Items[Index];
        item.FromPage = TextValue;

    }

    catch (Exception) {

    }
}

【问题讨论】:

    标签: c# wpf listview


    【解决方案1】:

    您可以添加以下内容:

    .cs

        private void txt_TBFromPage_GotFocus(object sender, RoutedEventArgs e)
        {
            this.MyListView.SelectedItem = (sender as FrameworkElement).DataContext;
        }
    

    .xaml

        <TextBox x:Name="txt_TBFromPage" GotFocus="txt_TBFromPage_GotFocus"  LostFocus="txt_TBFromPage_LostFocus"  Text="{Binding SelectedItem, Mode=TwoWay, ElementName=txtValue}" />
    

    符合您的需求?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多