Cannot see named Silverlight control in code - silverlight

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

Related

Catel and DevExpress DockLayoutManager don't work together

I use Catel and DevExpress DockLayoutManager in my application. I wanted to use this code to automatically create a View Model:
http://gyazo.com/147dff382d16e08cee0270ac20c6b330
http://gyazo.com/24a4ec62e90d49b4e08e3ba1d1790b59
but I can not run the application after compilation.
If we replace catel:UserControl on UserControl then everything works fine:
http://gyazo.com/b69a0257d992bb13c19813c055d47d92
, but goes without is not created ViewModel.
I wanted to use IUserControl but it has not helped. UserControlLogic does not perceive DocumentPanel as UserControl:
http://gyazo.com/e5596231404c054e459db06446ab57ee.
The reason for this is that DocumentPanelEx (and thus DocumentPanel) does not derive from UserControl. I will investigate if the base class being used can be turned into ContentControl instead of UserControl (but then the question is: from which class does DocumentPanel derive?). If you want us to investigate, please add an issue to the backlog at http://www.catelproject.com/support/issue-tracker/
For now you should put a UserControl as root into the DocumentPanelEx. I know it's not the ideal situation, but it will solve your problems for now.
I've reviewed your project from ticket Catel and DevExpress DockLayoutManager don't work together and it seems that the issue is caused by the Catel UserControl. On startup it tries to recursively find the InfoBarMessageControl in the visual and logical trees. If there is no such control and the visual tree is large, this operation may take a long time. I suggest you wrap the DockLayoutManager in the InfoBarMessageControl, this should resolve the issue.

Why does my WPF view not work without code-behind when applied through a DataTemplate?

I'm working on a large WPF project using MVVM. We're currently still deciding the extent to which we'll use code-behind, but so far we've gotten along fine with none at all (except for InitializeComponent on windows). However, I recently started using typed DataTemplates to apply views to my view models, and it seems these views, like windows, do not work without the InitializeComponent call, when, according to this article, I thought they would. The DataTemplate just declares a view. When I delete the view's code-behind file, the view model renders completely blank. When I leave it in, it's fine. Any ideas why I might be seeing this behavior?
First, you may be overlooking something important: I used that article heavily when learning MVVM/WPF as well, and I never thought it suggested eliminating InitializeComponent calls from the View.cs.
In fact, doing a quick search reveals the following (under Relaying Command Logic) [emphasis mine]:
Every view in the app has an empty
codebehind file, except for the
standard boilerplate code that calls
InitializeComponent in the class's
constructor.
I've been applying the same pattern you describe while leaving the default code-behind for each view in place, and so far it's smooth sailing. :)
Further: If you check out the definition for the default InitializeComponent(), you'll see that the generated code contains the following statement:
System.Windows.Application.LoadComponent(this, resourceLocater);
I haven't tested to make sure this is the case, but I'll wager a fiddle of gold against your soul that preventing that line from executing is going to affect the rendering of your view... ;)
According to djacobson, even the solution by Josh Smith that I referenced in my question cannot render its views without the code-behind, so the line stating this can be done is misleading. It seems the only way to avoid code-behind for your views is by not putting them into UserControls at all, but just keeping the XAML directly within a < DataTemplate > tag.

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.

WPF custom control XAML null error

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.

Resources