【发布时间】:2018-01-31 21:01:47
【问题描述】:
我试图创建一个 wpf 用户控件列表,然后在运行时将主窗口内容设置为用户控件。
由于所有 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();
}
}
允许 Visual Studio 设计器识别可设计组件的登录 xaml
<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 派生到 BaseControl 列表的类?
【问题讨论】:
-
“失败”的错误消息/异常是什么?
-
不要这样做。从这里开始阅读:Data Templating Overview
-
@Clemens 我认为你错过了他的要求......他想要制作具有重大差异的完整窗口,而不仅仅是具有相似/相同模板的不同数据。
-
Oppassum,没错。每个 Window\user 控件都将使用 \display 完全不同的数据,尽管某些 Window\User 控件将依赖于另一个 Window\Control 检索的数据
-
还是没告诉我“失败”是什么意思。
标签: c# wpf windows user-controls