WPF:有关依赖属性的基本问题
我在 Window
(ArtistInfo
) 中有以下 Xaml:
<Grid>
<TextBlock Text="{Binding Artist.Name}"></TextBlock>
</Grid>
这是同一窗口的代码隐藏(为了问题而简化了代码 ):
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);
}
基本上我想要做的是将数据绑定到依赖属性,这样当填充 Artist
时(在构造函数中),TextBlock
就会填充艺术家的名字。
我在这里缺少什么?
I have the following Xaml in a Window
(ArtistInfo
):
<Grid>
<TextBlock Text="{Binding Artist.Name}"></TextBlock>
</Grid>
And this is the code-behind for the same window (code simplified for question's sake):
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);
}
Basically what I'm trying to do is data binding to a Dependency Property, so that when Artist
is populated (in the constructor), the TextBlock
gets filled with the Artist's name.
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我唯一没有看到的是您更新 TextBlock 的绑定源。 首先为 TextBlock 添加名称,
然后在构造函数中更新 DataContext 值
EDIT OP 提到可能有多个 TextBlock 或子元素。
在这种情况下,我会对最接近所有值的父对象执行上述技巧。 在本例中为网格控件。 可以这么说,所有内部子级都将继承 DataContext 属性。
The only thing I didn't see was you updating the Binding source for the TextBlock. First add a name to the TextBlock
Then update the DataContext value in the constructor
EDIT OP mentioned that there may be more than one TextBlock or child element.
In that case I would do the above trick for the closest parent object to all of the values. In this case the Grid control. The DataContext property will be inherited so to speak by all of the inner children.