How to access the main public property WPF form

I have a user control, from where I have to call a window property that contains the user control, how can I access this property. Suppose I have a Title property in my window, and I want to access the Title type of a window from a user control. Any idea

- its OK

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

Thanks in advance

+3
source share
2 answers

This code will receive the parent window in which the user control is located:

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;
        }
0
source

Why don't you bind the title property of the parent window to your control 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>

0

Source: https://habr.com/ru/post/1739086/


All Articles