微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在页面之间共享视图模型?

如何解决如何在页面之间共享视图模型?

我可以将数据添加到视图模型,但是当我尝试从另一个页面访问同一视图模型时,数据将丢失。如何在多个页面上使用相同的视图模型?

viewmodel代码

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;

namespace App1
{
    class Debtviewmodel
    {
        ObservableCollection<Debt> _Debt = new ObservableCollection<Debt>();

        public System.Windows.Input.ICommand AddAccountCommand => new Command(AddAccount);
        public System.Windows.Input.ICommand RemoveAccountCommand => new Command(RemoveAccount);
        public System.Windows.Input.ICommand UpdateAccountCommand => new Command(UpdateAccount);
        public ObservableCollection<Debt> Debt { get; set; }
        public string Account { get; set; }
        public string SelectedAccount { get; set; }
        public double AnnualPercentageRate { get; set; }
        public decimal Amount { get; set; }
        public decimal MonthlyPayment { get; set; }
        public bool IntroductoryRate { get; set; }

        public double IntroductoryPercentageRate { get; set; }

        public int IntroductoryRange { get; set; }

        public Debtviewmodel()
        {
            ObservableCollection<Debt> Debts = _Debt;
        }

        public void AddAccount()
        {            

            var debt = new Debt(Account,Amount,AnnualPercentageRate,MonthlyPayment,IntroductoryRate,IntroductoryPercentageRate,IntroductoryRange);
            
            if (Account != null)
            {
                _Debt.Add(debt);
            }
        }

        public void RemoveAccount()
        {
            //Debt.Remove(SelectedAccount);
        }

        public void UpdateAccount()
        {
            //int newIndex = Debt.IndexOf(SelectedAccount);
            //Debt.Remove(SelectedAccount);
            
            //Debt.Add(Account);
            //int oldindex = Debt.IndexOf(Account);

            //Debt.Move(oldindex,newIndex);
        }
    }
}

列表页

<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:local="clr-namespace:App1"
             mc:Ignorable="d"
             x:Class="App1.ListViewPage">

    <!-- required to map viewmodel -->
    <ContentPage.BindingContext>
        <local:Debtviewmodel />
    </ContentPage.BindingContext>

    <ContentPage.toolbaritems>
        <ToolbarItem Text="Add"></ToolbarItem>
    </ContentPage.toolbaritems>
    
<!-- Bind variable in view model to listview itemsource -->
    <ContentPage.Content>
        
        <StackLayout>

            <!--<Entry Placeholder="Account"
                   Text="{Binding Account}"/>
            
            <Button Text="Add" Command="{Binding AddAccountCommand}"></Button>
            <Button Text="Remove" Command="{Binding RemoveAccountCommand}"></Button>
            <Button Text="Update" Command="{Binding UpdateAccountCommand}"></Button>-->

            <!--textcell,custom cells,or image cell-->
            
            <ListView ItemsSource="{Binding Debt}" SelectedItem="{Binding SelectedAccount}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <Grid.ColumnDeFinitions>
                                    <ColumnDeFinition Width="2*" />
                                    <ColumnDeFinition Width="2*" />
                                    <ColumnDeFinition Width="1*" />
                                    <ColumnDeFinition Width="3*" />
                                    
                                </Grid.ColumnDeFinitions>
                                
                                <Label Text="{Binding AccountName}"
                                       FontSize="Medium"
                                       VerticalTextAlignment="Start"
                                       Grid.Column="0"></Label>
                                
                                <Label Text="Balance"                                
                                       VerticalTextAlignment="Start"
                                       Grid.Column="1"></Label>
                                <Label Text="{Binding InitialAmount}"                                
                                       VerticalTextAlignment="End"
                                       Grid.Column="1"></Label>

                                <Label Text="APR"
                                       VerticalTextAlignment="Start"
                                       Grid.Column="2"></Label>
                                <Label Text="{Binding AnnualPercentageRate}"
                                       VerticalTextAlignment="End"
                                       Grid.Column="2"></Label>
                                
                                <Label Text="Monthly Payment"
                                       VerticalTextAlignment="Start"
                                       Grid.Column="3"></Label>
                                <Label Text="{Binding MonthlyPayment}"
                                       VerticalTextAlignment="End"
                                       Grid.Column="3"></Label>

                                <Image Source="edit.png" Grid.Column="4"></Image>
                                <Image Source="trash.jpg" Grid.Column="5"></Image>
                                
                            </Grid>
                            
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
                
            </ListView>
        </StackLayout>

    </ContentPage.Content>
</ContentPage>

添加页面

<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:local="clr-namespace:App1"
             mc:Ignorable="d"
             x:Class="App1.ListViewPage">

    <!-- required to map viewmodel -->
    <ContentPage.BindingContext>
        <local:Debtviewmodel />
    </ContentPage.BindingContext>

    <ContentPage.toolbaritems>
        <ToolbarItem Text="Add"></ToolbarItem>
    </ContentPage.toolbaritems>
    
<!-- Bind variable in view model to listview itemsource -->
    <ContentPage.Content>
        
        <StackLayout>

            <!--<Entry Placeholder="Account"
                   Text="{Binding Account}"/>
            
            <Button Text="Add" Command="{Binding AddAccountCommand}"></Button>
            <Button Text="Remove" Command="{Binding RemoveAccountCommand}"></Button>
            <Button Text="Update" Command="{Binding UpdateAccountCommand}"></Button>-->

            <!--textcell,or image cell-->
            
            <ListView ItemsSource="{Binding Debt}" SelectedItem="{Binding SelectedAccount}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <Grid.ColumnDeFinitions>
                                    <ColumnDeFinition Width="2*" />
                                    <ColumnDeFinition Width="2*" />
                                    <ColumnDeFinition Width="1*" />
                                    <ColumnDeFinition Width="3*" />
                                    
                                </Grid.ColumnDeFinitions>
                                
                                <Label Text="{Binding AccountName}"
                                       FontSize="Medium"
                                       VerticalTextAlignment="Start"
                                       Grid.Column="0"></Label>
                                
                                <Label Text="Balance"                                
                                       VerticalTextAlignment="Start"
                                       Grid.Column="1"></Label>
                                <Label Text="{Binding InitialAmount}"                                
                                       VerticalTextAlignment="End"
                                       Grid.Column="1"></Label>

                                <Label Text="APR"
                                       VerticalTextAlignment="Start"
                                       Grid.Column="2"></Label>
                                <Label Text="{Binding AnnualPercentageRate}"
                                       VerticalTextAlignment="End"
                                       Grid.Column="2"></Label>
                                
                                <Label Text="Monthly Payment"
                                       VerticalTextAlignment="Start"
                                       Grid.Column="3"></Label>
                                <Label Text="{Binding MonthlyPayment}"
                                       VerticalTextAlignment="End"
                                       Grid.Column="3"></Label>

                                <Image Source="edit.png" Grid.Column="4"></Image>
                                <Image Source="trash.jpg" Grid.Column="5"></Image>
                                
                            </Grid>
                            
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
                
            </ListView>
        </StackLayout>

    </ContentPage.Content>
</ContentPage>

解决方法

如杰森所说:If you specify the VM in XAML it will create a new instance for each page.他们是完全不同的。

如何在多个页面上使用相同的视图模型?

有很多方法可以做到。

例如,您可以在App.cs中定义/创建静态ViewModel:

public partial class App : Application
{
    public static DebtViewModel sharedViewModel { get; set; }

    public App()
    {
        InitializeComponent();

        MainPage = new MainPage();

        createViewModel();
    }

    public void createViewModel() {

        sharedViewModel = new DebtViewModel();
    }

    public class DebtViewModel { 
    
    }
}

然后在其他页面中,可以将此ViewModel设置为页面的bindingContext:

public partial class Page1 : ContentPage
{
    public Page1()
    {
        InitializeComponent();

        this.BindingContext = App.sharedViewModel;
    }
}

在解决方案中,将实例传递到构造函数上的新页面。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。