2013-02-18 37 views
6

問題是RelativeSource在以下情況下不起作用。我使用Silverlight 5RelativeSource和Popup

//From MainPage.xaml 
<Grid x:Name="LayoutRoot" Background="White" Height="100" Width="200"> 
    <Popup IsOpen="True"> 
     <TextBlock Text="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType=Grid}}" /> 
    </Popup> 
</Grid> 

//From MainPage.xaml.cs 
public MainPage() 
{ 
    InitializeComponent(); 
    DataContext = "ololo"; 
} 

如果我設置綁定一個斷點,我會得到錯誤:如果我使用ElementName=LayoutRoot代替RelativeSource

System.Exception: BindingExpression_CannotFindAncestor.

,一切都會好的。

爲什麼相對源綁定不起作用?

回答

6

彈出窗口就像ContextMenu,ToolTip控件,它們不會添加到VisualTree中。爲此,您需要做的像

<Grid x:Name="LayoutRoot" Height="100" Width="200" Background="Black"> 
    <Popup Grid.Row="0" x:Name="popup" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}"> 
     <TextBlock Text="{Binding DataContext, ElementName=popup}" Background="Red" Width="30" Height="30" /> 
    </Popup> 
</Grid> 

public MainWindow() 
    { 
     InitializeComponent(); 
     DataContext = "abcd"; 
     popup.PlacementTarget = LayoutRoot; 
    } 

我希望這將在文本菜單或工具提示的情況下help.Not一樣,在這裏你還必須指定PlacementTarget。

+1

好的。彈出控制很明顯。有沒有在ComboBoxItemTemplate中使用相對源的方法? – 2013-02-18 17:22:47

-1

彈出窗口不是視覺樹的一部分。

Relative Source「通過指定綁定源相對於綁定目標(MSDN)位置的位置」來獲取或設置綁定源。由於彈出窗口不是顯示它的控件的可視化樹的一部分,因此無法解析彈出窗口之外的任何內容。

1

你可以做一個小黑客:通過資源設置DataContext。

<Grid.Resources> 
    <Style TargetType="TextBlock"> 
     <Setter Property="DataContext" Value="{Binding ElementName=myGrid, Path=DataContext}" /> 
    </Style> 
</Grid.Resources> 
2

正如其他人所說,這是因爲Popup不是視覺樹的一部分。相反,您可以使用Popup的PlacementTarget屬性返回到視覺樹:

<Grid x:Name="LayoutRoot" Background="White" Height="100" Width="200"> 
    <Popup IsOpen="True"> 
     <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Popup}}, 
            Path=PlacementTarget.DataContext}" /> 
    </Popup> 
</Grid>