巧用 MVVM Toolkit的ObservableProperty,实现一个类绑定多个ViewModel

实现的本质,是在你使用的ViewModel中将另一个ViewMode当作一个ObservableProperty引入,如此这个引入的ViewModel即可在当前使用的ViewModel中使用了。

 

如下的管理员设置页面为ConfigView,其绑定的ViewModel为ConfigViewModel。

 

在开发中为了便于开发及后期的维护,个人将其中的用户信息管理(主要是账号密码)、WIFI管理、设备管理、CT管理分别用不同的ViewModel,最后将它们组合到CofigViewModel中。

 

 

如下为引入的CT管理的CTManagerViewModel ConfigViewModel中:

        [ObservableProperty]
        CTManagerViewModel ct = CTManagerViewModel.Instance;//获取CTManagerViewModel的单例

 

引入后在前端进行相应绑定时如下示例:

复制代码
 <StackPanel Orientation="Horizontal">
     <TextBlock Style="{StaticResource TBLeftStyle}" Text="本机配置" />
     <TextBlock
         Margin="106,0,40,0"
         Style="{StaticResource TBLeftStyle}"
         Text="IP地址" />
     <TextBox
         Width="318"
         Height="68"
         Style="{StaticResource DefaultTextBoxStyle1}"
         Text="{Binding Ct.LocalTerminalIP,Mode=TwoWay}" />
     <TextBlock
         Margin="106,0,38,0"
         Style="{StaticResource TBLeftStyle}"
         Text="端口" />
     <TextBox
         Width="318"
         Height="68"
         Style="{StaticResource DefaultTextBoxStyle1}"
         Text="{Binding Ct.LocalTerminalPort,Mode=TwoWay}" />
     <TextBlock
         Margin="102,0,48,0"
         Style="{StaticResource TBLeftStyle}"
         Text="AE Title" />
     <TextBox
         Width="318"
         Height="68"
         Style="{StaticResource DefaultTextBoxStyle1}"
         Text="{Binding Ct.LocalTerminalAETitle,Mode=TwoWay}" />

 </StackPanel>
复制代码

上述代码中将绑定的mode都设置为了TwoWay,以便于UI更新CTManagerViewModel 中的相应属性。

 

posted @   盛沧海  阅读(1180)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示