2015-10-13 71 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也幫助了我。

相關問題