【发布时间】:2014-03-12 08:45:59
【问题描述】:
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>
代码:
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>(SomeModel 有一个名为Name 的属性)
【问题讨论】:
-
d 'Textblock' 打算展示什么......作为 'MemberPath' 是什么...... d itemsource 是什么......
-
@Sankarann - 我添加了
MemberPath- 它旨在从外部绑定TextBlock的Path属性(即在我嵌入MyCustomControl的XAML 中) -
@Sankarann - 还添加了一个预期的用法示例
-
所以
MemberPath只有一个值,并且与TextBox.Text.. 绑定意味着所有列表项将显示与MemberPath.. 中相同的值。对吗? -
这里每个
ListItem都持有MyModel作为它的DataContext。因此,如果您想绑定Name,您可以使用<TextBlock Text="{Binding Name}"/>... 仍然不清楚您与MemberPath和TextBlock.Text的关系如何......
标签: c# wpf binding datatemplate