从Silverlight中的LayoutRoot中查找控件

Bre*_*ead 5 silverlight

我的usercontrol上有多个文本块Layoutroot问题是如何通过名称找到特定的TextBlock?

感谢名单

her*_*ter 7

var myElement =
    ((FrameworkElement)System.Windows.Application.Current.RootVisual)
        .FindName("TextBlockName");
Run Code Online (Sandbox Code Playgroud)

如果已经渲染了文本块,则应该在这种情况下工作.

为了能够像@ColinE提到的那样更容易地遍历可视树,您还可以使用Silverlight工具包.

// requires System.Windows.Controls.Toolkit.dll
using System.Windows.Controls.Primitives;

var myElement = myRoot.GetVisualDescendants().OfType<TextBlock>()
    .Where(txb => txb.Name == "TextBlockName").FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)