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

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

1.2 需要注册服务

//RootViewModel是主窗口

cs 复制代码
public class Bootstrapper : Bootstrapper<RootViewModel>
 {
     /// <summary>
     ///     配置IoC容器。为数据共享创建服务
     /// </summary>
     /// <param name="builder"></param>
     protected override void ConfigureIoC(IStyletIoCBuilder builder)
     {
         builder.Bind<SharedDataService>().ToSelf().InSingletonScope();
         builder.Bind<AddCategoryViewModel>().ToSelf();
     }

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

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

cs 复制代码
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 :
<Button 
        Content="&#xe650;"
       Command="{s:Action OpenWindowAction}"
        FontFamily="{StaticResource IconFont}"
        FontSize="20"
        Foreground="{DynamicResource TextIconBrush}"
        Style="{StaticResource ButtonCustom}" />

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

cs 复制代码
 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;//监听共享数据服务事件

}  


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

        }
    }

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

子窗口代码

cs 复制代码
 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);
     });
 }
XML 复制代码
<hc:Window x:Class="ProgramNotes.Views.AddCategoryView"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:hc="https://handyorg.github.io/handycontrol"
                xmlns:local="clr-namespace:ProgramNotes.Views"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                xmlns:vm="clr-namespace:ProgramNotes.ViewModels"
                xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
                 xmlns:s="https://github.com/canton7/Stylet"
                
                Width="300"
                Height="50"
                d:DataContext="{d:DesignInstance Type=vm:AddCategoryViewModel}"
                AllowsTransparency="True"
                ShowInTaskbar="False"
                ShowTitle="False"
                BorderThickness="1"
                Background="{StaticResource WindowBrush}" 
                WindowStartupLocation="CenterScreen"
                WindowStyle=" None"
                mc:Ignorable="d">
    
    <Grid Margin="8">
       
       
            <hc:SimplePanel >


                <TextBlock Margin="0"
                           HorizontalAlignment="Left"
                           VerticalAlignment="Center"
                           Text="新的类别名称 " />
                <TextBox 
                    HorizontalAlignment="Stretch"
                         Height="28"
                    Text="{Binding CategoryName, Mode=TwoWay}"
                         Margin="75,0 50 0"
                     />

            </hc:SimplePanel>



        <Button Grid.Row="0"
                Grid.Column="1"
                Margin="0"
               
                Style="{StaticResource ButtonPrimary}"
                Command="{Binding WinClosedCommand }"
                CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type hc:Window}}}"
                HorizontalAlignment="Right"
                VerticalAlignment="Center"
                Height="26"
              
                Content="确定" 
              
                    >
           
        </Button>


    </Grid>
</hc:Window>
相关推荐
baivfhpwxf20231 小时前
wpf ScaleTransform
wpf
wqq10272 小时前
WPF 图标原地旋转
wpf
续亮~2 小时前
基于Redis实现RAG架构的技术解析与实践指南
java·redis·架构·wpf·springai·文档检索
Pasregret18 小时前
09-RocketMQ 深度解析:从原理到实战,构建可靠消息驱动微服务
微服务·wpf·rocketmq
沉到海底去吧Go20 小时前
【图片识别分类】如何快速识别照片中的水印文字,对图片进行关键字分类,快速整理水印相机拍摄图片,基于WPF和腾讯OCR的技术实现
数码相机·ocr·wpf
界面开发小八哥20 小时前
界面控件DevExpress WPF v25.1新功能预览 - 文档处理类功能升级
c#·wpf·界面控件·devexpress·ui开发
He BianGu20 小时前
【WPF-VisionMaster源代码】应用OpenCVSharp仿Vision Master页面开发的软件源代码
图像处理·opencv·c#·wpf·机器视觉·visionmaster·视频处理
User:你的影子20 小时前
WPF 点击按钮,显示隐藏另一个控件
wpf
猫霸4 天前
WPF静态资源StaticResource和动态资源DynamicResource有什么区别,x:Static又是什么意思?
分布式·c#·.net·wpf