c# - How can Activity Viewmodel get data from a Fragment child ViewModel?
问题描述
I'm developing a Xamarin.Android application using MvvmCross and I'm trying to get stored data into Fragment Viewmodel from the main activity Viewmodel.
This is what I have.
And I'm using
- ActivityViewModel for the activity
- FragmentAViewModel for FragmentA
- FragmentBViewModel for FragmentB
So, I'm trying to access to a FragmentAViewModel.SomeProperty from ActivityViewModel object.
Is it possible?
I'm using IMvxMessenger as a workaround to "send" a notification to ActivityViewModel with the content of the property I want to acceess.
Is there any other way to achieve this?
Thanks in advance.
解决方案
一种替代方法是使用依赖注入系统来创建一个单例,该单例可用作视图模型之间的共享上下文。
例子
public interface ISharedContext
{
string Name { get; set; }
}
public class SharedContext : MvxNotifyPropertyChanged, ISharedContext
{
string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
}
SharedContext
在您的 App 类中注册
Mvx.LazyConstructAndRegisterSingleton<ISharedContext, SharedContext>();
在视图模型中的使用。然后,您可以直接绑定到SharedContext
或分配给它的属性并在不同的视图模型中使用。
public class FragmentAViewModel : MvxViewModel
{
public ISharedShoppingCart SharedContext { get; }
public FragmentAViewModel(ISharedContext sharedContext)
{
SharedContext = sharedContext;
}
}
public class ActivityViewModel : MvxViewModel
{
public ISharedShoppingCart SharedContext { get; }
public ActivityViewModel(ISharedContext sharedContext)
{
SharedContext = sharedContext;
}
}
推荐阅读
- python - 熊猫:删除列表中包含的所有行
- java - 数组中每个元素的频率
- excel - 将列数据作为值调用到表中的函数
- flutter - 为什么颤振 2.0.1 与 intl_translation 包不兼容?
- list - SwiftUI 列表:滑动删除奇怪的行为
- reactjs - useEffect 依赖警告
- qt - Qt:为什么在 QMainWindow 中添加状态栏会影响大小调整?
- java - 如何使用 Java 在 Excel 文件中查找特定单词
- c - 我正在尝试使用泰勒级数为 sin x 编写 ac 程序,但在执行程序时无法找出我的错误
- css - CSS shape-outside 和响应式内容