使用C#,如何访问ViewModel';当用作静态资源时,是什么属性和方法?

使用C#,如何访问ViewModel';当用作静态资源时,是什么属性和方法?,c#,xamarin,xamarin.forms,mvvm,viewmodel,C#,Xamarin,Xamarin.forms,Mvvm,Viewmodel,我在App.xaml中将ViewModels实例化为静态资源 <?xml version="1.0" encoding="utf-8" ?> <Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

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

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

我创建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>

你没有,至少在MVVM中没有。MVVM分离视图及其数据(viewmodel)。您试图实现的目标违反了MVVM原则。顺便说一句,这似乎是一个XY问题链接很好的例子。我将重新评估我的问题并相应地更新。这实际上是我发布的另一个问题的想法。有关上下文,请参见XY问题链接(这很好),如其所述,请后退一步。在这节课上,你一直提到静态,在你发布的另一个问题上。请编辑您现有的问题。你能详细说明你所指的是“静态”的部分吗?为什么?这应该是你应用程序中的一些全局属性吗?它是否应该是一个单例实例,您正在从全局使用的设置中获取您想要公开的设置?请澄清您试图从中获得什么,并应用更好的上下文。谢谢DRapp,当我提到
静态资源时,我指的是
App.xaml
资源字典中存储的资源。我想引用/继承每个
ViewModel
全局ViewModel的单个实例,该实例包含
SelectedItem
的属性,该属性来自
ListView
我遇到的问题是我需要跟踪哪个项目(或我的案例中的跟单员)已选择,以便每个ViewModel都可以显示特定于该选择的绑定。感谢Cherry,我将使用此作为可接受的答案,因为它从技术上回答了这个问题。然而,正如其他人之前指出的,我的问题比我最初认为的要深一点,我可能需要重新审视这个问题,寻找最佳解决方案。
<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>
 private void Button_Clicked(object sender, EventArgs e)
    {

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

        ICommand command = viewmodel.command1;
    
    }