我试图让几个类继承一个更通用的 Silverlight 用户控件,以避免我的代码中出现冗余。这些类继承了扩展控件,后者又继承了用户控件类。我遇到的问题是每次编译时都会重新生成 ExtendedControlExtension.g.cs 文件,继承不正确(它继承了用户控件而不是我的扩展控件)。
请注意,我一直在继承 .cs 和 g.cs 文件中的扩展控件,但继续使用 .aspx 文件中的用户控件标记,因为这会导致错误
错误 29 XML 命名空间“http://schemas.microsoft.com/winfx/2006/xaml/presentation”中不存在标记“ExtendedControl”。
有办法解决这个问题吗?
谢谢!
最佳答案
您不能更改 .g.cs
文件,事实上文件中是这么说的。此外,不幸的是使用术语“自定义控件”,因为这意味着特定的东西而不是你正在尝试做的事情。但是,好消息是您尝试做的事情是可行的。
从 UserControl
派生:
public class FancyUserControl : UserControl
{
// Your added common functionality.
}
然后使用正常机制向您的项目添加一个新的 UserControl
,假设是 UserControl1
。然后按如下方式编辑 UserControl.xaml
文件:
<local:FancyUserControl x:Class="SilverlightApplication1.UserControl1"
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:SilverlightApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</local:FancyUserControl>
特别注意其中包含 local
的三行,以适应您的应用程序。然后编辑UserControl1.xaml.cs
文件如下:
public partial class UserControl1 : FancyUserControl
{
public UserControl1()
{
InitializeComponent();
}
}
虽然 Visual Studio 还不太高兴,但最终重建您的项目,一切都会好起来的。
UserControl1
类现在派生自 FancyUserControl
而不是 UserControl
,您可以开始添加常用功能。要添加更多控件,您需要在最初将每个新控件添加到项目后手动编辑 XAML 和代码隐藏一次。
关于c# - Silverlight 用户控件部分类的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5996300/