c# - 使用 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";
解决方案
我创建 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;
}
推荐阅读
- r - 使用 R 连接到位于其他 ip 上的 oracle 数据库
- selenium - Selenium ElementClickInterceptedException - 拦截/接收相同的元素
- vue.js - 将阿波罗查询结果存储在本地状态?
- apache-camel - 在不使用 XSLT 的 Apache Camel Route 中使用 JAXB 从一种 XML 转换为另一种 XML 格式
- javascript - 即使html文件在同一目录中,ie11也会在文件上给出cors错误
- python - 功能属性寿命
- php - 如何使用嵌套的项目列表来减少数据库查询的数量
- networking - 搭建一个可以全局查询的NTP服务器
- angular - 如何在Angular应用程序中使routerlink既可点击又可双击?
- linux - 一个定期执行并且在收到信号时执行的函数可以是一个临界区吗?