【问题标题】:Get the TextBlock in a ListView in Windows 8.1在 Windows 8.1 的 ListView 中获取 TextBlock
【发布时间】:2014-10-20 15:50:50
【问题描述】:

我使用的是 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 个文本框?

谢谢。

【问题讨论】:

    标签: windows-phone


    【解决方案1】:

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

    <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.
    */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 2016-11-04
      • 2014-10-17
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多