【问题标题】:Windows Store, Accessing Canvas from code stored in DataTemplate of GridView itemWindows 应用商店,从存储在 GridView 项的 DataTemplate 中的代码访问 Canvas
【发布时间】:2012-11-18 23:26:07
【问题描述】:

如何从我的 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(通过添加子元素)。

但我不明白我该怎么做。

有人可以帮我吗? 提前谢谢!

【问题讨论】:

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


    【解决方案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);
            }
        }
    }
    

    如果有人可以为我解释我们在这堆代码中所做的事情 - 请这样做,因为我的大脑现在正在爆炸 :)

    谢谢大家!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 2014-01-06
      • 2012-12-17
      • 2014-07-02
      • 2013-05-25
      • 1970-01-01
      相关资源
      最近更新 更多