C#中ViewModel中View的访问按钮

时间:2016-10-11 11:05:21

标签: c# wpf mvvm openfiledialog

我正在尝试访问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我处理点击:

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>

1 个答案:

答案 0 :(得分:3)

MVVM架构中,View和ViewModel是松散耦合的。您应该使用DelegateCommand之类的命令,并将View的DataContext设置为ViewModel的实例,如下所示

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

在XAML中执行类似

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

使用Nuget获取Prism包并在Load Class中使用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.
    }
}