C# 从另一个WPF窗口继承列表
我有一个程序,它已经构建了一个主窗口,我正在添加一个名为“Profiler”的窗口。在主窗口中有一个我需要能够使用的列表,因此我需要使用主窗口作为基础 我做的第一件事是在主窗口类中,我列出了需要保护的列表,并创建了和get方法:C# 从另一个WPF窗口继承列表,c#,wpf,C#,Wpf,我有一个程序,它已经构建了一个主窗口,我正在添加一个名为“Profiler”的窗口。在主窗口中有一个我需要能够使用的列表,因此我需要使用主窗口作为基础 我做的第一件事是在主窗口类中,我列出了需要保护的列表,并创建了和get方法: protected List<PaperRoll> paperRolls = new List<PaperRoll>(); public List<PaperRoll> PaperRolls {
protected List<PaperRoll> paperRolls = new List<PaperRoll>();
public List<PaperRoll> PaperRolls
{
get { return paperRolls; }
}
受保护列表纸卷=新列表();
公开名单纸卷
{
获取{返回纸卷;}
}
然后在profiler窗口中,我尝试使用主窗口(称为DspWindow)作为基类:
public partial class Profiler : DspWindow
{
public Profiler() : base ()
{
InitializeComponent();
List<PaperRoll> pr = base.PaperRolls;
}
}
<base:DspWindow x:Class="DSP_Simulator.Profiler"
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:DSP_Simulator"
mc:Ignorable="d"
Title="Profiler" Height="300" Width="300">
<Grid>
</Grid>
</base:DspWindow>
公共部分类探查器:DspWindow
{
公共探查器():基()
{
初始化组件();
列表pr=基本纸卷;
}
}
这导致错误“探查器”的部分声明不能指定不同的基类。我试图研究这个错误,但似乎这是因为xaml没有从基类继承。因此,我改为xaml以包含基类:
public partial class Profiler : DspWindow
{
public Profiler() : base ()
{
InitializeComponent();
List<PaperRoll> pr = base.PaperRolls;
}
}
<base:DspWindow x:Class="DSP_Simulator.Profiler"
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:DSP_Simulator"
mc:Ignorable="d"
Title="Profiler" Height="300" Width="300">
<Grid>
</Grid>
</base:DspWindow>
这导致了多个错误,例如未找到'base:DspWindow,前缀'base'未定义,'base'是未声明的前缀。
有人能告诉我我要去哪里吗?你似乎不明白继承是如何运作的 仅仅因为您想在对象中使用类的成员,并不意味着您必须从它继承 我认为您不希望使用定义,而是希望使用列表的值,因此我建议您不要继承
DspWindow
,而应该在探查器中引用它
我不知道您的windows是如何协同工作的,但我猜DspWindow
会创建一个新的探查器
,因此我建议您可以创建一个新的探查器
对象,该对象的构造函数接收DspWindow
作为参数,然后在内部使用其实例
public partial class Profiler : Window
{
private DspWindow dspWindow;
public Profiler(DspWindow dspWindow)
{
InitializeComponent();
this.dspWindow = dspWindow;
}
void DoSomething()
{
int numberOfPaperRolls = dspWindow.PaperRolls.Count; //you can access the list in this object aswell!
}
}
在DspWindow
中:
var prof = new Profiler(this);
prof.Show();
您不需要将其用作基类,只需获取主窗口实例var main=(MainWindow)Application.Current.MainWindow;