简体   繁体   中英

Using C#, how can I access the ViewModel's properties and methods when used as a static resource?

I have ViewModels instantiated as a Static Resource in App.xaml.

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MobileApp.App"
             xmlns:ViewModels="clr-namespace:MobileApp.ViewModels">
    <Application.Resources>
        <ViewModels:MerchandiserViewModel x:Key="MerchandiserViewModel" />
    </Application.Resources>
</Application>

I would like to be able to access the properties of the ViewModel in C#

eg

string MerchandiserName = "Reference to Static Resource "MerchandiserViewModel.Name" Property Here";

I create MerchandiserViewModel class, implementing INotifyPropertyChanged interface to notify data changed.

 public class MerchandiserViewModel:ViewModelBase
{
    private string _str;
    public string str
    {
        get { return _str; }
        set
        {
            _str = value;
            RaisePropertyChanged("str");
        }
    }
    public ICommand command1 { get; set; }    
         
    public MerchandiserViewModel()
    {
        str = "test";
        command1 = new Command(()=> {

            Console.WriteLine("this is test!!!!!!!");
        });
    }
}

Adding in APP.xaml as static resource.

<Application
x:Class="FormsSample.App"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:models="clr-namespace:FormsSample.simplecontrol"
xmlns:resources="clr-namespace:FormsSample.resourcedictionary">
<Application.Resources>
    
    <models:MerchandiserViewModel x:Key="model1" />
</Application.Resources>

You can get properties and command from viewmodel in every contentpage.cs.

 private void Button_Clicked(object sender, EventArgs e)
    {

        MerchandiserViewModel viewmodel = (MerchandiserViewModel)Application.Current.Resources["model1"];
        string value1= viewmodel.str;

        ICommand command = viewmodel.command1;
    
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM