关于xaml:WPF应用程序中的自定义控件异常

Exception from custom control in WPF app

我正在尝试为我的WPF应用程序创建自定义控件,但无法理解为什么它不起作用。

我有两个项目-一个是我的自定义控件库,其中一个自定义控件是从Image派生的,只有很少的方法,第二个项目是我要使用控件的项目。我不想对样式或绑定进行任何操作,所以我使用的是默认值。

因此,我的自定义控件主题(generic.xaml):

1
2
3
4
5
6
7
   <ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:RTPlayer">
    <Style
     TargetType="{x:Type local:RTPlayer}" BasedOn="{StaticResource {x:Type Image}}">
    </Style>

和代码部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace RTPlayer
{
   public class RTPlayer : Image
   {
    static RTPlayer()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(RTPlayer), new FrameworkPropertyMetadata(typeof(RTPlayer)));
    }

    public void Start()
    {
       // ....
    }
   }
}

在我的主项目中,我添加了对库.dll文件的引用,并且我尝试将控件用作:

1
2
3
4
5
6
7
8
9
10
  <Window x:Class="rtspWPF.MainWindow"
    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:rtspWPF"
    xmlns:CustomControls="clr-namespace:RTPlayer;assembly=RTPlayer"
    xmlns:CustomControls="clr-namespace:RTPlayer;assembly=RTPlayer"
    Title="MainWindow" Height="auto" Width="auto">
<CustomControls:RTPlayer x:Name="image" Margin="10,10,10,10" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  Width="auto" Height="auto"/>

问题是-1)xaml CustomControl:RTPlayer字符串警告我:"无法找到名为" System.Windows.Controls.Image"的资源。资源名称区分大小写"; 2)如果我尝试启动应用程序,则会抛出Markup.XamlParseExceptionMarkup.StaticResourceHolder抛出异常..

我的代码有什么问题?


由于丹尼尔(Daniel)的评论,我已经找到了使我的应用正常运行的方法。

在Daniel告诉我Image组件没有基本样式之后,我发现了一个有类似问题的人:如何在WPF中继承基于类型的样式?

比起我刚刚将我的Generic.xaml文件重写为:

1
2
3
4
5
6
7
8
9
10
11
12
<ResourceDictionary
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:RTPlayer">

   <Style TargetType="Image" x:Key="ImageStyle">

   </Style>

   <Style TargetType="{x:Type local:RTPlayer}" BasedOn="{StaticResource ImageStyle}">
   </Style>
</ResourceDictionary>

一切正常!