Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find control from LayoutRoot in Silverlight

Tags:

silverlight

I have a multiple textblocks on my usercontrol Layoutroot the problem is how can I find a particular TextBlock by its name?

Thanx

like image 756
BreakHead Avatar asked Feb 22 '11 09:02

BreakHead


2 Answers

var myElement =
    ((FrameworkElement)System.Windows.Application.Current.RootVisual)
        .FindName("TextBlockName");

should work in this case, if the textblock has already been rendered.

To be able to easily traverse the visual tree more generally like @ColinE mentioned, you can also use the Silverlight toolkit.

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

var myElement = myRoot.GetVisualDescendants().OfType<TextBlock>()
    .Where(txb => txb.Name == "TextBlockName").FirstOrDefault();
like image 60
herzmeister Avatar answered Sep 26 '22 17:09

herzmeister


If you are creating a UserControl, any element that you name via x:Name should be available to you as a field in your code-behind.

If you are not creating a UserControl, you can search the visual tree via Linq to VisualTree ...

TextBlock block = LayoutRoot.Descendants<TextBlock>()
                            .Cast<TextBlock>()
                            .SingleOrDefault(t => t.Name == "TextBlockName");
like image 33
ColinE Avatar answered Sep 22 '22 17:09

ColinE