Xamarin网站上有一个很好的ViewModel示例How can I determine what causes repeated Windows Installer self-repair? 但是示例中没有模型,只有View和ViewModel
鉴于它的ViewModel
namespace XamlSamples
{
class ClockViewModel : INotifyPropertyChanged
{
DateTime dateTime;
public event PropertyChangedEventHandler PropertyChanged;
public ClockViewModel()
{
this.DateTime = DateTime.Now;
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
this.DateTime = DateTime.Now;
return true;
});
}
让我们说这个模型
namespace XamlSamples
{
public class ClockModel
{
public TimeSpan time;
...some other properties etc
如何将它们集成在一起并将xaml控件绑定到ViewModel属性和Model属性?
我可以在ViewModel中复制它们并设置它的构造函数,如
public ClockViewModel(ClockModel Model)
{
time = Model.time;
... other properties same way
}
但它看起来真的很丑陋和错误。
这样做的最佳做法是什么?在前面提到的示例中,ViewModel属性已绑定,但如何绑定模型属性或以干净的方式将它们添加到ViewModel?
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XamlSamples;assembly=XamlSamples"
x:Class="XamlSamples.ClockPage"
Title="Clock Page">
<Label Text="{Binding DateTime,
StringFormat='{0:T}'}"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center">
<Label.BindingContext>
<local:ClockViewModel />
</Label.BindingContext>
</Label>
</ContentPage>