查找段落UWP的父级

时间:2017-12-19 17:02:56

标签: c# uwp

我想找到段落的父级,名称为:" ParagraphOne" (因此RichTextBlock的名称为:" RichTextOne")但代码会生成异常。

Exception

的Xaml:

 <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <StackPanel>
            <RichTextBlock x:Name="RichTextOne" Margin="30">
                <Paragraph x:Name="ParagraphOne">
                    <Run Text="This is a Text"/>
                </Paragraph>
            </RichTextBlock>
            <Button x:Name="btnParent" Click="btnParent_Click" Margin="30" Width="100" Height="32" Content="Find Parent"/>
        </StackPanel>
    </Grid>
</Grid>

代码:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void btnParent_Click(object sender, RoutedEventArgs e)
    {
        var parent = VisualTreeHelper.GetParent(ParagraphOne) as UIElement;
        string pName = (parent as RichTextBlock).Name;
        var messageDialog = new MessageDialog("The name of parent is: " + pName);
        await messageDialog.ShowAsync();
    }
}

一种方式?提前谢谢!

生成的错误是:无法修复的错误(来自HRESULT的异常:0x8000FFFF(E_UNEXPECTED))

1 个答案:

答案 0 :(得分:2)

这应该有效:

RichTextBlock parent = ParagraphOne.ElementStart.Parent as RichTextBlock;