如何从ListView中的模板化数据中获取UIElement?

时间:2014-09-28 02:04:11

标签: c# xaml windows-runtime windows-phone-8.1

好吧,我觉得这有点愚蠢但是,我有一个带有模板类MyClass的列表视图或者其他什么,每当我" myListView.Add(new MyClass())" winrt平台在那里添加了一个新的UIElement,并将正确的属性正确地绑定到它们正确的元素中,现在,我希望能够遍历这些逻辑项(myListView.Items或myListView.SelectedItems)并获得相应的动画UIElement,那可能吗?

例如

class PhoneBookEntry {
    public String Name { get;set }
    public String Phone { get;set }
    public PhoneBookEntry(String name, String phone) {
        Name = name; Phone = phone;
    }
};

myListView.Add(new PhoneBookEntry("Schwarzeneger", "123412341234");
myListView.Add(new PhoneBookEntry("Stallone", "432143214321");
myListView.Add(new PhoneBookEntry("Statham", "567856785678");
myListView.Add(new PhoneBookEntry("Norris", "666666666666");

在XAML中(只是一个例子,所以我可以解释我的意思)

<ListView.ItemTemplate>
     <DataTemplate>
         <Grid>
              <TextBlock Text="{Binding Name}"/>
              <TextBlock Text="{Binding Phone}"/>
         </Grid>
     </DataTemplate>
</ListView.ItemTemplate>

所以,我的观点和目标是

foreach(PhoneBookEntry pbe in myListView.Items) // or SelectedItems 
{
    UIElement el; // How can I get the UIElement associated to this PhoneBookEntry pbe?
    if(el.Projection == null)
        el.Projection = new PlaneProjection;
    PlaneProjection pp = el.Projection as PlaneProjection;
    // Animation code goes here.
    if(myListView.SelectedItems.Contains(pbe)
        //something for selected
    else
        //something for not selected
}

我只需要一种获取UIElement的方法,该UIElement用于在模板化列表视图中表示此逻辑数据类PhoneBookEntry。 此外,这种必要性带来了一个非常大的问题,我在哪里,所选择的项目在Windows Phone上没有视觉上的差异-_-任何想法?

2 个答案:

答案 0 :(得分:2)

好的,我可能看起来像个傻瓜回答我自己的问题,但我已经找到了出路。

首先要做的事情是:ListViews只为列表中的确定项创建UIElements(缓存和显示的项)。因此,如果您确实向myListView.Items添加了2000个项目,则表示这些项目的UIElements的有效数量将为56或接近数字。 因为,ItemListView模拟了UIElements,即使它们不在那里,只是为了给滚动条提供大小和位置(因此为什么向下滚动非常大的列表会导致一些延迟,WinRT正在卸载UIElements并加载新的)? p>

由此,我发现我可以通过

简单地遍历当前加载的UIElements列表
// For each of the cached elements
foreach(LIstViewItem lvi in myListView.ItemsPanelRoot.Children) 
{
    // Inside here I can get the base object used to fill the data template using:
    PhoneBookEntry pbe = lvi.Content as PhoneBookEntry;
    if(pbe.Name == "Norris")
        BeAfraid();
    // Or check if this ListViewItem is or not selected:
    bool isLviSelected = lvi.IsSelected;
    // Or, like I wanted to, get an UIElement to animate projection
    UIElement el = lvi as UIElement;
    if(el.Projection == null)
        el.Projection = new PlaneProjection();
    PlaneProjection pp = el.Projection as PlaneProjection;
    // Now I can use pp to rotate, move and whatever with this UIElement.
}

所以,就是这样。在我的鼻子底下......

答案 1 :(得分:2)

您还可以使用ListView.ContainerFromItem或ListView.ContainerFromIndex方法,这些方法将返回列表视图中给定项目的容器UI元素(当然,仅在生成容器时)