WPF:有关依赖属性的基本问题

发布于 2024-07-17 18:49:25 字数 809 浏览 5 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰ゝ天使的微笑 2024-07-24 18:49:25

我唯一没有看到的是您更新 TextBlock 的绑定源。 首先为 TextBlock 添加名称,

<TextBlock Name="m_tb" ... />

然后在构造函数中更新 DataContext 值

public ArtistInfo() {
 ...
 m_tb.DataContext = this;
}

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

<TextBlock Name="m_tb" ... />

Then update the DataContext value in the constructor

public ArtistInfo() {
 ...
 m_tb.DataContext = this;
}

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.

想念有你 2024-07-24 18:49:25
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
    <Grid>
        <TextBlock Text="{Binding Artist.Name}"/>
    </Grid>
</Window>
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
    <Grid>
        <TextBlock Text="{Binding Artist.Name}"/>
    </Grid>
</Window>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文