使用隐藏代码访问来自 XAML 的变量和来自 ViewModel 的对象 [英] Accessing variables from XAML and object from ViewModel using Code Behind

查看:60
本文介绍了使用隐藏代码访问来自 XAML 的变量和来自 ViewModel 的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Windows 手机开发的新手.我想问一下是否有可能做到这种情况.我需要使用我后面的代码访问 XAML 中的变量,然后我将它作为一个项目添加到我在视图模型中找到的现有列表中.因此,我需要访问我的视图模型以获取列表和 XAML 以从资源中获取变量.

这可行吗?如果是,我该如何访问它.这就是我当前 XAML 中的内容.

<system:String x:Key="scanName">SCAN</system:String></phone:PhoneApplicationPage.Resources>

非常感谢,

解决方案

你试图做的事情严重违反了 MVVM 的所有内容,但它是可能的...

使用视图代码隐藏中的以下几行,您可以...

...访问资源字符串:

var scanName = this.Resources["scanName"];

...访问视图模型:

var vm = DataContext as MyViewModel;if (vm == null) 返回;vm.ScanHistory.Add(scanName);

话虽如此,你真的不应该这样做.MVVM 的思想是将 ViewModel 和 View 完全解耦,让 WPF 绑定机制为您将它们连接在一起.在您的情况下,据我所知,您应该将扫描名称存储在其他地方,作为资源或配置值,在您的 ViewModel 中获取它并在您的 ViewModel 上提供您的 View 可以绑定到的属性.

I'm a newbie in windows phone development. I would like to ask if it is possible to do this scenario. I need to access a variable in XAML using my code behind, then I will add it as an item to my existing list found in my View Model. Therefore, I need to access both of my View Model to get the list and the XAML to get the variable from the resources.

Is this doable? If yes, how can I access it. This is what I have in my current XAML.

<phone:PhoneApplicationPage.Resources>
  <system:String x:Key="scanName">SCAN</system:String>
</phone:PhoneApplicationPage.Resources>

Thanks much,

解决方案

What you're trying to do is a pretty big violation of everything MVVM is about, but it is possible...

With the following lines in the codebehind of your view, you can...

...access the resource string:

var scanName = this.Resources["scanName"];

...access the ViewModel:

var vm = DataContext as MyViewModel;
if (vm == null) return;
vm.ScanHistory.Add(scanName);

That being said, you really shouldn't do this. The idea of MVVM is to decouple ViewModel and View completely and let the WPF binding mechanisms wire it together for you. In your case, as far as I can tell, you should store the scan name somewhere else, either as a resource or a config value, fetch it in your ViewModel and provide a property on your ViewModel to which your View can bind.

这篇关于使用隐藏代码访问来自 XAML 的变量和来自 ViewModel 的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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