0

如何从我的 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。

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

但我不明白我该怎么做。

有人可以帮我吗?先感谢您!

4

1 回答 1

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);
        }
    }
}

If anyone can explain for me what we're doing in this bunch of code - please do this, 'cause my brain is exploding right now :)

Thank you all!

于 2012-11-19T17:01:47.877 回答