开发者

Find control from LayoutRoot in Silverlight

I have a multiple textblocks on m开发者_StackOverflow社区y usercontrol Layoutroot the problem is how can I find a particular TextBlock by its name?

Thanx


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();


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");


hey Masn i was write some code and similiar conditions in my case that all ok. this is the case (have many listbox and named variables diferenciated by number in final the name Example: listAttachment1,listAttachment2,listAttachment3,..,etc). To best explication show 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

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜