Why is my control not accessible in codebehind?

懵懂的女人 提交于 2019-12-12 18:28:23

问题


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 ?


回答1:


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.

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;

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




回答2:


You need to be sure that you are not accessing the control in a static method.




回答3:


I have another experience with the same Problem.

When I tried accessing the element from code behind, there was no intellisense showing it and I wasn't able to use methods with it. So I tried to debug the project and I found that there was a problem that was logical and was not a syntax error so it was not showing in XAML code or anywhere. I fixed it and then I was able to access it from code behind. Make sure the elements you are trying to access is correctly defined and has properties that are logically correct.

<ComboBox x:Name="_days" Selected="0"  Width="50"/> 

this was the code and Selected property was logically incorrect cause there was no element in combobox and you cant select 0th element.



来源:https://stackoverflow.com/questions/12231743/why-is-my-control-not-accessible-in-codebehind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!