开发者

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 ag开发者_运维知识库sxmpp 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

btw this problem always face me :(


A default WPF template will look like this with a StartupUri property.

<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.

<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.

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜