您的位置:首页 > 运维架构

“父窗口拖动的时候Popup不随着父窗口移动”问题的解决方案

2013-07-02 22:15 344 查看
我们用WPF用的Popup时候会发现,当 StaysOpen=True 的时候,因为Popup不会消失,在父窗口移走的时候Popup仍旧在原地。。。作者在国外网站上无意间发现了这个解决方案,拿出来给大家分享:

方法是为Popup定义一个附加属性。代码如下。

public class PopopHelper
{
public static DependencyObject GetPopupPlacementTarget(DependencyObject obj)
{
return (DependencyObject)obj.GetValue(PopupPlacementTargetProperty);
}

public static void SetPopupPlacementTarget(DependencyObject obj, DependencyObject value)
{
obj.SetValue(PopupPlacementTargetProperty, value);
}

// Using a DependencyProperty as the backing store for PopupPlacementTarget.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty PopupPlacementTargetProperty =
DependencyProperty.RegisterAttached("PopupPlacementTarget", typeof(DependencyObject), typeof(PopopHelper), new PropertyMetadata(null,OnPopupPlacementTargetChanged));

private static void OnPopupPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null)
{
DependencyObject popupPopupPlacementTarget = e.NewValue as DependencyObject;
Popup pop = d as Popup;

Window w = Window.GetWindow(popupPopupPlacementTarget);
if (null != w)
{
w.LocationChanged += delegate
{
var offset = pop.HorizontalOffset;
pop.HorizontalOffset = offset + 1;
pop.HorizontalOffset = offset;
};
}
}
}

}


之后只需要在Popup控件上这样写即可:

<Grid>
<TextBox x:Name="placementTextBox"/>
<Popup PopopHelper.PopupPlacementTarget="{Binding ElementName=placementTextBox}" />
</Grid>


本文的示例工程可以从附件下载。

欢迎各种转载,转载请注明来自 Leaco 的博客:/article/5301301.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: