c# - 如何使用 MVVM 和 Caliburn Micro 在多个 ViewModel 中使用模型中的数据
问题描述
我真的需要你的帮助来为我澄清一些事情;我无法在互联网上找到答案,即使我的问题经常被问到;它从来没有显示人们对接受的答案的意思。
我的问题是这样的:
我有一个 ShellViewModel;在这个 ShellViewModel 上,我想显示一个 PageTitle。然而; 我还希望这个 PageTitle 显示在另一个ViewModel 中;显示在ShellViewModel 内。
在 VB.Net 中,我只需创建一个公共字符串 PageTitle 并从其他表单中引用它(例如 textbox.text = MainForm.PageTitle);但这似乎不适用于 C#/WPF/MVVM ..
如何创建可以从多个位置设置和检索的“全局变量”;虽然都有相同的信息?
我尝试了几件事;这有效,但仅适用于 ShellViewModel(其他 ViewModel 无法访问)
这部分只工作一次;但我仍然有在这个 ViewModel 上创建一个新实例的问题;所以任何其他 ViewModel 仍然会得到另一个数据..
我真的,真的很困惑如何做这样一个卑微的任务......谁愿意帮助一个迷失的灵魂?
================================[编辑]================ ====================== 好的..所以我有一些有用的东西;有人可以验证这是否是正确的方法吗?
namespace ServiceTools.UserInterface.Models
{
public class PageTitleModel
{
public static string Title { get; set; }
public PageTitleModel()
{
Title = "Something something, You dont see me actually.. right?!";
}
}
}
public class ShellViewModel : Conductor<object> {
//Property for the Page title
public string PageTitle
{
get { return PageTitleModel.Title; }
set
{
PageTitleModel.Title = value;
NotifyOfPropertyChange(() => PageTitle);
}
}
public ShellViewModel()
{
PageTitleModel.Title = "Hello World";
// Set the Application Titlebar and DisplayName
SetTitles(PageTitleModel.Title);
}
public void SetTitles (string Title)
{
//Title of the window
this.DisplayName = Title;
PageTitle = Title;
}
}
namespace ServiceTools.UserInterface.ViewModels
{
public class OrderRegistrationViewModel : Screen
{
//private string PageTitle = PageTitleModel.Title;
//Property for the Page title
public string PageTitle
{
get { return PageTitleModel.Title; }
set
{
PageTitleModel.Title = value;
NotifyOfPropertyChange(() => PageTitle);
}
}
}
}
这似乎在两个视图之间同步标题......有人可以验证这是否是要走的路吗?
解决方案
每个 Screen (ViewModel) 在使用 Screen 作为其继承类型时都已经有了这个。他们有一个内置的属性DisplayName
,当然你可以创建一个BaseViewModel
类型的屏幕并重新创建轮子,如果你愿意的话。这是正在实现的IScreen
(具有IHaveDisplayName
)接口的结果Screen
。
//C#//
public class BaseViewModel : Screen {
private string _screenTitle;
public string ScreenTitle {
get => _screenTitle;
set {
_screenTitle = value;
NotifyOfPropertyChange();
}
}
}
//C#//
public class OrderRegistrationViewModel : BaseViewModel {
public OrderRegistrationViewModel(){
DisplayName = "Order Registration";
ScreenTitle = "BumbleBee Tuna";
}
}
<!--XAML -->
<UserControl>
<!-- Bound by convention via DataContext automagically by CM in the underlying framework -->
<TextBlock x:Name="DisplayName" />
<TextBlock x:Name="ScreenTitle" />
</UserControl>
推荐阅读
- logstash - 如何使用 Logstash 过滤器根据其他列的某些行添加新列?
- apache-spark - 从 CSV 分号分隔的数据在 HIVE 中创建表
- fullcalendar - Fullcalendar:在 dayrender 的每个插槽中添加工具提示
- reactjs - React - 像素比 - 为视网膜设备设置 2x 3x 图像
- json - 使用 kotlinx.serialization 库反序列化具有不同值类型的 JSON 数组
- c - 为什么使用左移位运算符后前两位数字丢失?
- r - 更改 geom_bar ggplot 中 20% 条的颜色
- reactjs - Reactjs - CKEditor onchange 提升状态
- php - 在PHP中将字符串中的奇怪字符转换为正常字符?
- python - Python zipfile 从 zip 文件中的目录中提取文件