开发者

Access properties controls of a window from a page in WPF

My problem is that I want to access from a page to the properties of a control (button, textblock, label, or a menuitem of the window....) placed in a window. The page is placed into the window. How can I do this? Is there any method 开发者_Go百科to find controls by name in a specific window or page or entire application?


A Window object has a method FindName() (inherited from FrameworkElement). MSDN: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.findname.aspx

If I understand correctly, you'll then need to use reflection to enumerate the control's properties.

Update:

In the XAML you'll have something like this:

ListBox o = this.FindName("myListBox") as ListBox;

In the code behind for the window you could use:

<Window>
    <Grid>
        <ListBox x:Name="myListBox" />
    </Grid>
</Window>

There's no "new" involved in the process.


I have obtained the window reference using Reflection:

    public static Window WindowByName(string strWindowName)
    {
        if (string.IsNullOrEmpty(strWindowName)) return null;

        Assembly asm = Assembly.GetExecutingAssembly();
        string strFullyQualifiedName = asm.GetName().Name + "." + strWindowName;
        object obj = asm.CreateInstance(strFullyQualifiedName);

        if (obj != null)
            return obj as Window;
        else
            return null;
    }

with the above method I retrieve the reference of WinMain.xaml and then I address its controls by using FindName method from PageRutas.xaml code behind like this:

        // Retrieve reference WinMain.xaml reference
        Window win = cWindow.WindowByName("WinMain");

        // Retrieve listbox reference
        System.Windows.Controls.ListBox lstbox = 
             (System.Windows.Controls.ListBox)win.FindName("LayoutListBox");

        // Modifying IsEnabled property
        lstbox.IsEnabled = false;

but now... I have another problem.... property changed to false after executing lstbox.IsEnable = false; line but something strange is happening because WinMain.xaml UI seems to ignore the change I have made (the listbox doesn't disabled in the UI). What's happening? anybody can help me?

Thanks.


var mainWindow = Application.Current.MainWindow as MainWindow; 

//Where MainWindow is Window type

use mainWindow.controlName to access the control

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜