MVVM 理解问题 [英] MVVM Understanding Issues

查看:19
本文介绍了MVVM 理解问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 mvvm 的问题列表,您不需要自己回答,总是感谢能帮助我进一步的链接:

A list of my questions towards mvvm, you don't need to answer on your own, links which help me further are always appreciated:

  1. 如果我有一个 Mainpage.xaml 文件并且我使用的是视图模型类,那么 Mainpage.xaml.cs 文件中应该包含哪些代码?没有什么?

  1. If I have a Mainpage.xaml file and I'm using a viewmodelclass which code should be in the Mainpage.xaml.cs file? Nothing?

那段代码是否应该在 Mainpage.xaml.cs 文件中:

Should that piece of code be in the Mainpage.xaml.cs file:

Viewmodel base = new Viewmodel();

Viewmodel base = new Viewmodel();

如果我实现了 ICommands,我该如何访问 Mainpage.xaml 上的 textbox.text?

If I implement ICommands how can I access for example a textbox.text on the Mainpage.xaml?

推荐答案

  1. 理想情况下,是的.但在大多数情况下很难遵循
  2. 并非在所有情况下.如果你的 ViewModel 的构造函数不接受参数,你可以用 xaml 编写它:

  1. Ideally, yes. But in most of cases it's hard to follow
  2. Not in every case. If your ViewModel's constructor does not accept arguments, you can write it in xaml:

<Window.Resources>
    <local:ViewModel x:Key="viewModel" /> <!-- this row will automatically create instance of ViewModel class-->
</Window.Resources>

如果视图模型类接受参数,那么是的,您必须编写:

If view model class accepts arguments, then yes, you will have to write:

ViewModel base = new Viewmodel(yourArgs);
this.DataContext = base;

在代码隐藏中.

  1. 如果你想跟着MVVM,把TextBox的Text属性绑定到Viewmodel属性:

  1. If you want to follow MVVM, bind TextBox's Text property to Viewmodel property:

<TextBox Text="{Binding MyText}" />

在 ViewModel 中:

and in ViewModel:

private string _myText;
public string MyText
{
    get { return _myText; }
    set 
    {
        if (_myText != value)
        {
            _myText = value;
            // NotifyPropertyChanged("MyText"); if needed
        }
    }
}

然后你可以使用 RelayCommand 或 DelegateCommand(谷歌它)来操作你在 ViewModel 中的 TextBox 的文本.

Then you could use RelayCommand or DelegateCommand (google it) to operate with text of your TextBox inside ViewModel.

  1. 是的.Command 还允许将参数传递给 ICommand(例如,当您将使用 RelayCommand 时)

希望能有所帮助.

这篇关于MVVM 理解问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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