我可以在XAML中链接和实例化ViewModel,还是需要在支持.cs时执行此操作?

时间:2017-09-19 13:33:50

标签: xamarin xamarin.forms

我有这个XAML

<?xml version="1.0" encoding="UTF-8"?>
   <Frame 
      xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
      xmlns:local="clr-namespace:Japanese;assembly=Japanese" 
      x:Class="Japanese.PhrasesFrame">
      <StackLayout x:Name="phrasesFrameStackLayout">

并支持.cs

public partial class PhrasesFrame : Frame
{
    public PhrasesFrameViewModel vm = new PhrasesFrameViewModel();

    public PhrasesFrame(PhrasesPage phrasesPage)
    {
        phrasesFrameStackLayout.BindingContext = vm;

和ViewModel

public class PhrasesFrameViewModel : ObservableProperty
{

有人能告诉我是否有必要在后台.cs中创建一个新的PhrasesFrameViewModel()实例,或者是否有更有效的方法来创建这个以及在XAML中绑定它?

1 个答案:

答案 0 :(得分:1)

您可以设置值inside a model,然后您不需要在backing.cs中创建新实例。

在模特:

public class PhrasesFrameViewModel
{
    public string Parameter1 { set; get; } = "P1";
    public bool Parameter2 { set; get; } = true;
    public List<string> Parameter3 { set; get; } = new List<string>(){"1","2"};
}

在XMAL中:

<?xml version="1.0" encoding="UTF-8"?>
<Frame xmlns="http://xamarin.com/schemas/2014/forms" 
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ProjectName" 
x:Class="ProjectName.PhrasesFrame"
>


<StackLayout x:Name="phrasesFrameStackLayout">
    <StackLayout.BindingContext>
        <local:PhrasesFrameViewModel/>
    </StackLayout.BindingContext>

    <Label Text = "{Binding Parameter1}"/>
    <Switch IsToggled = "{Binding Parameter2}"/>

    <ListView ItemsSource = "{Binding Parameter3}">
        <ListView.ItemTemplate>
            <DataTemplate>
                 <TextCell Text="{Binding}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</StackLayout>

结果:

enter image description here