【问题标题】:WPF user control inheritance issuesWPF 用户控件继承问题
【发布时间】:2016-04-04 13:53:38
【问题描述】:

我在一个库项目中制作了一个 WPF 控件,并想用一个新的控件来扩展它。

<UserControl x:Class="Genesyslab.Desktop.Modules.ExtensionUtils85.GUI.EmbeddingUserControl"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>

    </Grid>
</UserControl>

我试图像这样扩展它:

<src:EmbeddingUserControl x:Class="Interaxalab.Desktop.Modules.PrototipoCable.CustomViews.InteractionView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="Genesyslab.Desktop.Modules.ExtensionUtils85.GUI"
    Name="InteractionWorksheetView" Height="321.613" Width="471.396"
>
    <Grid>

        <WindowsFormsHost x:Name="windowsFormsHost1" HorizontalAlignment="Left" Height="284" VerticalAlignment="Top" Width="471"/>

    </Grid>
</src:EmbeddingUserControl>

但是,我收到一条错误消息,指出名称空间“Genesyslab.Desktop.Modules.ExtensionUtils85.GUI”中不存在名称“EmbeddingUserControl”。

该名称确实存在,因为 xaml.cs 可以找到它,但由于某种原因 xaml 不能。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    长话短说 - 您不能通过另一个使用 xaml 的控件来继承使用 xaml 的控件(即使这样做也有意义吗?)。在您的情况下, EmbeddingUserControl 不包含任何可视树元素(只是空网格),因此您可以这样做:

    public class EmbeddingUserControl : UserControl {
        // some methods, properties of your control
    }
    

    然后您可以像在您的问题中所做的那样继承(不要忘记在 xaml 文件和代码隐藏文件中从 EmbeddingUserControl both 继承)。

    如果您继承的控件本身没有 xaml,您也可以使用 xaml 从用户控件继承(因此您可以添加\覆盖逻辑)。

    如果您需要继承一些视觉结构 - 您必须从继承切换到组合。也就是说:您的基本控件提供了一些可以放置其他控件的占位符,或者甚至更好地允许提供模板来格式化数据项(例如 ItemsControl 和 ItemTemplate 属性)。然后,您只需在必要时用其他控件填充这些占位符。

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2014-06-09
      • 2013-09-03
      相关资源
      最近更新 更多