我试图允许几个类继承更通用的Silverlight用户控件,以避免代码中的冗余.这些类继承扩展控件,然后继承User Control类.我遇到的问题是ExtendedControlExtension.g.cs文件每次编译时都会重新生成,并且继承不正确(它继承了User Control而不是我的扩展控件).
请注意,我一直在继承.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>
根据您的应用,特别注意本地的三条线.然后编辑UserControl1.xaml.cs文件,如下所示:
- public partial class UserControl1 : FancyUserControl
- {
- public UserControl1()
- {
- InitializeComponent();
- }
- }
和Visual Studio不会很开心,但最终重建你的项目,一切都会很好.
UserControl1类现在派生自FancyUserControl而不是UserControl,您可以开始添加常用功能.要添加更多控件,您需要在最初将每个新控件添加到项目后手动编辑XAML和代码隐藏.