ViewModel中的数据未从PageLoad事件

如何解决ViewModel中的数据未从PageLoad事件

我是MVVM架构的新手。我正在构建一个UWP应用。我基本上有一个View(XAML),后面的代码(Xaml.cs),ViewModel和数据服务。

我的View / XAML看起来像这样:

<Page
    x:Class="SnapBilling.SyncModule.SyncView"
    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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls" 
    mc:Ignorable="d" Loaded="Page_Loaded"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
    
    <Grid>
        <Grid.Resources>
            <!--DataTemplate for Published Date column defined in Grid.Resources.  PublishDate is a property on the ItemsSource of type DateTime -->
            <DataTemplate x:Key="ProgressTemplate" >
                <ProgressBar x:Name="progressBar1" Value="{Binding Value.ProgressPercentage}" Maximum="100" Margin="20"/>
            </DataTemplate>
            
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition Height="4*" />
            <RowDefinition Height="2*" />
        </Grid.RowDefinitions>
        <controls:DataGrid x:Name="BackupSummaryDataGrid" 
                            Grid.Row="0"
                            Margin="40"
                            ItemsSource="{x:Bind DataContext.UploadProgressInfoDict}"
                            HorizontalAlignment="Stretch"
                            VerticalAlignment="Stretch"
                            AlternatingRowBackground="Transparent"
                            AreRowDetailsFrozen="False"
                            AreRowGroupHeadersFrozen="True"
                            AutoGenerateColumns="False"
                            CanUserReorderColumns="True"
                            CanUserResizeColumns="True"
                            ColumnHeaderHeight="32"
                            FrozenColumnCount="0"
                            GridLinesVisibility="None"
                            HeadersVisibility="Column"
                            HorizontalScrollBarVisibility="Visible"
                            IsReadOnly="False"
                            MaxColumnWidth="400"
                            RowDetailsVisibilityMode="Collapsed"
                            RowGroupHeaderPropertyNameAlternative="Range"
                            SelectionMode="Extended"
                            VerticalScrollBarVisibility="Visible"
                            >

            <controls:DataGrid.Columns>
                <controls:DataGridTextColumn Tag="SyncType" Header="Sync Type" Binding="{Binding Key}" IsReadOnly="True"  />
                <controls:DataGridTextColumn Tag="remaining" Header="Pending Items" Binding="{Binding Value.remainingNow}" IsReadOnly="True"  />
                <controls:DataGridTemplateColumn Header="% remaining" CellTemplate="{StaticResource ProgressTemplate}" />
                <controls:DataGridTextColumn Header="Status" Binding="{Binding Value.ProgressMessage}" IsReadOnly="True"/>

            </controls:DataGrid.Columns>
            
        </controls:DataGrid>
    </Grid>
</Page>

现在,当页面/视图xaml加载时,它将调用xaml类的构造函数,在此我们初始化组件并使用视图模型对象设置数据上下文。这是类的代码,

public sealed partial class SyncView : Page,IView
{
    public SyncView()
    {
        this.InitializeComponent();
        DataContext = new SyncViewModel(ServiceLocator.Current.GetService<ICommonServices>());
    }
    
    private void Page_Loaded(object sender,RoutedEventArgs e)
    {
    
    }
}

现在,DataContext = new SyncViewModel(ServiceLocator.Current.GetService<ICommonServices>());在这里创建了一个ViewModel对象,并将其正确绑定到数据上下文。

问题

当我通过Page_Loaded事件而不是像下面的构造函数那样设置数据上下文时,viewmodel对象未绑定到页面的数据上下文。

private void Page_Loaded(object sender,RoutedEventArgs e)
        {
        DataContext = new SyncViewModel(ServiceLocator.Current.GetService<ICommonServices>());

        }

如何解决这个问题?

解决方法

所以代码执行的顺序是

  1. 构造函数调用
  2. 查看元素创建
  3. 绑定
  4. 页面加载事件(仅在添加了所有子项时发生)

正在发生的事情是,当在绑定中出现DataContext时在构造函数中设置DataContext时不为空,但是在{{1}中设置DataContext时}绑定将在Page_Loaded为null的情况下发生,因此您在视图中看不到任何数据。

现在,如果可以的话,我建议您在绑定之前在构造函数中初始化View-model。但是,如果由于某种原因需要它绑定到DataContext事件中,则需要一种方法来告诉您视图在值更改时进行更新。

幸运的是,该框架已经有解决方案,您可以在ViewModel上使用Page_Loaded接口,以便可以通知视图有关属性值的更改,我猜想是INotifyPropertyChanged

但是您将必须编写一个事件处理程序,该事件处理程序将相应地更新您的视图
像这样的东西

Value.ProgressPercentage

这就是为什么我建议您改为使用数据绑定,这不是很复杂,但是它将为您节省几行额外的编码。

,

现在在后面的代码中:

public SyncView()
{
 this.Loaded += SyncView_Loaded;  
}
private void SyncView_Loaded(object sender,RoutedEventArgs e)
{
 this.InitializeComponent();
 DataContext = new SyncViewModel(ServiceLocator.Current.GetService<ICommonServices>());
}

在XAML中:

ItemsSource="{Binding UploadProgressInfoDict}"

原因:之前我创建了一个视图模型对象(例如VM),并将其保存在codebehind类的属性中,然后我使用该属性设置了datacontext。后来我将itemsource与该对象的UploadProgressInfoDict绑定在一起,例如

ItemsSource="{Binding VM.UploadProgressInfoDict}"

删除了这部分,效果很好!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-