如何在 WPF 窗口中访问继承的成员?

我试图在 WPF 应用程序中为我的窗口创建一个基类,但我无法在派生类中访问它们的成员。例如,这是基本窗口:


namespace MyApp.Windows

{

    public class BaseWindow : Window

    {

        public int MyProp { get; set; }

    }

}

这是一个窗口:


public partial class SomeWindow : BaseWindow

{

    public SomeWindow()

    {

        InitializeComponent();

        Loaded += SomeWindow_Loaded;

    }


    private void SomeWindow_Loaded(object sender, RoutedEventArgs e)

    {

        MyProp = do something;

    }

}

如果我像这样保留它,该MyProp属性工作得很好,但我收到一个InitializeComponent()无法识别的错误。因此,在窗口 xaml 中我更改x:Class如下:之前


<Window x:Class="MyApp.SomeWindow"


<Window x:Class="MyApp.Windows.BaseWindow"

现在,InitializeComponent()不再给我带来任何问题,但MyProp突然不被识别。为什么?


如果有帮助的话,我想要的是让所有窗口在加载后引发一个事件(事件被触发Loaded),并且我不想为我拥有的每个窗口编写这段代码,所以我想我可以在基类中编写这段代码,从中派生我的窗口,然后一切正常。


编辑:这是所有代码。BaseWindow.cs(没有其他 xaml):


using System.Windows;


namespace MyApp.Windows

{

    public class BaseWindow : Window

    {

        public int MyProp { get; set; }

    }

}

MainWindow.xaml.cs


namespace MyApp.Windows

{

    public partial class MainWindow : BaseWindow

    {

        public MainWindow()

        {

            InitializeComponent();

        }

    }

}

主窗口.xaml:


<myapp:BaseWindow x:Class="MyApp.Windows.BaseWindow"

        xmlns:myapp="clr-namespace:MyApp.Windows"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:local="clr-namespace:MyApp"

        mc:Ignorable="d"

        Title="MainWindow" Height="450" Width="800">

    <Grid>


    </Grid>

</myapp:BaseWindow>


MMTTMM
浏览 124回答 1
1回答

开心每一天1111

为了将 SomeWindow 的基类从 更改为Window,BaseWindow您需要替换它出现的任何位置Window。BaseWindow所以public partial class SomeWindow : Window变成public partial class SomeWindow : BaseWindow和<Window x:Class="MyApp.Windows.SomeWindow" ...>变成<myapp:BaseWindow x:Class="MyApp.Windows.SomeWindow"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xmlns:myapp="clr-namespace:MyApp.Windows" ...>带有不可避免的 XAML 命名空间前缀。这是上面示例中使用的 BaseWindow 类:namespace MyApp.Windows{&nbsp; &nbsp; public class BaseWindow : Window&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public int MyProp { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public BaseWindow()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Loaded += BaseWindow_Loaded;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; private void BaseWindow_Loaded(object sender, RoutedEventArgs e)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP