2015-10-13 54 views
3
<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:CustomCalc"> 
    <Style TargetType="{x:Type local:CustomControl1}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type local:CustomControl1}"> 

        <TextBlock Text="welcome" Height="50" Width="150" MouseDown=""/> 

       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</ResourceDictionary> 

在上述程序中,(在定制控制库的程序我锻炼) 我试图改变控制正文块=>按钮。(正文块充当按钮的功能) 所以我尝试添加一个事件到文本块,它给出了一个错误消息“确保事件失败”, 而这个文件名是“Generic.xaml”,所以我添加了一个类“Generic.xaml.cs”,但同样的错误显示。 请解释为什么它应该发生以及如何解决它,在此先感谢。“确保事件失败”错误发生

回答

5

您需要添加x:Class属性以支持XAML文件中的事件处理程序。所以,你的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:CustomCalc" 
    x:Class="CustomCalc.Generic"> 
    <Style TargetType="{x:Type local:CustomControl1}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type local:CustomControl1}"> 
        <TextBlock Text="welcome" Height="50" Width="150" MouseDown="TextBlock_MouseDown"/> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</ResourceDictionary> 

而且作为Generic.xaml.cs

namespace CustomCalc 
{ 
    public partial class Generic : ResourceDictionary 
    { 
     private void TextBlock_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) 
     { 

     } 
    } 
} 

也不要忘记合并您ResourceDictionaryApp.Xaml文件:

<Application.Resources> 
    <ResourceDictionary > 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="pack://application:,,,/CustomCalc;component/Generic.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 
+2

我有一个类似的问题,但我有定义'x:Class'。原来我的名字是错的。约定是'x:Class =“NAMESPACE.CLASSNAME”'重命名我的文件后,我从未更改过名称。 – ThePersonWithoutC

1

在我的情况与Visual Studio 2015和一个WPF项目,错误消失后Vis ual Studio重新启动。

0

在我的情况下,XAML文件(App.xaml是特定的)在我尝试创建事件时陷入共享项目中,并且与此线程的错误主题卡住了几分钟。

我的解决方案是从共享项目中排除XAML文件及其XAML.cs文件,然后在每个相关平台项目中链接(不复制!)它。

请参见下面的GIF的链接过程的图形可视: Linking files between projects

来源: http://geertvanhorrik.com/2015/04/01/fix-for-wpf-images-and-shared-projects/

0

我的问题被关闭并重新打开xaml文件导致错误解决(的Visual Studio 2017) 。我的xaml也在共享项目中。

如果需要重新启动Visual Studio也帮助了我。

相关问题