gpt4 book ai didi

wpf - 相对源和弹出

转载 作者:行者123 更新时间:2023-12-01 23:08:10 24 4
gpt4 key购买 nike

问题是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com