Why can a WPF/Silerlight XAML file parse without the default namespace? - silverlight

I read that "the default namespace is important because otherwise the XAML parser will not recognize the elements".
However, just as a test, I take it out and, although the visual designer cannot recognize the element names anymore, this Silverlight XAML runs just fine:
<UserControl x:Class="Second12.Page"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="This is a test."/>
</Grid>
</UserControl>
Why is that?

I would look at it being reasonable for the Silverlight parser to fall back to the WPF silverlight parsing by default.
you would get errors if you used wf xaml or even WPF xaml not supported by Silverlight parser.
I would look at the importance of having the namespace going forward though.
XAML is a language supported currently by WPF, Silverlight which uses a subset of WPF, and WF and a little bit in WCF. each of those have their own Parsers right now.
With .net 4.0 there will be system.xaml.dll or something to that effect. The namespace will mean quite a bit more as it will direct the parser further. WPF, WF, and WCF will all be using that parser, and would guess that silverlight in the future will use it.
edit, primarily the top level namespaces are used to provide intellisense schema in the way that parser is written for each group.

Perhaps the sentence ought to have read "should not recognize". Its seems a reasonable fallback position for the XAML parser to assume the no-name namespace contiains XAML elements in the absence of a default namespace definition.

Related

Can you view XAML as "regular" .net code (c#\vb.net)?

There are times when I find some example XAML that I want\need to do in code (c#\vb.net).
I assume at some point the XAML becomes code, or at least IL.
So my questions:
Am I correct in assuming that XAML is converted to IL? (or if not IL what does it become?)
If the above is correct, when does XAML become IL (or whatever it becomes)?
Is there some way to see the XAML in as "code"
Thanks.
No, XAML does not compile into IL, that gets done at runtime. The best way to think about it is as a way to compose an application from components.
For the majority of things you can replicate in C# what you do in XAML, however there is a small number of things that is available in XAML that's not in C# and vice versa. Charles Petzold at some point said that ostensibly, XAML looks like XML, but it's actually not, it's a language of its own.
For example this XAML code:
<Grid>
<TextBlock Text="Something" />
</Grid>
Is equivalent to the following C# code. This will get done in C# at runtime and short of setting a breakpoint in a particular component's constructor, there isn't much you can do to figure out what executes at runtime.
var grid = new Grid();
grid.Children.Add(new TextBlock{Text = "Something"});
I am sure there is a solution to your problem, but not as an answer to this particular question. Can you give more details on your problem and we can help you understanding it.
WPF and Silverlight treat XAML differently; neither convert XAML to IL. WPF's markup compiler converts XAML to a compiled form called BAML that is a binary version of the XAML. Silverlight leaves the XAML as plain text (compressd in the .XAP) and parses it at runtime.
Is there some way to see the XAML in
as "code"
If you are talking about the hierarchy of controls in xaml, then you may use myControl.Parent.
You can "see in code" how the controls in xaml are nested. You will also get/set their properties.

Making a DataTemplate blendable

How can I make a Datatemplate for a ViewModel blendable (designable in expression blend). When I go to resources and try to edit the DataTemplate directly all I see on the Drawingborad is a blank rectangle. This is because the DataTemplate is not bound to anything. Of course I can create a UserControl and create some designtime data in code there to see the template but I now would have to switch back and forth between the resource (to edit) and the usercontrol (to see the result of my edit). Isn't there a more direct way to edit and see my DataTemplate?
It's a bit of a stretch to use, but Blend has a feature called "Design-Time Data" that can help you out. It's tough to get started at first, but once you do a few it's pretty easy. It kind of forces you into a nice pattern for DataContext as well.
Here's a good link on the subject: http://www.robfe.com/2009/08/design-time-data-in-expression-blend-3/
Here's a few choice excerpts:
On Design-Time Sizes
...design time properties can be
safely ignored by other tools and they
are ignored at the runtime
(mc:Ignorable specifies that the
namespace with the "d" prefix can be
ignored).
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Expression Blend uses two design time
properties (d:DesignWidth,
d:DesignHeight) to specify a size for
a control to be used at design time...
On Design-Time Data Sources
I stumbled across d:Datacontext when I
was playing with Blend 3 and tried
adding a “live datasource” to my
window. I thought it was going to
behave just like the old way of
setting a DataContext, but when I ran
my application, there was no data! ...
So the upshot is, now we can write
code like this:
...
<Grid ...
DataContext="{StaticResource GameDataSource}"
d:DataContext="{StaticResource DesignTime_DateDataSource}">
Note that this is for Blend 3 if you want first-party support for these features. They are pretty good - there's even a designer for the design-time data, though I've not looked into those features yet.
Applying To DataTemplates
This is something I sorta made up, but it seems to work. Here I'm using the Design-Time data feature to pull data into the visual element's d:DataContext. You'd have to do this for every top-level element that needed a DataContext set.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<!-- Resource dictionary entries should be defined here. -->
<DataTemplate x:Key="MyTemplate">
<TextBlock Text="{Binding Text}" d:DataContext="{StaticResource SampleDataSource}" />
</DataTemplate>
</ResourceDictionary>
The binding syntax is a little bit more explicit if you are using a DataTemplate with a DataType set, but it still works:
<DataTemplate DataType="{x:Type vm:MyViewModel}" >
<TextBlock Text="{Binding Text}"
d:DataContext="{Binding Source={StaticResource SampleDataSource}}" />
</DataTemplate>
This strategy will allow you to see how the DataTemplate will work while editing it directly, however you won't be able to see the result on any view that utilizes that DataTemplate unless you actually run the app. This is a limitation of Blend at the moment due to the fact that they don't appear to be using Mocks, but rather complete replacement objects. If blend ever adds the ability to create a new fake data source by clicking on "New DataSource -> Based on Referenced Object -> MyCustomerObject", then you will be in business.
It's possible you could overcome this limitation with some attached property trickery of your own, but it would be difficult at best.
Alternative
An alternative that will work in every situation, but is a bit more cumbersome to setup is setting up StaticResources that swap out fake data for real data during runtime, but in the designer show static sample data.
Here's a really great article by Karl Shifflett that includes some of these techniques and a few videos on it:
http://karlshifflett.wordpress.com/2008/10/11/viewing-design-time-data-in-visual-studio-2008-cider-designer-in-wpf-and-silverlight-projects/
Hope this helps,
Anderson
This strategy will allow you to see
how the DataTemplate will work while
editing it directly, however you won't
be able to see the result on any view
that utilizes that DataTemplate unless
you actually run the app. This is a
limitation of Blend at the moment due
to the fact that they don't appear to
be using Mocks, but rather complete
replacement objects. If blend ever
adds the ability to create a new fake
data source by clicking on "New
DataSource -> Based on Referenced
Object -> MyCustomerObject", then you
will be in business.
If I want to use acutal ViewModel mocks I guess it is the best way to create actual ViewModel instances and the references them with d:DataContext (e.g. using a ObjectDataProvider or x:Static)

wpf visual studio designer won't load user controls

The view below is a container for three user controls, and I started getting this error after refactoring application resources:
Error 295 Could not create an instance of type 'FilterPanel'. C:...\ProjectPickerWindow.xaml
Here is the xaml for the view:
<Window x:Class="Smack.ConstructionAdmin.WpfPresentation.Views.ProjectPicker.ProjectPickerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:Smack.ConstructionAdmin.WpfPresentation.Views.ProjectPicker"
xmlns:res="clr-namespace:Smack.ConstructionAdmin.WpfPresentation"
Background="{DynamicResource {x:Static res:SmackResources.WaveWindowBackground}}"
Title="{Binding Path=DisplayName}" FontFamily="Arial" FontSize="12"
SizeToContent="WidthAndHeight" MinWidth="300"
>
<DockPanel LastChildFill="True">
<local:FilterPanel DockPanel.Dock="Top" DataContext="{Binding}" Padding="3" />
<local:StatusAndButtons DockPanel.Dock="Bottom" DataContext="{Binding}" Margin="3, 7" />
<local:Listing DataContext="{Binding}" Margin="3, 0"/>
</DockPanel>
The app runs fine, and I can undo the refactorings, but I would prefer not to. All of the user controls display fine in their designer windows.
Can someone tell me how to get this to display in the designer?
Cheers,
Berryl
=== ADD'L INFO # Andrew ===
Great general checklist, if not the fix yet.
1) no silent binding errors
2) the designer works great after commenting out the FilterPanel!
3) no noticeable behavior change; all tests past too
4) yeah, I may have not left enough bread crumbs to nail the exact refactor but major ones were:
-- put all converters for the presentation in the own ResourceDic
-- had the FilterPanel reference generic.xaml, which has all mergedResourceDics. It referenced a specific Dic called ListingStyles.xaml, which used to have the converters
As an aside, do any tools help find Resource 'problems' (Snoop, Mole?)? Is there anything like FxCop to find bad practices??
Not yet an answer but some suggestions as there is not enough information to go on without knowing more about the app: (Posted as an answer as I thought it too long for a comment).
These designer only issues are a pain to track down as the root cause is often not specifically related to where the error arises.
This looks as if FilterPanel has a dependency on an object that doesn't yet exist. I have usually found these to be either due to not resolving resource dictionaries correctly or ValueConverter parameters not cast properly to types or initialised at Design time.
Things to try - in ascending order of speed
1) Run the app and look at the Output window to ensure there are no silent binding errors.
2) Narrow down the issue - if you comment out the line that refers to the FilterPanel does the designer work? Often the error crops up in the next line.
3) Although the app appears to run OK has this introduced different behaviours?
4) Step back through your refactorings to find the point at which the problem arose.
I have found Expression Blend to be more tolerant but not necessarily more verbose when it does fall over.
UPDATE:
If you haven't already you may need to add the ThemeInfo custom attribute to your custom controls so they can find their resources - although I think if this mechanism were not working the app would throw an Exception. Anyhow the declaration is
[assembly:ThemeInfo(
//Theme specific resources,
//Generic resources
)]
There is a bunch of valid code/xaml that the VS2K8 designer cannot handle. A lot of them the Blend designer can handle.
If your control needs to be constructed in a special way before it can be 'used', then VS will blow up.
One VS2008 problem is controls from an abstract class. here or here which sounds like what may have happened if you are "refactoring"

Setting Command Bindings via XAML on PageFunction forms

If you are creating a WPF window or a WPF page, you can bind commands to functions within the XAML.
<Page x:Class="WpfPageApplication.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfPageApplication="clr-namespace:WpfPageApplication"
Title="Page1" Background="LightGray"
>
<Page.CommandBindings>
<CommandBinding
Command="WpfPageApplication:PizzaCommands.ConfigurePizza"
Executed="OnConfigurePizza" />
</Page.CommandBindings>
There is another type of WPF form: a PageFunction. But it doesn't let you type:
<PageFunction.CommandBindings>
I can guess two possible explanations:
Because PageFunction is a generic object, you have to somehow enter the generic parameters into the XAML.
It's just an inconsistency in the framework.
Does anyone know how I can configure the CommandBindings for a PageFunction within the XAML? (I know I can do it in the code, but that's not the point).
PageFunction ultimately derives from Page, so I'm fairly certain you can just use <Page.CommandBindings> to define your command bindings. Certainly you can use <Page.Resources> in a PageFunction to define its resources.
Why can't you use <PageFunction.CommandBindings>? I don't know, but I think you're probably right when you say it has to do with the fact that PageFunction is a generic type. You'd need some way in XAML to say what the underlying type is. I think that's possible in the .NET 4.0 version of XAML but not in the current version.

What to do when WPF Window doesn't recognize user control defined in the same project?

I have a window "Operation" in XAML that uses a user control "Status" defined in the same project. When I build the solution, it returns ok, but when I open the design view for the Window, visual studio says "Could not create an instance of type 'Status'. The XAML for the Window "Operation" is below:
<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" "
MinHeight="550"
MinWidth="675"
Loaded="Load"
ResizeMode="NoResize"
WindowStyle="None"
WindowStartupLocation="CenterScreen"
WindowState="Maximized"
Focusable="True">
<Canvas Name="canv">
<tci:Status x:Name="ucStatus"/>
<Grid Canvas.Top="0" Canvas.Left="0">
<StackPanel Orientation="Horizontal">
<!-- Indices -->
<Label Width="200"/>
</StackPanel>
</Grid>
</Canvas>
</Window>
The xmlns:tci is the namespace where the Status Usercontrol is. And tci:Status becomes underlined in blue when this error happens. How to use a UserControl like this?
I was consistently having this problem with one control in my project and wound up resolving it by changing all of my images to DynamicResource rather than StaticResource.
The really strange thing is that the designer worked just fine for the control itself and showed the images as expected. It was only when I used the control inside my main window that the designer gave me the "Could not create instance of " message.
I don't know exactly whats the solution, but that happens to me too from time to time. I end up deleting declaration of the namespace, rebuilding and trying again. :\
Try cleaning your entire project, then do a full rebuild. The WPF designer in VS is poorly done, in my opinion, and there are weird issues like this all over the place.
I recommend not relying on Design View for anything, at this point - it's just too unstable. Try Expression Blend, it's a little bit better with things like this. If you don't want to go that route, you're probably better off building and running your app :-(
If you're running VS 2008, do you have SP1 installed?
I typically see this when I haven't built the control. Make sure you build the control and see if you still see the problem. Occasionally, VS just gets confused and you need to close and open the control you are having a problem with. In this case, that would be your window.
Similar to what Jon Norton said, I also found this link (-link removed, see below-) that implicates resources. I had the situation described in the link, and Jon's fix sorted it.
EDIT
Sorry, the link now requires a login and the page doesn't exist anymore. I couldn't find what it was supposed to be after three years.

Resources