问题描述
问题是,的RelativeSource
不会在以下情况下工作。我使用Silverlight 5。
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的:BindingEx pression_CannotFindAncestor
如果我用的ElementName = LayoutRoot
而不是的RelativeSource
,一切都会好的。
If I use ElementName=LayoutRoot
instead of RelativeSource
, everything will be OK.
为什么相对源绑定不起作用?
Why does the relative source binding not work?
推荐答案
弹出像文本菜单,工具提示控制,他们不加入的VisualTree。为此,您需要做的像
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;
}
我希望这将在文本菜单或工具提示的情况下help.Not一样,在这里你还必须指定PlacementTarget。
I hope this will help.Not like in case of ContextMenu or Tooltip , here you will also have to specify the PlacementTarget.
这篇关于的RelativeSource和弹出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!