MVVM若干认识问题 [英] MVVM Understanding Issues
问题描述
我对MVVM的问题清单,你不需要回答关于你自己的,它帮我总是赞赏链接:
-
如果我有一个MainPage.xaml中的文件,我使用的代码应该是在MainPage.xaml.cs提交viewmodelclass?没有?
-
如果这段代码是在MainPage.xaml.cs文件:
视图模型基地=新视图模型();
-
如果我实现个ICommand哪能例如访问MainPage.xaml中一个textbox.text?
- 个ICommand完全取代Button.Click事件?难道不是吗?
- 理想的情况下,是的。但在大多数情况下,它很难遵循
-
并非在任何情况下。如果您的视图模型的构造函数不接受参数,你可以在XAML中写:
< Window.Resources>
<局部:视图模型X:键=视图模型/> < - !此行会自动创建视图模型类的实例 - >
< /Window.Resources>
如果视图模型接受参数,那么,你就必须写:
视图模型的基础=新的视图模型(yourArgs);
this.DataContext =基地;
在代码隐藏。
-
如果你想跟随MVVM,绑定文本框的Text属性到视图模型属性:
<文本框的文本={结合MYTEXT}/>
和在视图模型:
私人字符串_myText;
公共字符串MYTEXT
{
{返回_myText; }
组
{
如果(_myText =价值!)
{
_myText =价值;
// NotifyPropertyChanged(MYTEXT);如果需要的话
}
}
}
然后就可以使用RelayCommand或DelegateCommand(谷歌它)与您的文本框内视图模型的文本操作。
- 是。命令也允许对参数传递给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:
If I have a Mainpage.xaml file and I'm using a viewmodelclass which code should be in the Mainpage.xaml.cs file? Nothing?
Should that piece of code be in the Mainpage.xaml.cs file:
Viewmodel base = new Viewmodel();
If I implement ICommands how can I access for example a textbox.text on the Mainpage.xaml?
- ICommands completely replace the Button.Click event? Don't they?
- Ideally, yes. But in most of cases it's hard to follow
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.
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.
- Yes. Command allows also to pass parameter to ICommand (for example, when you will use RelayCommand)
Hope, it helps.
这篇关于MVVM若干认识问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!