How to programmatically bind a (dependency) property of a control that's inside a DataTemplate?

南楼画角 提交于 2019-12-02 04:21:11

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!