Windows应用商店,从存储在GridView项目的DataTemplate中的代码访问Canvas

时间:2012-11-18 23:26:07

标签: c# xaml gridview windows-store-apps

如何从C#代码访问存储在GridView项目的DataTemplate中的Canvas控件?

<DataTemplate x:Key="250x250ItemTemplate">
    <Grid HorizontalAlignment="Left" Width="250" Height="250">
        <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
            <Canvas x:Name="Canv"/>  <------ I WANT ACCESS THIS CANVAS FROM C# CODE
        </Border>
    </Grid>
</DataTemplate>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <GridView x:Name="GridViewData" ItemTemplate="{StaticResource 250x250ItemTemplate}"/>
</Grid>

我正在从C#代码填充GridViewData项目,使用来自远程加载的XML的数据设置GridViewData.ItemsSource。

然后我需要分别修改每个元素的Canvas(通过添加子元素)。

但我不明白我该怎么做。

任何人都可以帮助我吗? 提前谢谢!

1 个答案:

答案 0 :(得分:1)

每个有兴趣回答这个问题的人! 我在这里找到了一个解决方案:http://www.wiredprairie.us/blog/index.php/archives/1730

我不明白为什么我们需要在这里做太多魔术,这很可怕,但它确实有效。

namespace Extension
{
    public static class FrameworkElementExtensions
    {
        public static FrameworkElement FindDescendantByName(this FrameworkElement element, string name)
        {
            if (element == null || string.IsNullOrWhiteSpace(name))
            {
                return null;
            }
            if (name.Equals(element.Name, StringComparison.OrdinalIgnoreCase))
            {
                return element;
            }
            var childCount = VisualTreeHelper.GetChildrenCount(element);
            for (int i = 0; i < childCount; i++)
            {
                var result = (VisualTreeHelper.GetChild(element, i) as FrameworkElement).FindDescendantByName(name);
                if (result != null)
                {
                    return result;
                }
            }
            return null;
        }
    }
}

for (int i = 0; i<GridViewTickers.Items.Count; i++)
{
    var element = GridViewTickers.ItemContainerGenerator.ContainerFromIndex(i) as FrameworkElement;
    if (element != null)
    {
        var tb = element.FindDescendantByName("Canv") as Canvas;
        if (tb != null)
        {
            TextBlock tb1 = new TextBlock();
            tb1.Text = "hello";
            tb.Children.Add(tb1);
        }
    }
}

如果有人能够解释我们在这堆代码中做了什么 - 请这样做,'因为我的大脑现在正在爆炸:)

谢谢大家!

相关问题