I have a multiple textblocks on my 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With