2016-10-11 157 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. 
    } 
}