外观
Prism多区域共享属性
方式
1. 单例模式的 ViewModel
创建一个单例 ViewModel,该 ViewModel 包含需要共享的属性。然后,通过 Prism 的依赖注入容器将这个单例 ViewModel 注入到需要访问该属性的各个区域的 ViewModel 中。
public class SharedViewModel {
public string SharedProperty { get; set; }
// 其他共享属性和方法
}
// 在 Prism 的 Bootstrapper 或 UnityContainer 中配置单例
container.RegisterSingleton<SharedViewModel>();更适合于在应用程序的不同部分之间共享和同步状态。
2.属性通知
//构造函数注入的形式不行,必须是通知函数的形式
public SharedPropertyService sharedPropertyService;
public SharedPropertyService _SharedPropertyService
{
get => sharedPropertyService;
set => SetProperty(ref sharedPropertyService, value);
}
//PropertyChanged事件需要内部的属性
private bool isSdMode = true;
/// <summary>
/// 是否手动扫描模式
/// </summary>
public bool IsSdMode { get => isSdMode; set => SetProperty(ref isSdMode, value); }3. 使用事件或消息
通过 Prism 的事件聚合器(Event Aggregator),发布和订阅消息,从而在不同的区域和 ViewModel 之间共享数据。
public class SharedPropertyUpdatedEvent : PubSubEvent<string>
{
// 可以传递更复杂的对象,而不仅仅是字符串
}
// 在需要共享属性的 ViewModel 中发布事件
_eventAggregator.GetEvent<SharedPropertyUpdatedEvent>().Publish(newValue);
// 在其他 ViewModel 中订阅事件
var sharedPropertyUpdatedEvent = _eventAggregator.GetEvent<SharedPropertyUpdatedEvent>();
sharedPropertyUpdatedEvent.Subscribe(value => {
// 更新当前 ViewModel 的属性
SharedProperty = value;
});应用程序中跨组件共享数据的常见方式,特别是当共享的数据需要触发动作或通知其他组件时。
4. 使用共享的服务类
创建一个服务类,该类包含共享的属性,并提供修改和获取这些属性的方法。然后,将这个服务类注入到需要访问这些属性的 ViewModel 中。
public class SharedPropertyService
{
public string SharedProperty { get; set; }
// 其他业务逻辑
}
// 在 ViewModel 中使用服务
public class SomeViewModel
{
private readonly SharedPropertyService _sharedPropertyService;
public SomeViewModel(SharedPropertyService sharedPropertyService)
{
_sharedPropertyService = sharedPropertyService;
}
public string SharedProperty => _sharedPropertyService.SharedProperty;
}5. 使用依赖项属性
创建一个静态类,其中包含依赖项属性(Dependency Property),这些属性可以在不同的视图和 ViewModel 之间共享。
public static class SharedProperties
{
public static readonly DependencyProperty SharedPropertyProperty = DependencyProperty.Register("SharedProperty", typeof(string), typeof(SharedProperties), new PropertyMetadata("Default Value"));
public static string SharedProperty
{
get { return string)DependencyObject.GetValue(SharedPropertyProperty); } set { DependencyObject.SetValue(SharedPropertyProperty, value); } }
}依赖项属性主要用于 XAML 和视图层,因此它们可能不是在 ViewModel 之间共享数据的最佳选择。通常,使用事件聚合器、服务类或单例模式的 ViewModel 是更推荐的方法。
6. 使用 ViewModel 的继承
如果共享属性的 ViewModel 之间存在继承关系,可以在基类 ViewModel 中定义共享属性,然后让所有子类 ViewModel 继承这个基类。
public class BaseViewModel
{
public string SharedProperty { get; set; }
}
public class ViewModelA : BaseViewModel
{
// 可以使用 SharedProperty
}
public class ViewModelB : BaseViewModel
{
// 同样可以使用 SharedProperty
}