如何知道我们何时完成DataContext?(How to know when we're done with a DataContext?)

编程入门 行业动态 更新时间:2024-10-19 16:25:03
如何知道我们何时完成DataContext?(How to know when we're done with a DataContext?)

我目前正在学习WPF和MVVM。

我有一个在我的XAML中使用创建的对话框

<Window.DataContext> <vm:PreferencesViewModel /> </Window.DataContext>

PreferencesViewModel()的构造函数调用我的PreferencesModel对象的LoadConfig()(加载XML文件)。 我想要做的是在单击对话框的“确定”按钮时从PreferencesViewModel调用PreferencesModel :: SaveConfig()但我不能,因为我无法访问由<vm:PreferencesViewModel />自动创建的PreferencesViewModel对象<vm:PreferencesViewModel /> 。 我会在析构函数中执行此操作,但GC不会销毁该对象。

有没有办法知道XAML何时完成了PreferencesViewModel对象?

I'm currently learning WPF and MVVM on my own.

I have a dialog box that is created in my XAML using

<Window.DataContext> <vm:PreferencesViewModel /> </Window.DataContext>

The constructor of PreferencesViewModel() calls the LoadConfig() of my PreferencesModel object (loads a XML file). What I would like to do is call PreferencesModel::SaveConfig() from the PreferencesViewModel when the "OK" button of my dialog box is clicked but I can't since the I don't have access to the PreferencesViewModel object automatically created by <vm:PreferencesViewModel />. I'd do it in the destructor but the GC won't destroy the object.

Is there a way to know when the XAML is done with the PreferencesViewModel object?

最满意答案

...但我不能,因为我无法访问PreferencesViewModel ...

给它一个名字并在codebehind中访问它。

<vm:PreferencesViewModel x:Name="MyVM" />

或者从代码后面的datacontext中提取它:

var myVM = (PreferencesViewModel) DataContext;

...but I can't since the I don't have access to the PreferencesViewModel...

Give it a name and access it in codebehind.

<vm:PreferencesViewModel x:Name="MyVM" />

Or extract it off of the datacontext in code behind:

var myVM = (PreferencesViewModel) DataContext;

更多推荐

PreferencesViewModel,XAML,对象,PreferencesModel,<vm,电脑培训,计算机培训,IT培训"/>

本文发布于:2023-08-06 18:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DataContext

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!