首页 > 解决方案 > 使用 C#,当用作静态资源时,如何访问 ViewModel 的属性和方法?

问题描述

我在 App.xaml 中将 ViewModel 实例化为静态资源。

<?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>

我希望能够在 C# 中访问 ViewModel 的属性

例如

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

标签: c#xamarinxamarin.formsmvvmviewmodel

解决方案


我创建 MerchandiserViewModel 类,实现 INotifyPropertyChanged 接口来通知数据更改。

 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!!!!!!!");
        });
    }
}

添加 APP.xaml 作为静态资源。

<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>

您可以从每个 contentpage.cs 中的 viewmodel 获取属性和命令。

 private void Button_Clicked(object sender, EventArgs e)
    {

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

        ICommand command = viewmodel.command1;
    
    }

推荐阅读