Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

wpf - RelativeSource and Popup

The problem is that RelativeSource does not work in the following case. I use 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";
}

If I set a breakpoint on the binding, I'll get Error:

System.Exception: BindingExpression_CannotFindAncestor.

If I use ElementName=LayoutRoot instead of RelativeSource, everything will be OK.

Why does the relative source binding not work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Popup is like ContextMenu , ToolTip controls , They are not added to the VisualTree. For this you will have to do like

<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; 
    }

I hope this will help.Not like in case of ContextMenu or Tooltip , here you will also have to specify the PlacementTarget.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...