我们用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 + ;
pop.HorizontalOffset = offset;
};
}
}
} }
之后只需要在Popup控件上这样写即可:
<Grid>
<TextBox x:Name="placementTextBox"/>
<Popup PopopHelper.PopupPlacementTarget="{Binding ElementName=placementTextBox}" />
</Grid>
本文的示例工程可以从附件下载。
欢迎各种转载,转载请注明来自 Leaco 的博客:http://www.cnblogs.com/Leaco/p/3168540.html