【问题标题】:Access button from View in ViewModel in C#从 C# 中的 ViewModel 中的视图访问按钮
【发布时间】:2016-10-11 11:05:20
【问题描述】:

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

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>

【问题讨论】:

  • 您的xaml 是如何定义的?
  • 你违反了 MVVM 的概念。您的视图模型不应该对您的视图一无所知。如果你想在你的视图模型中有行为,你应该使用 ICommand
  • 您的 View 的 DataContext 似乎没有设置为您的 Load 类。
  • @NikhilAgrawal 它很大,但我已将按钮放在主窗口中
  • @GalDak:只有你的按钮。

标签: c# wpf mvvm openfiledialog


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多