简体   繁体   中英

How to access Main Form Public Property WPF

I have a user control from where I have to call the property of the window which contain the user control how can I access that property. Suppose I have Title Property in my window and I want to access Title property of the window from the user control. Any idea

is That OK

(App.Current.MainWindow as MainWindow).Title;

Thanks in advance

Why dont you bind title property of parent window with your control's property?


Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window Title" Height="500" Width="650" ResizeMode="NoResize" x:Name="us1">   
      TextBox Name="txtBlk" Text="{Binding Path=Title, ElementName=us1}"/>          
/Window>

This code will get the parent window where the user control resides:

FrameworkElement parent = (FrameworkElement)this.Parent;
        while (true)
        {
            if (parent == null)
                break;
            if (parent is Page)
            {
                //Do your stuff here. MessageBox is for demo only
                MessageBox.Show(((Window)parent).Title);
                break;
            }
            parent = (FrameworkElement)parent.Parent;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM