The TextBlock
居住在一个DataTemplate
,因此我无法通过其名称来引用它。那么我该如何绑定它(例如)Text
以编程方式属性?
XAML:
<UserControl x:Class="MyNameSpace.MyCustomControl" ... >
...
<ListBox ItemsSource="{Binding Path=ItemsSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
...
</UserControl>
Code:
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"
Where SomeModelCollection
是一些数据模型属性,例如ObservableCollection<SomeModel>
(SomeModel
有一个属性叫做Name
)