不要从此类获取对XAML元素的引用

问题描述 投票:0回答:1

为了让我将在我的班级中插入几次的兼职,我创建了一个新的XAML元素:

<Page
    x:Class="App1.EntryPage_Field"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Name="GridItem" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Width="300" Height="400">
        <TextBlock Text="test"></TextBlock>
    </Grid>
</Page>

现在我想获取GridItem并将其放在我的类中,但我无法获得它的引用。

            Grid el = (Grid)EntryPage_Field.FindName("GridItem");
            ViewGrid.Items.Add(el);

根本不编译。

            Grid el = (Grid)FindName("GridItem");
            ViewGrid.Items.Add(el);

崩溃为el为空。

只是为了澄清,我希望每次使用它时我的同伴都是空的,所以也许我应该在某个地方打电话给新人?

c# xaml uwp uwp-xaml
1个回答
0
投票

要从页面获取GridItem Grid,您可以使用EntryPage_Field类对象实例。

尝试以下代码从GridItem类获取EntryPage_Field,然后将其放入ViewGrid网格女巫在另一页。在将GridItem添加到ViewGrid之前,您应该确保GridItem不是其他Control或页面的子项。

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    EntryPage_Field myPage = new EntryPage_Field();
    Grid myGrid = (Grid)myPage.FindName("GridItem");
    myPage.Content = null;
    ViewGrid.Children.Add(myGrid);
}
© www.soinside.com 2019 - 2024. All rights reserved.