从 C# 中的 ViewModel 中的视图访问按钮 [英] Access button from View in ViewModel in C#

查看:58
本文介绍了从 C# 中的 ViewModel 中的视图访问按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 ViewModel 中的 View 访问一个按钮,但是在出现错误时我遗漏了一些东西:

I am trying to access a button from View in ViewModel, but I am missing something as I get the error:

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 中,我像这样处理点击:

The purpose of the button is to open a OpenFileDialog. In my ViewModel I handle the click like this:

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>

推荐答案

MVVM 架构中,View 和 ViewModel 是松耦合的.你应该使用像 DelegateCommand 这样的 Command 并像这样将 View 的 DataContext 设置为 ViewModel 的实例

In MVVM architecture, View and ViewModel are loosly coupled. You should use Command like DelegateCommand and set DataContext of View as instance of ViewModel like this

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

在 XAML 中做一些类似

In XAML do something like

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

使用 Nuget 获取 Prism 包,并在加载类中使用 DelegateCommand 之类的

Use Nuget to get Prism Packages and in Load Class, use DelegateCommand like

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.
    }
}

这篇关于从 C# 中的 ViewModel 中的视图访问按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆