Wpf 弹出控件与父控件一起移动

Wpf 弹出控件与父控件一起移动,wpf,Wpf,希望这是一个快速为您的WPF专家在这里。是否有任何简单的XAML解决方案允许我的弹出窗口在寡妇移动或更改大小时移动?代码如下。如果不是,我总是可以在代码隐藏中处理事件 <Grid> <Canvas> <Expander Header="details" HorizontalAlignment="Center" VerticalAlignment="Top" ExpandDirection="Down" Ex

希望这是一个快速为您的WPF专家在这里。是否有任何简单的XAML解决方案允许我的弹出窗口在寡妇移动或更改大小时移动?代码如下。如果不是,我总是可以在代码隐藏中处理事件

<Grid>
    <Canvas>
        <Expander Header="details" HorizontalAlignment="Center" VerticalAlignment="Top" ExpandDirection="Down"
                  Expanded="Expander_Expanded" Panel.ZIndex="99" Collapsed="Expander_Collapsed" Name="expander">

                <Popup PopupAnimation="Slide" Name="popup" Width="200" Height="200" StaysOpen="True" AllowsTransparency="True" 
                       IsOpen="False" >
                <Grid Background="Cornsilk">
                    <Grid.BitmapEffect>
                        <DropShadowBitmapEffect/>
                    </Grid.BitmapEffect>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                   <TextBlock TextWrapping="Wrap" FontWeight="Bold">
                      Some example text
                   </TextBlock>
                </Grid>
            </Popup>

        </Expander>
    </Canvas>
</Grid>

一些示例文本

不幸的是,没有快速的解决方案。您可以使用我在这里介绍的技巧:

下面是一个使用以下方法的解决方案:

此仅标记示例由文本框和弹出窗口组成。当文本框聚焦时,弹出窗口打开。通过钩住窗口的位置更改事件并强制弹出窗口相应地重新定位,弹出窗口将跟随窗口移动

<Grid>
    <StackPanel>
        <TextBox x:Name="textBox1" Width="200" Height="20"/>
        <Popup PlacementTarget="{Binding ElementName=textBox1}" IsOpen="{Binding IsKeyboardFocused, ElementName=textBox1, Mode=OneWay}">
            <TextBlock Background="White" Text="Sample Popup content."/>
            <p:Attached.Operations>
                <p:EventHandler Path="Loaded">
                    <p:ScriptHandler Path="@FindAncestor([Window], @AssociatedObject.PlacementTarget).LocationChanged">
                        @AssociatedObject.HorizontalOffset += 1;
                        @AssociatedObject.HorizontalOffset -= 1;
                    </p:ScriptHandler>
                </p:EventHandler>
            </p:Attached.Operations>
        </Popup>
    </StackPanel>
</Grid>

@AssociatedObject.HorizontalOffset+=1;
@AssociatedObject.HorizontalOffset-=1;

这几乎是Rick的答案,但在代码背后,因为我认为绝对没有理由引入另一种依赖关系

protected override void OnLocationChanged(EventArgs e)
{
    popup.HorizontalOffset += 1;
    popup.HorizontalOffset -= 1;
    base.OnLocationChanged(e);
}
只需复制并粘贴到窗口的代码,然后用弹出实例的标识符替换弹出窗口的标识符


我发现它更好,更简洁,它不使用您必须取消订阅或内存泄漏的事件。

对于您的应用程序的运行时,重写将具有更好的性能(除了微性能非理性主义者,比如您的Really,仍然会喜欢它之外,没有什么值得注意的)。

谢谢。你可能会认为MS会作为类的一部分提供这种类型的功能。我尝试了这段代码和标记Porgraming它工作得很好,但我想知道的唯一一件事是,如果窗口拖到任务栏下面,弹出窗口会重新定位到屏幕的中心,再也不会回来。有没有办法处理这种情况?