简体   繁体   English

wpf中另一种形式的控制形式

[英]control form from another form in wpf

如何从另一个表单示例控制主表单我想从wpf中的另一个表单访问主表单中的表?

You can either use UI automation (which would only let you interact with it as if you were a user clicking on/typing in the controls): http://msdn.microsoft.com/en-us/library/dd561932(VS.85).aspx 您可以使用UI自动化(只能让您与其进行交互,就好像您是在控件中单击/键入用户一样): http : //msdn.microsoft.com/zh-cn/library/dd561932(VS。 85).aspx

Or you can use code behind to pass a reference from one window to the other, probably in your Application class. 或者,您可以使用后面的代码将引用从一个窗口传递到另一个窗口,这可能在您的Application类中。

There is nothing specific to WPF that makes either option any easier or harder to implement. WPF并没有使WFP变得更容易或更难实现的选项。

salamonti, Do you want to access a control on the main form or the data that the control is displaying? salamonti,您要访问主窗体上的控件还是该控件显示的数据? If the latter I would suggest you to keep the data in a separate area than the control presenting it. 如果是后者,我建议您将数据保存在与显示数据的控件不同的区域中。 This can be achieved with MVVM and several other view separation patterns. 这可以通过MVVM和其他几种视图分离模式来实现。 You can also use Routed Events and Routed Commands to execute code in one "form" from a different one. 您还可以使用路由事件和路由命令以另一种形式的“形式”执行代码。

If you want to access the "main form" from a child form, you can create a property on the child form of type FrameworkElement for example. 如果要从子窗体访问“主窗体”,则可以在例如FrameworkElement类型的子窗体上创建属性。 Then, when you create the child form, just populate this property with the instance of the main form. 然后,在创建子窗体时,只需使用主窗体的实例填充此属性。 This way you'll have access to whatever you want in the main form. 这样,您将可以访问主表单中的任何内容。

this is a tiny sample of communication between windows in WPF 这是WPF中Windows之间通信的一个很小的示例

you can refer to controls as the way you do with class fields, cause that's what they are 您可以将控件称为对类字段的处理方式,因为这就是它们的本质

public class Form1 : Window
{
    public DateTime FormCreationDate {get; set;}

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Form2 a = new Form2();
        a.Owner = this;
        a.Show();
    }
}


public class Form2 : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.label1.Content = string.Format(
            "the owner of this window was created on {0}", 
            ((Form1)this.Owner).FormCreationDate.ToString());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM