概述
有个场景, 自定义了一个控件BaseControl, 它从UserControl继承的。由于业务需求, 公开了一个protected virtual void Process() 函数。 在不同的场景下可以继承BaseControl并重新Process()方法,从而实现不同的逻辑。
BaseControl的cs如下:
public partial class BaseControl : UserControl
{
public BaseControl()
{
InitializeComponent();
}
protected virtual void ProcessFrame( Bitmap bitmap)
{
}
}
BaseControl的xaml如下:
<UserControl x :Class="Muzizongheng.BaseControl"
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>
继承BaseControl的子类ChileControl的代码如下:
public partial class ChildControl : CameraControl. MainWindow
{
protected override void Process()
{
//
}
}
当在Windows中使用ChildControl时, 会在BaseControl的InitializeComponent()方法中抛出异常, “The component does not have a resource identified by the uri”
解决方法是:
替换BaseControl的构造方法里的InitializeComponent。
public partial class BaseControl : UserControl
{
public BaseControl()
{
//InitializeComponent();
this.LoadViewFromUri("/Muzizongheng;component/MainWindow.xaml" );
}
protected virtual void ProcessFrame( Bitmap bitmap)
{
}
}
public static class UserControlExtension
{
public static void LoadViewFromUri( this UserControl userControl, string baseUri)
{
try
{
var resourceLocater = new Uri(baseUri, UriKind.Relative);
var exprCa =
( PackagePart)
typeof (Application ).GetMethod("GetResourceOrContentPart",
BindingFlags.NonPublic | BindingFlags .Static).Invoke(null, new object [] {resourceLocater});
Stream stream = exprCa.GetStream();
var uri =
new Uri (
( Uri)
typeof (BaseUriHelper ).GetProperty("PackAppBaseUri",
BindingFlags.Static | BindingFlags .NonPublic).GetValue(null, null), resourceLocater);
var parserContext = new ParserContext
{
BaseUri = uri
};
typeof(XamlReader ).GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags .Static)
.Invoke( null, new object[] { stream, parserContext, userControl, true });
}
catch (Exception )
{
}
}
}
The component does not have a resource identified by the uri
最后
以上就是快乐小松鼠为你收集整理的WPF中如何继承一个UserControl的全部内容,希望文章能够帮你解决WPF中如何继承一个UserControl所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复