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

前端 未结 1 1577
闹比i
闹比i 2021-01-25 18:05

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

相关标签:
1条回答
  • 2021-01-25 18:28

    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.

    0 讨论(0)
提交回复
热议问题