在Windows 8.1中的ListView中获取TextBlock

时间:2014-10-20 07:25:42

标签: windows-phone

我使用的是Windows 8.1。我有一个使用ItemsSource属性填充的ListView。 在我的ListView.ItemTempalte中,它有一个TextBox。

<ListView
      ItemsSource="{Binding CollectionGroups, Source={StaticResource GroupedData}}">
      <ListView.ItemTemplate>
        <DataTemplate>
           <TextBox Text="{Binding Group.Property1}" 
                      Foreground="Black" FontSize="18" />
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>

我的问题是如何在C#代码中获取最后一项文本框?我在上面显示的xaml页面背后的代码?例如,我的CollectionGroups中有10个项目,我的列表视图应该有10个文本框。如何获取列表视图的第10个文本框?

谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您需要为标记指定名称:

<ListView
  ItemsSource="{Binding CollectionGroups, Source={StaticResource GroupedData}}" x:Name="lvGroupData">
  <ListView.ItemTemplate>
    <DataTemplate>
       <TextBox Text="{Binding Group.Property1}" 
                  Foreground="Black" FontSize="18" x:Name="tbProperty1" />
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

然后你需要一个VisualTreeHelper方法(这是标准的方法,你会发现在整个网络上或多或少都像这样的方法):

public T FindElementByName<T>(DependencyObject element, string sChildName) where T : FrameworkElement
{
    T childElement = null;
    var nChildCount = VisualTreeHelper.GetChildrenCount(element);
    for (int i = 0; i < nChildCount; i++)
    {
        FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;

        if (child == null)
            continue;

        if (child is T && child.Name.Equals(sChildName))
        {
            childElement = (T)child;
            break;
        }

        childElement = FindElementByName<T>(child, sChildName);

        if (childElement != null)
            break;
    }
    return childElement;
}

现在您可以访问所需的元素:

this.UpdateLayout(); 
// Get the last item here
var lvItem = this.lvGroupData.Items[this.lvGroupData.Items.Count - 1];
var container = this.lvGroupData.ContainerFromItem(lvItem);
// NPE safety, deny first
if (container == null)
    return;
var textboxProperty1 = FindElementByName<TextBox>(container, "tbProperty1");
// And again deny if we got null
if (textboxProperty1 == null)
    return;
/*
  Start doing your stuff here.
*/