2016-10-11 89 views
0

我試圖從ViewViewModel訪問按鈕,但我失去了一些東西,因爲我得到的錯誤:訪問按鈕

Severity Code Description Project File Line Suppression State 
Error CS1061 'MainWindow' does not contain a definition for 'Loadfile' and no extension method 'Loadfile' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?) Uml-Creator C:\Users\HH\Source\Repos\UMLEditor\Uml-Creator\Uml-Creator\View\MainWindow.xaml 54 Active 

按鈕的目的是打開OpenFileDialog。在我ViewModel我處理click這樣的:

class Load 
    { 

     private void Loadfile(object sender, EventArgs e) 
     { 
      OpenFileDialog loadfile = new OpenFileDialog(); 
      if (loadfile.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       // File.Text = File.ReadAllText(loadfile.FileName); 
      } 
     } 
} 

和視圖:

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 
    } 

編輯:

<Button x:Name="openButton" ToolTip="Open project" Click="Load_Click"> 
        <Image Source="pack://application:,,,/Images\Open.png" Stretch="UniformToFill" Height="17"></Image> 
       </Button> 
+0

xaml是如何定義的? –

+1

您違反了MVVM的概念。你的viewmodel不應該知道你的視圖。如果你想在你的viewmodel中有行爲,你應該使用ICommand – Alex

+0

看來你的View的DataContext沒有設置爲你的'Load'類。 – Rabban

回答

3

MVVM建築,景觀和視圖模型的鬆耦合。您應該使用命令像DelegateCommand並設置DataContext查看作爲視圖模型的實例這樣

public MainWindow() 
{ 
    InitializeComponent(); 
    DataContext = new Load(); 
} 

在XAML中做這樣的事情

<Button .... Click = "{Binding ClickCommand}" /> 

使用的NuGet獲得棱鏡的軟件包,並在負載類中,使用DelegateCommand像

public Load 
{  
    public DelegateCommand<object> _clickCommand; 
    public DelegateCommand<object> ClickCommand  
    { 
     get 
     { 
      if (_clickCommand == null) 
       _clickCommand = new DelegateCommand<object>(OnClickCommandRaised); 
      return _clickCommand; 
     } 
    } 

    public void OnClickCommandRaised(object obj) 
    { 
     //Your click logic. 
    } 
}