wpf - 相对源和弹出

标签 wpf silverlight data-binding binding

问题是 RelativeSource在以下情况下不起作用。我用银光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";
}

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

System.Exception: BindingExpression_CannotFindAncestor.



如果我使用 ElementName=LayoutRoot而不是 RelativeSource , 一切都会变好。

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

最佳答案

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

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

关于wpf - 相对源和弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14939632/

相关文章:

c# - 如何将网格绑定(bind)到 WPF 中选定的 TreeView 项

silverlight - 从 DataTemplate 中绑定(bind)?

c# - 如何在 Silverlight TextBlock 中用省略号截断字符串?

c# - Silverlight 类库到 Windows Phone 7 类库

java - xjc 仅用于模式的一部分

c# - 创建一个单一的键绑定(bind),每次用任何数字按下控件时都会触发一个命令,然后将该数字作为参数传递?

c# - 从 WPF 应用捕获视频

c# - 公开多个数据绑定(bind)源

c# - 如何将 Canvas 绑定(bind)到矩形列表

wpf - 通过 WPF 中的 MVVM 模式更改按钮背景颜色