【问题标题】:Exception from custom control in WPF appWPF 应用程序中自定义控件的异常
【发布时间】:2016-10-10 15:26:29
【问题描述】:

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

我有两个项目 - 一个是我的自定义控件库,其中一个自定义控件源自 Image,只有几个方法,第二个项目是我想使用我的控件。我不想对样式或绑定做任何事情,所以我使用默认值。

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

   <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>

及代码部分:

namespace RTPlayer
{
   public class RTPlayer : Image
   {
    static RTPlayer()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(RTPlayer), new FrameworkPropertyMetadata(typeof(RTPlayer)));
    }

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

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

  <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.XamlParseException Markup.StaticResourceHolder 抛出异常..

我的代码有什么问题?

【问题讨论】:

  • 你能发布XamlParseException.InnerException的堆栈跟踪吗?
  • 图像控件没有可以在样式中继承的基本样式。

标签: wpf xaml custom-controls


【解决方案1】:

感谢 Daniel 在 cmets 中的回答,我发现了我应该做些什么才能让我的应用正常运行。

Daniel 告诉我 Image 组件没有基本样式后,我找到了一个有类似问题的人:How to inherit type-based styles in WPF?

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

<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>

一切正常!

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    相关资源
    最近更新 更多