2014-03-26 24 views
2

我有一個名爲「CardDisplay」的用戶控件,它有一個名爲「CardValue」的公開的依賴屬性。控制本身基本上是一個文本塊(圖像真的,但它與一個文本塊,是更容易顯示)綁定到該財產,像這樣:爲什麼將綁定數據上下文設置爲控件的數據上下文?

<UserControl> 
    <Grid> 
     <TextBlock Text="{Binding CardValue}"/> 
    </Grid> 
</UserControl> 

數據上下文設置爲this代碼爲簡單起見,儘管它也適用於標準視圖模型。這工作正常,如果你這樣使用它:

<local:CardDisplay CardValue="2"/> 

「2」出現在控件中的預期。但是,如果我把上面一行

<local:CardDisplay CardValue="{Binding CurrentCard}"/> 

不顯示任何內容,我也得到一個結合異常說「CurrentCard」無法在類型「DisplayCard」中找到。顯然,它不應該看顯示卡,它應該看父母的數據上下文(當然,這有一個名爲「CurrentCard」的屬性)。如預期

切換到「的ElementName」結合的作品:

<TextBock x:Name="HiddenText" Text="{Binding CurrentCard}"/> 
<local:CardDisplay CardValue="{Binding Path=Text, ElementName=HiddenText}"/> 

基本上,我很茫然,爲什麼我綁定突然停止尋找在正確的位置。同樣的行爲可以用一個簡單的數據模板被視爲得好:

<DataTemplate x:Key="CardTemplate"> 
    <Image Source="{Binding Converter={StaticResource IntToImgSourceConverter}"/> 
</DataTemplate> 

<ContentPresenter ContentTemplate="{StaticResource CardTemplate}" Content="{Binding CurrentCard}"/> 

將拋出一個異常約束力說,它不能對「INT」類型找到一個名爲「CurrentCard」屬性。

爲什麼父級綁定嘗試在子數據上下文中查找屬性?從子修復中刪除數據上下文(綁定再次按預期工作),但似乎不應該有必要。

編輯: 需要說明的是,在設置數據上下文之後,綁定DP基本上是無用的。如果我的綁定是正確的,那麼讓它使用父級的數據上下文的最好方法是什麼?使用情況下,我想的是讓這個工作:

<ItemsControl ItemsSource={Binding PlayerHand}> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <local:CardDisplay CardValue="{Binding Path=CardValue}"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

回答

3

這種結合:

<local:CardDisplay CardValue="{Binding CurrentCard}"/> 

從綁定源目前DataContext指結合路徑CurrentCard。由於您在代碼隱藏中設置UserControl的DataContext,因此它不會繼承父代DataContext,因此會得到綁定錯誤。 DataContext只有在您未將其設置爲子級別時才從父級DataContext繼承。

在另一邊,這種結合工作正常:

<local:CardDisplay CardValue="{Binding Path=Text, ElementName=HiddenText}"/> 

因爲這一個無關當前DataContext。它明確將元素設置爲綁定源而不是當前DataContext

相關問題