当 View 被渲染/实例化时通知 ViewModel [英] Notify ViewModel when View is rendered/instantiated

查看:50
本文介绍了当 View 被渲染/实例化时通知 ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义用户控件 (ChartControl),我在 WPF 应用程序 (MainApp) 中使用它,并且呈现如下:

I have a custom usercontrol (ChartControl) that I use within my WPF app (MainApp) and which I render as follows:

<ContentControl Grid.Row="1" Content="{Binding ChartControl, Mode=OneWay}" />

启动 MainApp 后,以下内容按给定顺序执行:

Upon starting MainApp the following are executed in the given order:

主应用视图主应用视图模型图表控件视图模型图表控件视图

MainApp View MainApp ViewModel ChartControl ViewModel ChartControl View

我从我的 MainApp ViewModel 的构造函数中实例化 ChartControl ViewModel.问题是在实例化 ChartControl ViewModel 之后,我还需要从 MainApp 中调用 ChartControl 的方法.

I instantiate the ChartControl ViewModel from within the constructor of my MainApp ViewModel. The problem is that after instantiating the ChartControl ViewModel I also need to call a method of ChartControl from within MainApp.

我遇到的问题是,在调用该方法作为其视图模型的一部分之前,我需要渲染 ChartControl 视图(执行其 InitializeComponent).

The problem I am having is that I need the ChartControl view to be rendered (have its InitializeComponent executed) before I call the method as part of its viewmodel.

我认为一种解决方案可能是在完全实例化和设置时从视图通知视图模型.这是一个可行的解决方案吗?如果是,我该怎么做?

I thought one solution could be to notify the view model from the view when it is fully instantiated and set up. Is that a viable solution and if yes how would I do that?

总而言之,在调用匹配视图模型的方法之前,我需要完全设置视图.我遇到的问题是,在这种情况下,视图模型首先被实例化,然后才呈现视图.

In summary, I need the view to be fully set up before invoking a method of the matching viewmodel. The problem I am having is that in this case the view model is instantiated first and only then is the view rendered.

有什么想法吗?

谢谢

推荐答案

您可以利用交互触发器在任何 UI 事件上触发 VM 上的命令

You can make use of Interactivity triggers to fire Command on your VM on any UI event

您可以像下面一样监听 UserControl 的 Loaded 事件并将其绑定到您的 VM 上的 Command:

You can listen to Loaded event of UserControl like below and bind it to Command on your VM:

<UserControl x:Class="Test.TestView.MyUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        x:Name="myControl" >

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding ElementName=myControl, Path=OnLoadedCommand}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

并且确保您的 VM 中具有 Command

And sure you will have Command in your VM as

public ICommand OnLoadedCommand { get; private set; }

public MyUserControl()
{
    OnLoadedCommand = new DelegateCommand(OnLoaded);
}

public void OnLoaded()
{
}

这篇关于当 View 被渲染/实例化时通知 ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆