The TextBlock
resides in a DataTemplate
, thus I can\'t refer to it by its name. So how do I bind its (e.g.) Text
property programmatically
You can get TextBlock
using VisualTreeHelper
. This method will get you all TextBlockes present in Visual tree of listBoxItem:
public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj)
where T : DependencyObject
{
if( depObj != null )
{
for( int i = 0; i < VisualTreeHelper.GetChildrenCount( depObj ); i++ )
{
DependencyObject child = VisualTreeHelper.GetChild( depObj, i );
if( child != null && child is T )
{
yield return (T)child;
}
foreach( T childOfChild in FindVisualChildren<T>( child ) )
{
yield return childOfChild;
}
}
}
}
Usage :
TextBlock textBlock = FindVisualChildren<TextBlock>(listBoxItem)
.FirstOrDefault();
But I would still suggest to do the binding in XAML instead of doing it in code behind.
In case ItemSource
is ObservableCollection<MyModel>
and MyModel
contains property Name
, it can be done in XAML like this:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
Since DataContext
of ListBoxItem
will be MyModel
, hence you can bind directly to Name property like mentioned above.