2016-08-01 53 views
0

我有一個問題得到和事件處理程序工作的按鈕。我使用Visual Studio 2015年我的代碼及以下的錯誤是:WPF C#按鈕事件處理程序不工作

XAML:

<Window x:Class="WpfApplication1.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:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="500" Width="983.334"> 
. 
. 
. 
    <Button x:Name="Button1" Content="Database" HorizontalAlignment="Left" 
      Margin="10,427,0,0" VerticalAlignment="Top" Width="99" 
      Click="Button1_Click"/> 

背後代碼:

namespace WpfApplication1 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 
     private void Button1_Click(object sender, RoutedEventArgs e) 
     { 
      MessageBox.Show("Test"); 
     } 
    } 
} 

Error: CS1061 'MainWindow' does not contain a definition for 'Button1_Click' and no extension method 'Button1_Click' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?)

每當我添加一個按鈕,然後單擊事件處理程序部分,這是我看到:文檔項目沒有代碼隱藏文件。在添加事件處理程序之前添加代碼隱藏文件和類定義。

任何幫助,將不勝感激。

+0

你能後開''元素和屬性從你的XAML文件? – MickyD

+0
+0

謝謝,通常會將[編輯](http://stackoverflow.com/posts/38709809/edit)它。我已經爲你做了:) – MickyD

回答

0

它爲我以下XAML

<Window x:Class="WpfApplication1.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:WpfApplication1" mc:Ignorable="d" Title="MainWindow" Height="500" Width="983.334"> 
    <Button x:Name="Button1" Content="Database" HorizontalAlignment="Left" 
     Margin="10,427,0,0" VerticalAlignment="Top" Width="99" Click="Button1_Click"/> 
</Window> 

和隱藏文件

/// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Button1_Click(object sender, RoutedEventArgs e) 
     { 
      MessageBox.Show("Test"); 
     } 
    } 

這是你有什麼下面的代碼。 您是否嘗試過重建解決方案?

+0

是的,我已經嘗試過多次重建,並且搜索了類似的問題,但沒有成功。 – CausedByMonkey

+0

@CausedByMonkey爲了萬一發生了奇怪的事情,也許使用嚮導創建一個新項目並重復你所做的事情? – MickyD

+0

那麼我複製了一個新的Visual Studio實例中的確切代碼,它的工作。不知道爲什麼。 – CausedByMonkey