Reputation: 10672
I have a multiple textblocks on my usercontrol Layoutroot the problem is how can I find a particular TextBlock by its name?
Thanx
Upvotes: 5
Views: 9962
Reputation: 11
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
}
Upvotes: 1
Reputation: 11287
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();
Upvotes: 7
Reputation: 70142
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");
Upvotes: 3