相对来源和弹出窗口 [英] RelativeSource and Popup
问题描述
问题是 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:
系统异常:BindingExpression_CannotFindAncestor.
System.Exception: BindingExpression_CannotFindAncestor.
如果我使用 ElementName=LayoutRoot
而不是 RelativeSource
,一切都会好的.
If I use ElementName=LayoutRoot
instead of RelativeSource
, everything will be OK.
为什么相对源绑定不起作用?
Why does the relative source binding not work?
推荐答案
Popup 就像 ContextMenu 、 ToolTip 控件,它们没有添加到 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;
}
我希望这会有所帮助.不像 ContextMenu 或 Tooltip 的情况,在这里您还必须指定 PlacementTarget.
I hope this will help.Not like in case of ContextMenu or Tooltip , here you will also have to specify the PlacementTarget.
这篇关于相对来源和弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!