我正在开发一个UWP应用程序,试图使用Transform3DAnimations
代替GridView
从平台示例中实现HubSection
。除了获取GridViewItem
之外,我已经弄明白了。以下代码来自上下文中的示例到hubsection。
private void UpdateRandomSection()
{
// Updating the section triggers a cool animation!
// See SectionView.xaml and SectionView.xaml.cs
var sectionsInView = HeadlinesHub.SectionsInView;
var sectionsCount = sectionsInView.Count;
if (sectionsCount > 0)
{
var sectionToUpdate = sectionsInView[_random.Next(sectionsCount)];
sectionToUpdate.DataContext = new HeroArticlesViewModel();
}
}
我正在尝试抓取GridViewItem
,但我无法获取GridViewItem
它总是返回GridViewItem
的数据模型。如何从GridViewItem
获取GridView
?我的代码如下:
private Random InAppLiveTileRandomTileNumberGenerator;
private void UpdateRandomSection()
{
var sectionsInView = AllDevicesGridView.Items;
var sectionsCount = sectionsInView.Count;
if (sectionsCount > 0)
{
var sectionToUpdate = (GridViewItem)AllDevicesGridView.Items[InAppLiveTileRandomTileNumberGenerator.Next(sectionsCount)]; //Invalid Cast exception here
sectionToUpdate.DataContext = new InappLiveTileViewModelModel();
}
}
答案 0 :(得分:1)
对于您的代码行var sectionToUpdate = (GridViewItem)AllDevicesGridView.Items[InAppLiveTileRandomTileNumberGenerator.Next(sectionsCount)];
,它将返回您看到的GridViewItem
的数据模型。要获得GridViewItem
,您可能需要使用ContainerFromItem
方法。例如,如果要从所选项目代码中获取GridViewItem
对象,则可以如下所示:
private void listViewDirectory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var container = AllDevicesGridView.ContainerFromItem(AllDevicesGridView.SelectedItem);
GridViewItem item = container as GridViewItem;
System.Diagnostics.Debug.WriteLine(item.ActualHeight);
}
您似乎想要获得一个分配了项目索引的特殊项目:
var container = AllDevicesGridView.ContainerFromItem(AllDevicesGridView.Items[1]);
GridViewItem item = container as GridViewItem;
如果您想获取GridViewItem
的数据上下文,则可能需要从GridViewItem
获取ListViewItemPresenter
。在这里,我使用VisualTreeHelper
获取ListViewItemPresenter
。顺便说一句,除非您没有其他方法,否则不建议使用VisualTreeHelper
。
private void listViewDirectory_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var container = AllDevicesGridView.ContainerFromItem(AllDevicesGridView.Items[1]);
GridViewItem item = container as GridViewItem;
ListViewItemPresenter itempresenter;
IEnumerable<ListViewItemPresenter> items = FindVisualChildren<ListViewItemPresenter>(item);
int count = items.Count();
itempresenter = items.ElementAt<ListViewItemPresenter>(0);
itempresenter.DataContext = new Person() { Name = "update", Contact = "update" };
}
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}