更新时间:2022-10-15 15:11:45
并非在任何情况下。如果您的视图模型的构造函数不接受参数,你可以在XAML中写:
< Window.Resources>
<局部:视图模型X:键=视图模型/> < - !此行会自动创建视图模型类的实例 - >
< /Window.Resources>
如果视图模型接受参数,那么,你就必须写:
视图模型的基础=新的视图模型(yourArgs);
this.DataContext =基地;
在代码隐藏。
如果你想跟随MVVM,绑定文本框的Text属性到视图模型属性:
<文本框的文本={结合MYTEXT}/>
和在视图模型:
私人字符串_myText;
公共字符串MYTEXT
{
{返回_myText; }
组
{
如果(_myText =价值!)
{
_myText =价值;
// NotifyPropertyChanged(MYTEXT);如果需要的话
}
}
}
然后就可以使用RelayCommand或DelegateCommand(谷歌它)与您的文本框内视图模型的文本操作。
希望,它帮助。
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?
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.
Hope, it helps.