Aizen
Aizen

Reputation: 1825

WPF getting object inside Windows

Problem. I don't know how to access the objects inside the passed Window Object from my method.

void MyMethod(Window myWindow){
     myWindow. <--- "I have an Progress bar inside this object that I believe has been passed. But don't know how to access it".




}

I can also try to use the current Application class library from System.Windows but the problem is still the same, I just don't know how to reference the objects that is inside the window.

void MyMethod(){
     ProgressBar myprogressbarInsidetheApp = Application.Current.MainWindow <----- I am lost. Please help.

}

Upvotes: 0

Views: 1123

Answers (2)

Mark Feldman
Mark Feldman

Reputation: 16148

You really shouldn't be doing this but if you absolutely insist...use the WPF Tree Visualizer to determine the name of the child element you are trying to access and then use window.FindName("the_elements_name"); to get a reference object. If the element doesn't have a name then you'll need to navigate the entire visual tree looking for an element of the required type.

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66501

I'd avoid passing a reference to the Window, but if you have some constraint that's forcing you too, then you'll need to cast it to your specific Window before you can access any elements on it.

If this was your window, named "MainWindow":

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ProgressBar Name="MyProgressBar" Value="30" />
    </Grid>
</Window>

You'd have to cast it like this:

void MyMethod(Window myWindow)
{
    var pb = ((MainWindow)myWindow).MyProgressBar;

    // do something with "pb"
}

Upvotes: 1

Related Questions