mkvist
mkvist

Reputation: 11

C# find all WPF Windows

I have a C# / WPF project in Visual studio 2013. The project contains one main window and several pop-up window. Most of those pop-up windows contains control elements, including buttons.

I need to find all buttons on all windows, or actually i need to find what the "IsEnabled" property is bound to for all buttons. So in the code below, i would like to find/extract "IsChangePwdEnabled" of all buttons.

The code below is just an example of one window and one button, i have 30-40 windows in my solution and all with several buttons on.

Is there a solution to extract this data? I have tried with the LogicalTreeHelper.GetChildren(), in the initialization of the program, but with that function I need the parrent of the object which has to be searched, and i do not have that, because the window object is only created when needed.

Example of pop-up window (Logon):

<window x:Class="ManagedHMI.CLogonDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ManagedHMI" 
WindowStyle="ToolWindow"
Topmost="True"
Title="Logon" SizeToContent="WidthAndHeight"
>
<Grid Margin="5,5,5,5" >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
...
<Button x:Name="ChangePwd" Width="90" Click="ChangePwd_Click" IsEnabled="{Binding Path=IsChangePwdEnabled, UpdateSourceTrigger=PropertyChanged}">

Code that creates the Logon window:

m_LogonDlg = new CLogonDialog(Logon, UnlockPc, ChangePassword, userDomain, m_language);

In my program, the "IsEnabled" property is used to check which buttons a user has access rights to use, and i want to use this functionality to make an export of userrights for all buttons.

Upvotes: 1

Views: 1192

Answers (1)

mm8
mm8

Reputation: 169400

You could use the Application.Current.Windows property to get references to the windows and then use the FindVisualChildren method from the below question to find all controls of a specific type in a specific window. Something like this:

var windows = Application.Current.Windows;
foreach(var window in windows)
{
    var buttons = FindVisualChildren<Buttons>(window);
    if(buttons != null)
    {
        foreach(var button in buttons)
        {
            bool isEnabled = buttons.IsEnabled;
            //...
        }
    }
}

Find all controls in WPF Window by type

Upvotes: 1

Related Questions