RelativeSource和Popup

Ale*_*kin 8 data-binding silverlight wpf binding

问题是RelativeSource在以下情况下不起作用.我使用silverlight 5.

//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";
}
Run Code Online (Sandbox Code Playgroud)

如果我在绑定上设置断点,我会得到错误:

System.Exception:BindingExpression_CannotFindAncestor.

如果我用ElementName=LayoutRoot而不是RelativeSource,一切都会好的.

为什么相对源绑定不起作用?

yo *_*han 8

Popup就像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; 
    }
Run Code Online (Sandbox Code Playgroud)

我希望这会有所帮助.不像在ContextMenu或Tooltip的情况下,在这里你还必须指定PlacementTarget.