如何在wpf中获得父控件? [英] How to get parent control in wpf?
问题描述
使用MessageBox显示出现在调用者中心的对话框,显然,要做到这一点,MessageBox必须得到父控件,以便计算中心位置。
我在页面中遇到类似的问题,单击按钮会显示一个弹出窗口,并将页面的属性IsEnable设置为false,因此,代码必须得到父控件---页面,但我不知道不能做所以。
例如:
Use MessageBox to display a dialog box that appears in the caller's central, obviously, to do this, MessageBox must get the parent control, so as to calculate the center position.
I have a similar problem in a page where clicking the button displays a popup, and set the page's property IsEnable to false, therefore, code must get the parent control --- page, but I do not know can not do so.
example:
namespace WpfBrowserApplication1
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MessagePopup.Show(this,"hello");
}
}
}
namespace WpfBrowserApplication1
{
public sealed class MessagePopup
{
public static void Show(UIElement parent, string message)
{
Popup window = new Popup();
StackPanel sp = new StackPanel { Margin = new Thickness(5) };
sp.Children.Add(new TextBlock { Text = message });
Button newButton = new Button { Content = "button" };
newButton.Click += delegate { window.IsOpen = false; parent.IsEnabled = true; };
sp.Children.Add(newButton);
sp.Children.Add(new Slider { Minimum = 0, Maximum = 50, Value = 25, Width = 100 });
window.Child = new Border
{
Background = Brushes.White,
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(2),
Child = sp
};
window.PlacementTarget = parent;
window.Placement = PlacementMode.Center;
window.IsOpen = true;
parent.IsEnabled = false;
}
}
}
我希望父母是通过代码获得的,而不是通过参数,如下所示:
I hope that the parent is get by code , not by parameters,like this:
public static void Show(string mess)
{
UIElement parent = //get the parent control --- page
...
parent.IsEnable = false;
}
谢谢。
Thanks.
推荐答案
UIElement parent = this.Parent;
请尝试以下方法。
Try the following.
UIElement parent = App.Current.MainWindow;
谢谢,
Vineeth
Thanks,
Vineeth
on childwindow(Usercontrol)加载事件
on childwindow(Usercontrol) load event
private void onload(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow((DependencyObject)sender);
if (parentWindow != null)
{
parentWindow.Close();
}
}
这篇关于如何在wpf中获得父控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!