WPF custom control XAML null error - wpf

Yet another strange WPF error:
I have a custom control in a simple XAML page. The project builds and runs perfectly, with no errors.
Here's the XAML:
<Window x:Class="Grapher2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:graph="clr-namespace:Grapher2"
Title="Grapher" Width="800" Height="600">
<StackPanel Name="container" Width="700" Height="500">
<graph:GraphCanvas x:Name="graphCanvas" Width="700" Height="500" Background="#ddd" />
</StackPanel>
But when I try to view the XAML page in the XAML designer window, I get the message:
"Problem Loading--The document contains errors that must be fixed..."
When I hit the "Reload the designer" link, an error pops up in the Error List which says:
"Object reference not set to an instance of an object"
and the line starting with "graph:GraphCanvas..." is underlined.
I was originally developing on our development server, and there, everything was the same, except the error was:
"Request for the permission of type 'System.Security.Permissions.SecurityPermission (...blah blah... failed.)"
Again, everything works perfectly, except that I can't view the page in the XAML designer window, which is keeping me from developing the rest of the app.
I've tried cleaning, building, rebuilding, and all combinations of orders of these commands, with no success.
EDIT:
Please bear in mind this is my first custom control, and I could be doing something horribly, horribly wrong. Like I said, the app compiles and works beautifully, so I'm kinda mystified.
EDIT #2:
My derived canvas is not a partial class. From my understanding of how InitializeComponent works (What does InitializeComponent() do, and how does it work in WPF?), there is no auto-generated partial class that contains InitializeComponent linked to my control. Again, the control works perfectly without it, except for breaking the XAML design view.

I had a similar issue recently. Basically my understanding is that in designer some things happens in not exactly the same order as during run-time and some things that you would think could never be null actually are null during design-time.
I solved the problem this way: commented large parts of code in my control to the point there was no error in Cider and then uncommented them until I got the error again. Then when source of the error was localized, I surrounded problematic parts with
if (something != null)
{
...
}
Even when I felt that there's no way that could be null. And after some time I got rid of the error.
Not very "scientific" approach but it solved my problem. :)

Unfortunately, there are problems with the Cider designer in Visual Studio 2008 where this type of error is all too common. The version in VS2010 is vastly improved, but that's no comfort when you hit this issue in VS2008.

I'm not sure what "Grapher2" is but you might check to make sure that there isn't code in its constructor that can't run correctly when the designer instantiates it. Something like a database call would be problematic.

I've seen similar issues.
This is only a partial solution as it won't render in the parent in design mode, but it'll get rid of the error. It's the best solution I've been able to find so far.
In the Constructor of your custom control.
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
InitializeComponent();
Hope that helps, or maybe it'll help you find a better solution. If you do please post it so I can use it ;)
Edit
I get a different error when not using the code above:
Could not create an instance of type ''
So may be a different issue then what I've seen, but sounds like it might be related.

Related

App runs normally but has "errors" during design time: "does not exist in namespace" and "an error occured when finding the resource dictionary"

My application has certain errors, in its error box during design time, to do with it's resource dictionary. For example, in my Main Window a resource dictionary is called as follows;
<Window.Resources>
<ResourceDictionary Source="Resources.xaml"/>
</Window.Resources>
I get a blueline on the middle line saying "An error has occurred while finding the resource dictionary "Resources.xaml". Yet, the Resources.xaml is in the root folder of the project, and so is the MainWindow.
I am aware that there are similar questions like this out there, however the answers;
"Make sure Resources.xaml is set to build action: page"
"Make sure you are correctly referencing Resources.xaml"
were not helpful to me.
I have an additional problem in that, within the resource dictionary, I have errors telling me;
the name ProductDatabaseViewModel does not exist in the namespace "clr-namespace:gate2software.ViewModels"
and similarly;
the name ProductDatabaseView does not exist in the namespace "clr-namespace:gate2software.Views"
in the following xaml;
<DataTemplate DataType="{x:Type vm:ProductDatabaseViewModel}">
<vw:ProductDatabaseView />
</DataTemplate>
In reality both of these are available exactly where they are stated to be.
Any suggestions for either of my two problems would be greatly appreciated.
make sure your path is correct? or try like dis path:
<ResourceDictionary Source=ms-appx:///CustomControls/Resources.xaml>
Have you tried to close the designer process (sometimes this works)?
Task Manager > Details > XDesProc.exe > end process. You will be able to reload it by clicking refresh in any VS view, but first rebuild all.
And by the way, Resources.xaml is for sure a ResourceDictionary type and not Page ? This kind of errors are shown also when you try to add a page as resource, not a ResourceDictionary.
I just ran into this same issue. My projects were targeted for a x64 build. I changed them to Any CPU See below and was able to see my view model data at design time.

Very strange bug when using data binding to element under a Telerik RadTreeView

I have the following XAML code as part of a custom control:
<telerik:RadTreeView x:Name="treeModules">
<telerik:RadTreeView.ItemTemplate>
<core:HierarchicalDataTemplate ItemsSource="{Binding Submodules}">
<local:ModuleInfoUserControl IsReadOnly="{Binding ElementName=ctrlIsReadOnly, Path=IsReadOnly}"/>
</core:HierarchicalDataTemplate>
</telerik:RadTreeView.ItemTemplate>
</telerik:RadTreeView>
Where:
The ItemsSource property of
treeModules is set by code to a list
of Module objects. The Module class
has a property named Submodules,
which consists on a collection of
more Modules.
ModuleInfoUserControl is a custom
control used to display module
information. IsReadOnly is a
dependency property declared on the
control.
ctrlIsReadOnly is a hidden TextBox
defined elsewhere in the main user
control. It is used to make a bunch
of controls editable or read only.
The problem: binding to ctrlIsReadOnly element in ModuleInfoUserControl does not work. The IsReadOnly property of it is always at its default state, even if the corresponding property of crlIsReadOnly changes.
But, if I change the RadTreeView into a standard Silverlight TreeView, and the HierarchicalDataTemplate into the standard Silverlight version too, it works as expected.
Ok, up to here I have pasted an exact copy of the support ticket I have sent to Telerik in the hope that they could help me. I must say that the reply has been quick and as efficient as it could be: they have said me that they could not reproduce the bug, and have send me a small test project that exercises the offending piece of code. The test project shows the bug on my machine, but works on Telerik's.
And here comes the really strange part. I have published Telerik's sample project on my personal site. Here is the link:
http://www.konamiman.com/TelerikTest/TestPage.html
The idea is that when pressing the "ToggleIsReadOnly" button, the "Root" TextBox should become read-only. But again, it works on Telerik's machines, but not on mine! So the application code itself is apparenly ok.
Thinking that it could be a problem on my machine's Silverlight runtime, I have tested a bunch of others, including: Spanish Windows 7 32 and 64 bits, Spanish Windows XP, English Windows Server 2008, and even on my wife's computer with Japanese Windows XP. On all of these, it does NOT work as expected.
So, what's happening here? I am completely stuck.
By the way, Silverlight Runtime I'm using is version 3.0.50106.0.
UPDATE: I have uploaded the source code of the test project as well. Here is the URL:
http://www.konamiman.com/TelerikTest/TreeViewTest.zip
I have tried the test project now, and I can not get it to work. I have tried changing the thread culture to "en-US", but that does not help. It would appear that items controls a HierarchicalDataTemplate cannot bind to properties on elements outside of that datatemplate. I think you should get back to Telerik and ask them again if they are 100% sure that this works as expected on their machines. If it does, it is a very strange bug.
[EDIT]
I have found some more info, see the links below. It looks like this is a general silverlight problem. But it is still strange that the Telerik guy claims that it works on his machine.
http://forums.silverlight.net/forums/p/108804/267789.aspx
And here is a similar thing but with the Telerik GridView component:
http://www.telerik.com/community/forums/silverlight/gridview/elementname-binding-inside-of-celltemplate.aspx
I have found an alternative approach that seems to work fine. Instead of defining ctrlIsReadOnly as part of the main user control tree, I define it as a static resource:
<UserControl.Resources>
<TextBox x:Key="ctrlIsReadOnly" IsEnabled="True" IsReadOnly="False" Visibility="Collapsed" />
</UserControl.Resources>
Then I just have to slightly change the binding declaration on ModuleInfoUserControl:
<local:ModuleInfoUserControl IsReadOnly="{Binding Source={StaticResource ctrlIsReadOnly}, Path=IsReadOnly}"/>
I then access ctrlIsReadOnly from code this way: ((TextBox)this.Resources["ctrlIsReadOnly"])

XAML Designer "cannot find type" when converters are in UserControl.Resources

I have a WPF UserControl with binding converters referenced like this:
<UserControl x:Class="MyControl" x:Name="MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TheMainNamespaceOfThisAssembly">
<UserControl.Resources>
<local:ConfidenceColorConverter x:Key="ConfidenceColorConverter"/>
</UserControl.Resources>
I then use the binding converter later. I see the user control in my design window. Then I compile, then place this user control in my main window. I run it and it works. However, I still would like to use the designer on the main window, which breaks with:
Could not create an instance of type 'MyControl'.
So I learned how to debug the designer; when I do, I get an XamlParseException:
Cannot find type 'TheMainNamespaceOfThisAssembly.ConfidenceColorConverter'. The assembly used when compiling might be different than that used when loading and the type is missing. Error in markup file...
If remove the references to the converters, my user control displays well in the designer on the main window. Any ideas how to fix my references to the converters so that they won't break the designer?
Couldn't understand if the article Troubleshooting WPF Designer Load Failures applies or not.
Could you please try to reproduce the problem on a clean new project rather than editing your existing one? You cannot have
<UserControl x:Class="MyControl" x:Name="MyControl"...
as you would need to add a namespace to "x:class" and change "x:Name" value to be different from class name. The designer works fine when I create a clean project as you describe and fix this sort of errors. You might be omitting some details from the question you think are unimportant, but those details can make all the difference.
After talking with others, the VS2008 designer has numerous problems that prevent its use in many situations. We gave up.
Update: It seems like some, especially Joel Cochran, are using the Expression Blend design view with more success, as long as you obey his four principles of MVVM in XAML development.

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

Why would my XAML editor be giving me an error but the project compiles and runs fine?

I've implemented the Attached Behavior Command pattern which compiles and runs fine, but strangely my XAML editor is giving the error:
The attachable property 'Behaviors'
was not found in type
'CommandBehaviorCollection'.
in this XAML:
<c:CommandBehaviorCollection.Behaviors>
<c:BehaviorBinding Event="MouseLeftButtonDown"
Command="{Binding PressedLeftButton}"
CommandParameter="MainBorder123"/>
<c:BehaviorBinding Event="MouseRightButtonDown"
Command="{Binding PressedRightButton}"
CommandParameter="MainBorder123"/>
</c:CommandBehaviorCollection.Behaviors>
However, I can compile and run it fine.
I've rebuilt the project, the solution, closed and opened it, but the XAML editor still gives me this error.
Has anyone experienced an incongruity between XAML editor and compiler like this before? Any idea how to make the XAML editor see that there really isn't a problem?
Yes. I normally turn the XAML Editor off and use the XML Editor instead. It's faster and doesn't throw these red herring "errors" at you. I haven't had a chance to try it yet, but hopefully VS2010 does a much better job in this area.

Resources