如何使用其名称从Grid删除此元素 [英] How can I remove this element from Grid using its name

查看:209
本文介绍了如何使用其名称从Grid删除此元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友

此代码有效

hello friends

this code works

<Grid Name="Layout">
    <TextBlock Name="tbPrueba" Text="Prueba" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="50,20,0,0"/>
    <Button Name="buEliminar" Content="Eliminar" HorizontalAlignment="Left" VerticalAlignment="Top"
            Width="75" Margin="50,56,0,0" Click="buEliminar_Click"/>
</Grid>





private void buEliminar_Click(object sender, RoutedEventArgs e)
{
    UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
    Layout.Children.Remove(Hijo);
}



但是当我从代码中添加控件时,这不起作用



but when I add the control from code, this does not work

TextBlock MyTextBlock = new TextBlock()
{
    Name = "tbPrueba",
    Text = "Prueba",
    HorizontalAlignment = HorizontalAlignment.Left,
    VerticalAlignment = VerticalAlignment.Top,
    Margin = new Thickness(50, 20, 0, 0),
};
Layout.Children.Add(MyTextBlock);



...



...

        private void buEliminar_Click(object sender, RoutedEventArgs e)
        {
// Not work why ?
            UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
            Layout.Children.Remove(Hijo);
        }


请告诉我发生了什么


please tell me what''s going on

推荐答案

可能性1:
private void buEliminar_Click(object sender, RoutedEventArgs e)
{
 UIElement Hijo = (UIElement)LogicalTreeHelper.FindLogicalNode(Layout, "tbPrueba");
 //UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
 Layout.Children.Remove(Hijo);
}



详细信息:
http://msdn.microsoft.com/en-us/library/system. windows.logicaltreehelper.findologicnode.aspx [ ^ ]

可能性2:



Details:
http://msdn.microsoft.com/en-us/library/system.windows.logicaltreehelper.findlogicalnode.aspx[^]

Possibility 2:

TextBlock MyTextBlock = new TextBlock()
     {
       Name = "tbPrueba",
       Text = "Prueba",
       HorizontalAlignment = HorizontalAlignment.Left,
       VerticalAlignment = VerticalAlignment.Top,
       Margin = new Thickness(50, 20, 0, 0),
     };
     Layout.Children.Add(MyTextBlock);
     this.RegisterName("tbPrueba", MyTextBlock);







private void buEliminar_Click(object sender, RoutedEventArgs e)
{
 //UIElement Hijo = (UIElement)LogicalTreeHelper.FindLogicalNode(Layout, "tbPrueba");
 UIElement Hijo = Layout.FindName("tbPrueba") as UIElement;
 Layout.Children.Remove(Hijo);
}




关于这件事有一些记载:
http://stackoverflow.com/questions/1755377/why-cant-i-access-a-textbox-by-name-with-findname [




There is something written about that:
http://stackoverflow.com/questions/1755377/why-cant-i-access-a-textbox-by-name-with-findname[^]


这篇关于如何使用其名称从Grid删除此元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆