上节中我们讲了怎么样定义一个区域与区域引用视图,但并不是所有的组件都支持组件当作区域使用,比如StackPanel就不支持当作区域来使用:
我们自接使用会报以下错误,这时候我们就要自定义一个区域适配器:
1.首先我们创建一个StackPanelRegionAdapter的类:
1 using Prism.Regions; 2 using System.Windows; 3 using System.Windows.Controls; 4 5 namespace MyTest 6 { 7 public class StackPanelRegionAdapter : RegionAdapterBase<StackPanel> 8 { 9 public StackPanelRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) 10 : base(regionBehaviorFactory) 11 { 12 } 13 14 protected override void Adapt(IRegion region, StackPanel regionTarget) 15 { 16 region.Views.CollectionChanged += (s, e) => 17 { 18 if (e.Action==System.Collections.Specialized.NotifyCollectionChangedAction.Add) 19 { 20 foreach (FrameworkElement view in e.NewItems) 21 { 22 regionTarget.Children.Add(view); 23 } 24 } 25 }; 26 } 27 28 protected override IRegion CreateRegion() 29 { 30 return new Region(); 31 } 32 } 33 }
2.修改MainWindow.xaml为StackPanel作为Region的容器:
3.我们需要在app中注册定义的StackPanelRegionAdapter
1 using Prism.Ioc; 2 using Prism.Regions; 3 using System.Windows; 4 using System.Windows.Controls; 5 6 namespace MyTest 7 { 8 /// <summary> 9 /// Interaction logic for App.xaml 10 /// </summary> 11 public partial class App 12 { 13 protected override Window CreateShell() 14 { 15 return Container.Resolve<MainWindow>(); 16 } 17 18 protected override void RegisterTypes(IContainerRegistry containerRegistry) 19 { 20 21 } 22 protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings) 23 { 24 base.ConfigureRegionAdapterMappings(regionAdapterMappings); 25 regionAdapterMappings.RegisterMapping(typeof(StackPanel) 26 , Container.Resolve<StackPanelRegionAdapter>()); 27 28 } 29 } 30 }
4.修改MainWindowViewModel中绑定的名字:
1 using Prism.Mvvm; 2 using Prism.Regions; 3 4 namespace MyTest 5 { 6 public class MainWindowViewModel:BindableBase 7 { 8 9 private string _title = "hello"; 10 public string Title 11 { 12 get { return _title; } 13 set { SetProperty(ref _title, value); } 14 } 15 16 private readonly IRegionManager regionManager; 17 18 19 public MainWindowViewModel(IRegionManager regionManager) 20 { 21 this.regionManager = regionManager; 22 regionManager.RegisterViewWithRegion("stackRegion", typeof(ViewA)); 23 24 } 25 26 } 27 }
启动项目,我们就可以将StackPanel作为容器使用了: