C # WPF - Access element of another XAML by code

0

Hello, I have two screens a Window and a Page loaded inside the screen

Class Window1{
   //to do ..
 __mainFrame; // acessa normal
}

Class page1{
 //to do
__mainFrame; // sem  acesso ao frame
}

Inside the window class I have a <Frame x:Name="__mainFrame"></frame> where I load the pages and wanted when I clicked a button that is inside page1 to be loaded into that iframe as the two are in different classes I can not load, would I have some way to do this access?

Obs, using the extend of one class inside the other does not work As in the example below

Class window1 : page1{

}
    
asked by anonymous 22.01.2018 / 19:45

2 answers

0

Well I've got the right way to do it here

Class page1{

((Window1)System.Windows.Application.Current.MainWindow).__mainFrame;

}

Where Window is the class name of my Window1 that references the xmal I want to access and MainWindow is the x: Name window element

This way you can access any element external to your class

    
22.01.2018 / 20:08
1

The way you did solves the problem, but in an environment with multiple classes and multiple levels of objects you will have reference problems. Outside the coupling between classes that will only grow, if you need to change the name __ mainFrame at some point, you will have to exit changing into multiple files. Anyway, the maintenance will be extremely complex.

A better solution (there are others, for sure) is to create an Action property on your page1, assign a role to it on your Windows1, and then run on page1 when you need it.

Example:

Class Window1{

    construtor(){
        // crie uma instancia de page1 ou acesse uma já existente, como exemplo, vou criar
        var page1 = new page1();
        page1.FazerAlgumaCoisa = () => {
            __mainFrame; // aqui você tem acesso ao objeto __mainFrame para fazer o que quiser      
        }
    }  
    __mainFrame; // acessa normal
}

Class page1{
    public Action FazerAlgumaCoisa { get; set;}

    public void ExecutarAcaoNoMainFrame(){

        this.FazerAlgumaCoisa?.Invoke();

    }
}

You can also pass parameters if necessary, just change your Action property, as in the example below where I pass a string.

Class Window1{

    construtor(){
        // crie uma instancia de page1 ou acesse uma já existente, como exemplo, vou criar
        var page1 = new page1();
        page1.FazerAlgumaCoisa = (parametro1) => {
            __mainFrame; // aqui você tem acesso ao objeto __mainFrame para fazer o que quiser      
//parametro1 pode ser usada aqui
        }
    }  
    __mainFrame; // acessa normal
}

Class page1{
    public Action<string> FazerAlgumaCoisa {get;set;}

    public void ExecutarAcaoNoMainFrame(){

        this.FazerAlgumaCoisa?.Invoke("qualquer valor");

    }
}
    
23.03.2018 / 22:12