无法从课程中访问中心元素

时间:2015-09-09 05:24:26

标签: c# xaml windows-8.1

我在主页上有一个xaml,想要访问它的元素,比如x:Name =" D1P1"在c#类中,但不能使用它并得到错误名称" D1P1"在当前上下文中不存在任何想法如何访问c#类中的hub元素我使用FindName但它确实没有工作

<Hub>
        <HubSection Width="950" x:Name="DayOneTimeHubSection" Margin="20,0,0,0">
            <DataTemplate>
                <Grid>
                    <StackPanel Orientation="Vertical">
                        <StackPanel Orientation="Horizontal" Height="180" Margin="0,0,0,-15">
                            <StackPanel Width="280" Height="160" Background="#FF253842" Margin="05,0,0,0">
                                <TextBlock x:Name="D1P1"  HorizontalAlignment="Center" LineHeight="80" TextWrapping="Wrap"  FontSize="64" TextAlignment="Center" Foreground="#FFB0B1B2" FontFamily="Arial Narrow" Margin="0,10,0,0" />
                                <TextBlock x:Name="D1NP1" HorizontalAlignment="Center" VerticalAlignment="Bottom" LineHeight="64" TextWrapping="Wrap"  FontSize="64" TextAlignment="Center" Foreground="White" FontFamily="DengXian" Margin="30,0" />
                            </StackPanel>
                        </StackPanel>
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </HubSection>
    </Hub>

2 个答案:

答案 0 :(得分:0)

您可以使用此方法:

private DependencyObject FindControl<T>(DependencyObject control, string ctrlName)
{
   int childNumber = VisualTreeHelper.GetChildrenCount(control);
   for (int i = 0; i < childNumber; i++)
   {
      DependencyObject child = VisualTreeHelper.GetChild(control, i);
      FrameworkElement fe = child as FrameworkElement;
      if (fe == null) return null;

      if (child is T && fe.Name == ctrlName)
      {
         return child;
       }
       else
       {
          DependencyObject nextLevel = FindControl<T>(child, ctrlName);
          if (nextLevel != null)
             return nextLevel;
       }
    }
    return null;
 }

使用示例:

StackPanel mypanel = FindControl<StackPanel>(HubSection, "myPanel");

您需要传递其中一个顶级节点(如HubSection)的名称以及您用于控件的名称。

我希望你在说什么:D

答案 1 :(得分:0)

我找到了一个解决方案,并使用VisualTreeHelper的以下功能来实现它

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

并且每个人都可以使用所有elemet。

foreach (TextBlock tb in FindVisualChildren<TextBlock>(DayOneTimeHubSection))
        {
            //YOur Logic
        }