且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVVM若干认识问题

更新时间:2022-10-15 15:11:45


  1. 理想的情况下,是的。但在大多数情况下,它很难遵循

  2. 并非在任何情况下。如果您的视图模型的构造函数不接受参数,你可以在XAML中写:

     < Window.Resources> 
    <局部:视图模型X:键=视图模型/&GT; &LT; - !此行会自动创建视图模型类的实例 - &GT;
    &LT; /Window.Resources>








如果视图模型接受参数,那么,你就必须写:

 视图模型的基础=新的视图模型(yourArgs); 
this.DataContext =基地;

在代码隐藏。




  1. 如果你想跟随MVVM,绑定文本框的Text属性到视图模型属性:

     &LT;文本框的文本={结合MYTEXT}/&GT; 




和在视图模型:

 私人字符串_myText; 
公共字符串MYTEXT
{
{返回_myText; }

{
如果(_myText =价值!)
{
_myText =价值;
// NotifyPropertyChanged(MYTEXT);如果需要的话
}
}
}



然后就可以使用RelayCommand或DelegateCommand(谷歌它)与您的文本框内视图模型的文本操作。




  1. 是。命令也允许对参数传递给ICommand的(例如,当您将使用RelayCommand)



希望,它帮助。


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. If I have a Mainpage.xaml file and I'm using a viewmodelclass which code should be in the Mainpage.xaml.cs file? Nothing?

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

    Viewmodel base = new Viewmodel();

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

  4. ICommands completely replace the Button.Click event? Don't they?

  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;

in code-behind.

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

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

and in ViewModel:

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

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

  1. Yes. Command allows also to pass parameter to ICommand (for example, when you will use RelayCommand)

Hope, it helps.