2009-04-25 63 views
0

我在WindowArtistInfo)中有以下Xaml:WPF:關於依賴屬性的基本問題

<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將填充Artist的名稱。

我在這裏缺少什麼?

回答

4
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...> 
    <Grid> 
     <TextBlock Text="{Binding Artist.Name}"/> 
    </Grid> 
</Window> 
+0

+1感謝您展示xaml Kent如何完成它 – 2009-04-25 15:19:31

5

我沒有看到的唯一的事情是你更新TextBlock的綁定源。首先添加一個名字到TextBlock

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

然後在構造函數中

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

編輯 OP提到,可能有不止一個的TextBlock或子元素更新的DataContext值。

在這種情況下,我會對最接近所有值的父對象執行上述技巧。在這種情況下,網格控件。 DataContext屬性將被所有內部孩子繼承。

+0

如果我有其他文本塊(如藝術家姓氏,年齡...),我必須設置所有這些TextBlocks的DataContext? – 2009-04-25 15:11:03

+1

@Dreas,在這種情況下,你應該選擇一個父元素並在那裏設置DataContext。它會被子元素「繼承」 – JaredPar 2009-04-25 15:11:55

+0

非常棒,效果很棒!感謝JaredPar的幫助。 – 2009-04-25 15:14:09