如何以编程方式绑定DataTemplate内部控件的(依赖)属性?
TextBlock
驻留在DataTemplate
,因此我无法通过其名称来引用它。 那么如何以编程方式绑定其(例如) Text
属性?
XAML:
... ...
码:
public partial class MyCustomControl : UserControl { ... public static readonly DependencyProperty DataSourceProperty = DependencyProperty.Register("DataSource", typeof (IEnumerable), typeof (MyCustomControl), new PropertyMetadata(default(IEnumerable))); public IEnumerable DataSource { get { return (IEnumerable) GetValue(DataSourceProperty); } set { SetValue(DataSourceProperty, value); } } public static readonly DependencyProperty MemberPathProperty = DependencyProperty.Register("MemberPath", typeof (string), typeof (MyCustomControl), new PropertyMetadata(default(string))); public string MemberPath { get { return (string) GetValue(MemberPathProperty); } set { SetValue(MemberPathProperty, value); } } ... public MyCustomControl() { InitializeComponent(); var binding = new Binding(MemberPath); BindingOperations.SetBinding(/*how do I refer to the TextBlock here ???*/, TextBox.TextProperty, binding); } ... }
预期用法示例:
<my:MyCustomControl DataSource="{Binding Path=SomeModelCollection}" MemberPath="Name"
SomeModelCollection
是一些数据模型属性,如ObservableCollection
( SomeModel
有一个名为Name
的属性)
您可以使用VisualTreeHelper
获取TextBlock
。 此方法将获取listBoxItem的Visual树中存在的所有TextBlockes:
public IEnumerable FindVisualChildren (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 ( child ) ) { yield return childOfChild; } } } }
用法:
TextBlock textBlock = FindVisualChildren(listBoxItem) .FirstOrDefault();
但我仍然建议在XAML中进行绑定,而不是在后面的代码中进行绑定。
如果ItemSource
是ObservableCollection
并且MyModel
包含属性Name
,则可以在XAML中完成,如下所示:
由于ListBoxItem
DataContext
将是MyModel
,因此您可以直接绑定到Name属性,如上所述。