Custom Control and Visual Studio 2008 SP1 - winforms

I've created a custom control (a class that inherits from Control). When I put it on a Form I can work with it on Visual Studio IDE. It shows me an error and I don't see the form.
The error message is this: La variable 'ctrlImagen' no está declarada o no se asignó nunca.
It's a winform for a Compact Framework app.
How can I solve this? (it the class inherits from UserControl it works perfectly)

Sounds crazy, but Visual Studio is selectively executing code for your control in the designer. First thing to check is your constructors. Make sure you have an empty, default constructor, that is public, even if you never plan on using it. After that make sure any code you have tied to layout events (such as resize) are good to go, these are likely the culprits, as thats where I always find problems when my custom controls don't work in the designer.

It sounds like you have a bug in the code for your Control. This sounds like a runtime error that is preventing the control from rendering.
Re-read your code and look for potential null-pointer exceptions, unassigned variables, stack overflows, etc. The bug is lying in their somewhere.

Any chance your user control doesn't have a public default constructor? I can get a similar error "The variable 'userControlX' is either undeclared or was never assigned' if the constructor isn't public.
Would need more info, though.

It seems a design time exception has happened in initialization logic that gets executed before your form initialization logic executed. A good example would be a NullPointerException fired by the default constructor (or one or more methods it invokes) of a user control that contained by your form.

I put this on constructor to solve the problem:
this.ClientSize = new Size(21, 21);
The beging of my class is this:
public class ControlMapa : Control
{
public ControlMapa()
{
this.ClientSize = new Size(21, 21);
...
Thank you!

Related

How does the VS Wpf Designer instantiate and limit execution of VIewModel code?

The WPF designer has a tough job to do. In order to show you a life view of your screen or component it has to execute code but, since you do not control the designer, it has to do this without producing any side effects.
So how does it do that? What are the rules around execution?
What if the view's code-behind code does logging to a file or a service?
What if the code-behind calls MessageBox.Show?
What if the code-behind doesn't have an empty default constructor?
I've hit situations before where I had a default constructor that was checking GetIsInDesignMode and creating and assigning a DataContext if false, and still the designer wasn't rendering correctly. Is there some sort of stack-depth limit?
What are the limitations?
it has to do this without producing any side effects
No, the designer is not that smart. If IsDesignTimeCreatable is specified, it will execute all code in a public parameterless constructor and in properties accessed by bindings. Specifically, it will popup message boxes, write to files, etc -- or throw exceptions trying (just try it yourself).
If you don't have a public parameterless constructor, it can't create an instance, so no code will run.
Regarding your question about "stack depth limit", I know of no such limitation. If you have a specific case where it's not working, I suggest you ask a specific question about that case.
In most cases where the designer fails it is because of an exception or other non-data-related problems (such as missing design-time resources). You should definitely guard code you don't want called during design-time using DesignerProperties.GetIsInDesignMode (I usually add a property IsInDesignMode to the base view model).
This is not exactly answering your question, but to be honest 'how does it work' is not a very specific question.
However rather than dropping this check in to your code-behind, are you aware that you can add something like this to your Xaml?
d:DataContext="{Binding Source={d:DesignInstance Type=namespace:className, IsDesignTimeCreatable=True}}"
This means that you can make a design-time version of your class, e.g. CalculatorDesign :
ICalculator, reference that in the Xaml, and each time you change and compile the design-time class the view will update within VS without running any code or having complicated logic in code-behind.

WPF UserControl throws exception in design mode

I'm trying to create a custom control using UserControl. When I drop the custom control on a window, it displays for a second then the designer crashes and I get the messag:
An Exception was thrown
ArgumentNullException: Value cannot be null.
Parameter name: sp
The stack trace shows an error in a call the ServiceProvider constructor.
Any idea what's going on on here? I tried this with a blank UserControl on a blank Window and got the same error.
Thanks for your help.
XAML designer will call the UserControl's constructor when loading in designer.
If in the constructor or UserControl.Loaded is another Method that is not running in the design mode should be skip.
In order to avoid this you can place a if condition as follows in your UserControl constructor
if(DesignerProperties.GetIsInDesignMode(this))
return;
// another Method that Running in RunTime
WPF user control throws design-time exception
After further googling the issue, it seems that this is related to the presence of installshield projects in the solution. If I remove all installshield projects, I don't get the exception anymore.
This is more of a workaround than a solution though...

VS2010 Winform designer alterate decent code

I'm encountering a problem with the WinForm designer. I made a new UserControl, I added a DataGridView, some other elements and a TreeView. With the gui I named all those new components. Now it's time to code that stuff and I realise that the designer missnamed my node of my TreeView. The Designer also added new columns from my DataSource even if it was set to AutoGenerateColumn to false. I though: "Well time to clean some Designer crap again..." and I cleaned that stuff up in the InitializeComponent function (I know it's labeled "Do not modify with the code editor" but... do I have the choise?
Anyway, my problem is : When I go back on the Design view, the VS Designer seems to regenerate the code back but not even how it was. Now the designer declares my DataGridView and my TreeView as local members of InitializeComponent function. I can easily repair and undo my changes but I would like to understand and know if there is a way to disable the auto code generation of the designer.
Also, I tried to make another function which have all what I need so the designer don't screw it up and call it into the initialize component. This solution works at run time but not on Design view. I'm kinda low.
As far as I know, the short answer is no. If something is marked as Do not edit due to code generation., then do not edit it :). I would suggest reading up on partial classes, as that is how you can modify classes without actually messing with the auto generated code. In your case, you will need to go into the designer and fix everything there so that the auto generation works as you expect it to.

Adding a user control "The Enumerator is not valid"

I'm using Visual Studio 2010 to create a small WPF application. I've created a user control that I am now trying to add to my main form. The user control does show up in toolbox but every time I try to drag the control to the form I get the error:
The enumerator is not valid because the collection changed.
I should know what's wrong and it is bugging me that I can't figure it out.
You have a bug in the constructor of the usercontrol - you are using a foreach-loop over an IEnumerable and while the loop is running, the IEnumerable is changed, this is not allowed with a foreach loop. Use a for loop instead if you are manipulating the Collection you are iterating over.
The problem here is that you don't know what code is throwing the exception.
WPF is terrible about exceptions, especially in constructors. The framework insists on catching and re-throwing a new exception, usually multiple times, and it's difficult to find the original stack trace. I've found the easiest way to track down this kind of error is to tell Visual Studio to stop as soon as the exception is thrown, rather than waiting until WPF has re-thrown it a couple of times and made the details difficult to dig out.
I don't have Visual Studio 2010 in front of me, but here's how to do this in VS2008 -- 2010 is probably similar:
Go to the Debug menu > Exceptions...
Next to "Common Runtime Language Exceptions", check the box in the "Thrown" column
Then debug your app again. It will stop at the line that's actually causing the problem, and it'll be much easier for you to see what's going on. And if you're still not sure why it's throwing an exception, you'll be able to post a code sample.
In order for a user control to function properly you need to have a constructor that takes zero arguments. This way the form designer has a way to render the control in a "default" manner.
I then overloaded my constructor to take the arguments I needed to actually run the control properly and everything worked as expected.
You need to:
Remove the DLL reference
Add a reference to your control
Rebuild the solution
Add your control. It should work!

Cannot see named Silverlight control in code

In my first few hours with Silverlight 3, as an avid WPF user, I am greatly disappointed at the many things it doesn't support. This seems like an odd issue to me and it's so generic that I cannot find anything online about it.
I have the following XAML:
<controls:TabControl x:Name="workspacesTabControl" Grid.Row="1"
Background="AntiqueWhite" ItemsSource="{Binding Workspaces, ElementName=_root}"/>
However, I cannot see the workspacesTabControl in code-behind. I thought maybe IntelliSense is just being mean and tried to go ahead and compile it anyway, but got an error:
Error 1 The name 'workspacesTabControl' does not exist in the current context
How do I access controls in code-behind?
EDIT: I realized I've pasted the wrong error - I have two controls inside the UserControl called workspacesTabControl and menuStrip. I cannot get to either one of them by their name in the code-behind.
Just in case, here is the XAML for the menuStrip:
<controls:TreeView Grid.ColumnSpan="2" Height="100" x:Name="menuStrip"
ItemContainerStyle="{StaticResource MenuStripStyle}"
ItemsSource="{Binding Menu, ElementName=_root}"/>
EDIT AGAIN:
I'm not sure if this is helpful, but I've taken a look at the InitializeComponent() code and here's what I saw:
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/SapphireApplication;component/SapphireMain.xaml", System.UriKind.Relative));
}
It seems that it simply loads the XAML when it runs (not before or during compilation) so the menuStrip and workspacesTabControl names don't actually get registered anywhere (as they usually are in WPF/win Forms). Could that attribute be a problem? And where do I get rid of this requirement for all the future UserControls I make?
Check the properties in VS for the xaml file itself... make sure the Build Action is set to Page.
As ridiculous as it may sound, I have resorted to using FindName() method to access named items in code-behind:
this.FindName("workspacesTabControl") as TabControl
I realize that this is a ridiculous way but I am forced to use this for now. Please let me know if someone else has encountered this problem and have come up with a better solution!
When you first create a control, Visual Studio does not pick it up with intellisense. However, after you try to build the project, it should become availble. You can also just type the name in without intellisense and then build it. Haven't verified this, but I heard this was on the list of things to fix in SL4.
That being said, if you name a control inside of a datatemplate, that control is not directly accessible in code-behind. This is the same for WPF, though.
You should be able to see it in the codebehind, that part works the same as WPF, maybe if you fix the problem with the menuStrip, then visual studio will be able to build the xaml paty of the page and ull be able to access the tabcontrol
I've seen the same problem in my Silverlight development. Specific to my problem my named controls were nested inside other controls (i.e. a datagrid) and I was unable to access them in my code behind. Any named controls at the same nesting level or above the previously mentioned datagrid worked fine but anything inside it was lost into the abyss.
As already mentioned, it should just appear in Intellisense, however the fact that you're getting an error related to something else, i.e. "menuStrip" is probably interfering with Intellisense. Resolve that error and you'l probably find that you can access the "workspacesTabControl" control.
Are you possibly using some sample code or something where they've named a control "menuStrip" and you've renamed it?
Good luck
Check that you don't have any controls using the same class name as a namespace name. For example:
namespace Solution.ProjectName.workspacesTabControl
{
public class workspacesTabControl
{
...
}
}
This will also give you this error.
Good luck,
Mark

Resources