TextBlock
駐留在DataTemplate
,因此我不能用它的名字來引用它。那麼如何以編程方式將其(例如)Text
屬性綁定?如何以編程方式綁定DataTemplate內的控件的(依賴項)屬性?
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
@Sankarann - 我添加了'MemberPath' - 它的目的是綁定'Path'屬性從外部(即在我嵌入'MyCustomControl'的XAML中'TextBlock') – Tar
@Sankarann - 也添加了一個預期的用法示例 – Tar