tags:

views:

132

answers:

2

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

A: 

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>

Rakesh Gunijan
That is just an example, otherwise I want to call function written in the main form.
Asim Sajjad
Refer this post - http://stackoverflow.com/questions/2513669/complex-user-interface-mvc-pattern/2513884#2513884
Rakesh Gunijan
+2  A: 

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;
        }
Jojo Sardez
I am using window applcation.
Asim Sajjad
@Asim Saijad - I modified my answer. Replaced casting from Page to Window.
Jojo Sardez
The line of code which I have mentioned in my code also work, which one is best if compared with you solution and the statement I have mentioned in my question?
Asim Sajjad
@Asim Saijad - For your particular need I think your code is much better since mine could consume more memory during execution and could affect the performance a bit. Anyway you could use my code if you intended to get the parent (to the nth level) of an object :)
Jojo Sardez