views:

212

answers:

2

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?

+4  A: 

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.

JaredPar
and if I have other textblocks (such as artist surname, age ...), do i have to set the DataContext of all those TextBlocks ?
Andreas Grech
@Dreas, in that case you should pick a parent element and set the DataContext there. It will be "inherited" by child elements
JaredPar
Excellent, works great! Thanks for the help JaredPar.
Andreas Grech
The DataContext is searched in all your Visual Tree, so if you want all your TextBlocks to have the same DataContext, set the DataContext at the Grid or Window level.
Nicolas Dorier
@Slashene, yup that's exactly what I did infact.
Andreas Grech
+4  A: 
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
    <Grid>
        <TextBlock Text="{Binding Artist.Name}"/>
    </Grid>
</Window>

HTH, Kent

Kent Boogaart
+1 Thanks for showing how's its done in xaml Kent
Andreas Grech