【问题标题】:Adding derived UserControls to List<> in Wpf将派生的用户控件添加到 Wpf 中的 List<>
【发布时间】: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


【解决方案1】:

奇怪的是,虽然我不确定根本问题是什么,但我已经解决了这个问题

为了清楚我写的问题

 Login BaseControlDerivedWindow  = new Login();

但实际代码是

Login login = new Login(); 

这导致编译器发出类似“ 无法从 Program.Controls.Login 转换为 Program.Controls.BaseControl"

为了清楚起见,我更改了代码后,它编译了,然后让我将 Login 实例重命名为 login 并再次编译没有问题。

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    相关资源
    最近更新 更多