我试图创建一个wpf用户控件列表,然后在运行时将mainwindows内容设置为usercontrol。
由于所有UserControls也将共享接口,我想从派生的窗口类构建它们:
public class BaseControl : UserControl, IControlState
public string ControlName
{
get
{
return this.GetType().Name;
}
}
public void UseState(object parameters)
{
throw new NotImplementedException();
}
}
从UserControl派生的类
public partial class Buglist : UserControl
{
public Buglist()
{
InitializeComponent();
}
}
从我的BaseControl派生的类
public partial class Login : BaseControl
{
public Login()
{
InitializeComponent();
}
}
登录xaml以允许Visual Studio设计器识别可设计的组件
<MyType:BaseControl x:Class="BugAnalyzer.Controls.Login"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BugAnalyzer.Controls"
xmlns:MyType="clr-namespace:BugAnalyzer.Controls"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="112,72,0,0" TextWrapping="Wrap" Text="login" VerticalAlignment="Top"/>
</Grid>
在我的主窗口中,我希望能够将这些控件添加到列表中,然后能够访问共享属性,例如ControlName。
public partial class MainWindow : Window
{
List<UserControl> uclist = new List<UserControl>();
List<BaseControl> bcList = new List<BaseControl>();
public MainWindow()
{
InitializeComponent();
Buglist UserControlDerivedWindow = new Buglist();
Login BaseControlDerivedWindow = new Login();
uclist.Add(UserControlDerivedWindow); //Works
bcList.Add(BaseControlDerivedWindow); //Fails
}
为什么我可以将从UserControl派生的类添加到列表UserControls 但不是从BaseControl派生到BaseControls列表的类吗?
答案 0 :(得分:0)
奇怪的是,虽然我不确定根本问题是什么,但我已经解决了这个问题
为了清楚我写的问题
Login BaseControlDerivedWindow = new Login();
但实际代码是
Login login = new Login();
导致编译器发出类似“ 无法从Program.Controls.Login转换为Program.Controls.BaseControl“
在我更改代码后为了清晰编译然后让我将Login实例重命名为login并再次编译没有问题。