Find a control from LayoutRoot in Silverlight

I have several text blocks in my usercontrol Layoutroot The problem is, how can I find a specific TextBlock by its name?

Thanx

+5
source share
3 answers
var myElement =
    ((FrameworkElement)System.Windows.Application.Current.RootVisual)
        .FindName("TextBlockName");

should work in this case if the text block has already been processed.

To be able to easily traverse the visual tree as a whole, for example, @ColinE, 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();
+7
source

If you create a UserControl, any element that you call using x:Nameshould be available to you as a field in the code.

UserControl, Linq to VisualTree...

TextBlock block = LayoutRoot.Descendants<TextBlock>()
                            .Cast<TextBlock>()
                            .SingleOrDefault(t => t.Name == "TextBlockName");
+3

Hey Masn, I wrote code and similar conditions in my case that everything is in order. this is the case (there are many lists and named variables, differentiated by the number in the final name. Example: listAttachment1, listAttachment2, listAttachment3, .. etc.). For a better explanation of my code:

public void refreshAttachmentList (ListlistOfControlsRequest, int identifier) ​​{

    string valueName = "attachmentsField_"+identifier;

        var mylistAttachment = ((FrameworkElement)System.Windows.Application.Current.RootVisual).FindName(valueName);
        ListBox listAttachRequest = mylistAttachment as ListBox;

        listAttachRequest.ClearValue(ItemsControl.ItemsSourceProperty);
        listAttachRequest.ItemsSource = listOfAttachmentsControls;
        listAttachRequest.....all properties

}

+1
source

All Articles