简体   繁体   English

如何从另一个in-behind xaml代码中访问变量in-behind xaml代码

[英]how to access variables in-behind xaml code from another in-behind xaml code

i'm trying to make like a messenger program WPF my solution contains app.xaml & app.xaml.cs , mainwindow.xaml & mainwindow.xaml.cs and another two xaml pages first for connecting , second for messenger core { contacts , status , .. etc } i hava a library of agsxmpp that helps me to connect where is the best .cs file to define and initialize connection and how to access it (( and its event handlers )) from another .cs file 我正在努力制作一个信使程序WPF我的解决方案包含app.xaml&app.xaml.cs,mainwindow.xaml和mainwindow.xaml.cs以及另外两个用于连接的xaml页面,第二个用于messenger core {contacts,status ,...等我有一个agsxmpp库,帮助我连接哪里是最好的.cs文件来定义和初始化连接以及如何从另一个.cs文件访问它((及其事件处理程序))

btw this problem always face me :( 顺便说一下这个问题总是面对我:(

A default WPF template will look like this with a StartupUri property. 使用StartupUri属性,默认WPF模板将如下所示。

<Application x:Class="WpfApplication1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>

You need to remove StartupUri and use the Startup event instead so that you can create your main window manually. 您需要删除StartupUri并使用Startup事件,以便您可以手动创建主窗口。

<Application x:Class="WpfApplication1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Startup="Application_Startup">
    <Application.Resources>

    </Application.Resources>
</Application>


namespace WpfApplication1
{

    public partial class App : Application
    {
        private XmppClientConnection _client = new XmppClientConnection ( );

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var mainWindow = new Window1();
            mainWindow.Show();
        }
    }
}

Then you can add a new constructor to the Window1 class so you can pass it the object you need to reference. 然后,您可以向Window1类添加一个新的构造函数,以便您可以将它传递给您需要引用的对象。

public partial class Window1 : Window
{
    private XmppClientConnection _client;

    public Window1()
    {
        InitializeComponent();
    }

    public Window1(XmppClientConnection client):this()
    {
        _client = client;
    }
}

Like so: 像这样:

private void Application_Startup(object sender, StartupEventArgs e)
{
    _client = new XmppClientConnection();
    var mainWindow = new Window1(client);
    mainWindow.Show();
}

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

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