And*_*ech 0 c# data-binding wpf xaml dependency-properties
我在Window(ArtistInfo)中有以下Xaml :
<Grid>
<TextBlock Text="{Binding Artist.Name}"></TextBlock>
</Grid>
Run Code Online (Sandbox Code Playgroud)
这是同一个窗口的代码隐藏(为了问题简化了代码):
public static readonly DependencyProperty ArtistProperty =
DependencyProperty.Register("Artist", typeof(Artist), typeof(ArtistInfo));
Artist Artist {
get {
return (Artist)GetValue(ArtistProperty);
}
set {
SetValue(ArtistProperty, value);
}
}
public ArtistInfo() {
InitializeComponent();
}
public ArtistInfo(int artistID) {
InitializeComponent();
Artist = GetArtist(artistID);
}
Run Code Online (Sandbox Code Playgroud)
基本上我正在尝试做的是数据绑定到依赖属性,因此当Artist填充(在构造函数中)时,TextBlock将填充Artist的名称.
我在这里错过了什么?
我唯一没看到的是你更新TextBlock的绑定源.首先为TextBlock添加一个名称
<TextBlock Name="m_tb" ... />
Run Code Online (Sandbox Code Playgroud)
然后更新构造函数中的DataContext值
public ArtistInfo() {
...
m_tb.DataContext = this;
}
Run Code Online (Sandbox Code Playgroud)
编辑 OP提到可能有多个TextBlock或子元素.
在这种情况下,我会针对所有值的最近父对象执行上述技巧.在这种情况下,网格控件.DataContext属性将被所有内部子节点继承.
| 归档时间: |
|
| 查看次数: |
463 次 |
| 最近记录: |