Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何访问主窗体公共属性WPF_C#_Wpf - Fatal编程技术网

C# 如何访问主窗体公共属性WPF

C# 如何访问主窗体公共属性WPF,c#,wpf,C#,Wpf,我有一个用户控件,我必须从中调用包含用户控件的窗口的属性,我如何访问该属性。 假设我的窗口中有Title属性,我想从用户控件访问窗口的Title属性。有什么想法吗 可以吗 (App.Current.MainWindow作为主窗口)。标题 提前感谢为什么不将父窗口的title属性与控件的属性绑定 Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xm

我有一个用户控件,我必须从中调用包含用户控件的窗口的属性,我如何访问该属性。 假设我的窗口中有Title属性,我想从用户控件访问窗口的Title属性。有什么想法吗

可以吗

(App.Current.MainWindow作为主窗口)。标题


提前感谢

为什么不将父窗口的title属性与控件的属性绑定


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>

此代码将获取用户控件所在的父窗口:

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

这只是一个例子,否则我想调用以主窗体编写的函数。请参阅本文-我正在使用窗口应用程序。@Asim Saijad-我修改了我的答案。替换了从一页到另一页的转换。我在代码中提到的代码行也可以工作,如果与您的解决方案和我在问题中提到的语句相比,哪一个是最好的?@Asim Saijad-对于您的特殊需要,我认为您的代码要好得多,因为我的代码在执行过程中可能会消耗更多内存,并可能会对性能产生一些影响。无论如何,如果要获取对象的父对象(第n级),可以使用我的代码:)