为什么在代码隐藏中无法访问我的控件? [英] Why is my control not accessible in codebehind?

查看:32
本文介绍了为什么在代码隐藏中无法访问我的控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 VS 2010 中创建 WPF 应用程序并在 Grid 中放置一个按钮时,我可以从 C# 代码访问该控件.我有与 XAML名称"字段同名的按钮类实例变量.但是当我使用VS 2012 RC创建WPF项目时,我看不到控件的实例.可能是什么问题?VS 2010 和 2012 之间是否有任何默认项目设置差异?

When I create a WPF application in VS 2010 and place a button in Grid I can access the control from C# code. I have the button class instance variable with the same name as in XAML "name" field. But I can't see the instance of the control when I create a WPF project using VS 2012 RC. What can be the problem ? Is there any default project settings difference between VS 2010 and 2012 ?

推荐答案

如果您在谈论代码隐藏,那么您应该能够访问按钮而无需再次声明它,只需使用它的 x:name 属性.现在,如果您正在谈论 MVVM,那么您应该在使用按钮之前设置您的数据上下文.

If you're talking about codebehind then you should be able to access to the button without declaring it again just by using it's x:name attribute. Now, if you're talking about MVVM, then you should set your datacontext before using the button.

当我使用 2012 (Release Candidate) 时,当我尝试访问在 xaml 中声明的元素时,我没有得到代码隐藏 cs 文件的智能感知(我必须在没有它的情况下编写代码),它甚至暗示没有元素名称但项目编译和工作.所以我建议你尝试在没有智能感知的情况下编写代码并编译它.

When I'm using 2012 (Release Candidate) I get no intellisense for the codebehind cs files when trying to access elements declared in the xaml (I have to wrote the code without it) and it even suggest there's no element by that name but project compiles and works. So I'll suggest you to try to write the code without intellisense and compile it.

YourButton.IsEnabled = false;

我猜这是 VS 2012 中的默认设置,以鼓励使用 MVVM,但这只是想法.

I guess this is by default in VS 2012 to encourage use of MVVM but that's no more than thoughts.

这篇关于为什么在代码隐藏中无法访问我的控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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