wpf stylet框架 关于View与viewmodel自动关联绑定的问题

1.1 命名规则   Aview 对应  AVIewModel,       文件夹  views  和    viewmodels

1.2 需要注册服务

//RootViewModel是主窗口

public class Bootstrapper : Bootstrapper
 {
     /// 
     ///     配置IoC容器。为数据共享创建服务
     /// 
     /// 
     protected override void ConfigureIoC(IStyletIoCBuilder builder)
     {
         builder.Bind().ToSelf().InSingletonScope();
         builder.Bind().ToSelf();
     }

 2 主窗口打开子窗口  如:RootViewModel==>AddCategoryViewModel   

命令绑定方式:   Command="{s:Action OpenWindowAction}"

public RootViewModel _rootViewModel ;
private IWindowManager _windowManager;
 
public RootViewModel(IWindowManager windowManager,SharedDataService sharedService)
{
           _windowManager = windowManager;
           EditContent =  new();
           _rootViewModel = this;
           _sharedService = sharedService;
           _sharedService.CategoryNameChanged += OnCategoryAdded;

}  

 public void OpenWindowAction(object commandParameter)
 {
     _windowManager.ShowWindow(new AddCategoryViewModel(_sharedService));  //打开子窗口
   
 }
     
//xaml :

3 窗口通信 , 注册服务 如上1.2:   

 private readonly SharedDataService _sharedService= new(); 

 public NoteContentModel _noteContentModel = new();


public RootViewModel(IWindowManager windowManager,SharedDataService sharedService)
{
           _windowManager = windowManager;
           EditContent =  new();
           _rootViewModel = this;
           _sharedService = sharedService;
           _sharedService.CategoryNameChanged += OnCategoryAdded;//监听共享数据服务事件

}  


/// 
    ///  共享数据服务.
    ///  如果跨线程修改数据(异步,多线程),需通过 
    ///  Execute.OnUIThread(() => SharedValue = "新值");
    ///  
    /// 
public  class SharedDataService: PropertyChangedBase
{
    private string _CategoryName;
    public string CategoryName
    {
        get { return _CategoryName; }
        set { SetAndNotify(ref _CategoryName, value);
            CategoryNameChanged?.Invoke(value); // 触发事件 

        }
    }

    /// 
    ///  分类名称发生变化事件.
    /// 
    public event Action CategoryNameChanged;




子窗口代码

 public partial class AddCategoryViewModel : Screen
 {
     private readonly SharedDataService _sharedService;
     public AddCategoryViewModel() { }


     // 通过构造函数注入 
     public AddCategoryViewModel(SharedDataService sharedService)
     {
         _sharedService = sharedService;
     }

     private string _categoryName;
     public string CategoryName
     {
         get => _categoryName;
         set => SetAndNotify(ref _categoryName, value);
     }

     // 使用 Stylet 的 RelayCommand 替代 System.Windows.Input 
     public RelayCommand WinClosedCommand => new RelayCommand((o) =>
     {
         // 更新共享数据 
         _sharedService.CategoryName = CategoryName;
        
         ((HC.PopupWindow)o).Close();

          关闭窗口(Stylet 标准方式)
         //this.RequestClose(true);
     });
 }


    
    
       
       
            


                
                

            



        


    

你可能感兴趣的:(WPF,wpf)