ContextMenu static resource compile error - silverlight

I've created a Silverlight control with a ContextMenu property. I've also created a ContextMenu static resource, which one I want to add to the control, but I get a compile error.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controlsInputToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit" >
<controlsInputToolkit:ContextMenuService.ContextMenu x:Key="FilterableTreeViewContextMenu">
<controlsInputToolkit:ContextMenu>
<controlsInputToolkit:MenuItem Header="New" />
</controlsInputToolkit:ContextMenu>
</controlsInputToolkit:ContextMenuService.ContextMenu>
</ResourceDictionary>
The error:
Unexpected ATTRIBUTE in parse rule PropertyElement ::= . PROPERTYELEMENT Content? ENDTAG..
Any idea?

This error indicates that an attribute has been applied to a property element which is not valid. In your case, this is the x:Key attribute on the controlsInputToolkit:ContextMenuService.ContextMenu element. You will need to remove it.
You can identify property elements in XAML by the period that is included within the name of the element. The part of the name prior to the period is the name of a class and the part that follows is a property on that class. Attributes are not allowed within such elements.
Your XAML was compact enough for me to easily find the problem. If this error occurs within a much larger XAML file, then the following regular expression can be used within Visual Studio to locate the problem. Just make sure to check the 'Use' checkbox in the 'Find and Replace' dialog and select 'Regular Expressions' in the combo box.
\<:Al#.:Al# :Al#=\".#\":b#>
If you need to adjust the expression then the MSDN documentation on regular expression syntax will be useful.

Related

What does the <vm:SimpleViewModel x:Key="viewModel"/> mean in WPF?

I am new to WPF and MVVM, actually started just a week back and I am trying to code up an application using both WPF and MVVM, while coding up an example I came across the following statement <vm:SimpleViewModel x:Key="viewModel"/> and I am trying to reason about it. I understand what 'x:' refers to, its the default XAML namespace mentioned in the XAML file and I have created a namespace for my own ViewModel class that the UI will be interacting with and I have given it an alias "vm" and SimpleViewModel is the ViewModel for my application, the statement for the purposes of reference is xmlns:vm="clr-namespace:MVVM_Tutorial".
My Reasoning for the statement <vm:SimpleViewModel x:Key="viewModel"/> is that a Window is a XAML element and has a resource dictionary that it refers to resolve and refer to certain elements, hence inside its resource dictionary which is defined in the "x:" namespace we are assigning a variable called "Key" whose value is the SimpleViewModel class defined in the "vm:" namespace. Just want to know if I am right with my reasoning or is there something that I am missing and would want to know proceeding further from here.
XAML is just markup that describes an object graph. Code is also markup that describes an object graph. I can say this
var window = new Window();
window.DataContext = new MyNamespace.MyViewModel();
or I can write the exact same thing like this
<Window xmlns:blahblah="clr-namespace:Normal.Xmlns.Deleted.For.Brevity"
xmlns:this="clr-namespace:MyNamespace">
<Window.DataContext>
<this:MyViewModel />
<!-- snip -->
Any object that can be instantiated in code can be used in xaml. There are some restrictions (e.g., default public constructor without arguments), but for the most part this is true. XAML just defines an object graph that is deserialized at runtime.
Since any type can be referred to in xaml, you could, hypothetically, have moved that instance of MyViewModel to a resource dictionary and referred to it via a StaticResource or a DynamicResource. Note, anything you put in a resource dictionary has to have a key, assigned via x:Key:
<Window xmlns:blahblah="clr-namespace:Normal.Xmlns.Deleted.For.Brevity"
xmlns:this="clr-namespace:MyNamespace"
DataContext="{DynamicResource lolderp}">
<Window.Resources>
<this:MyViewModel x:Key="lolderp" />
<!-- snip -->
XAML is a subset of XML, and uses XML namespaces to map to code namespaces in the current, or other, assemblies. It's how the framework knows what object MyViewModel refers to. To learn more, read this link on msdn.
I'm sure someone else can chime in with more clarification...
In the xaml file, the references of
"xmlns:[something]="clr-namespace:[yourProjectOrLibrary]".
Since your code-behind can be verbose with long name space references, and your SOLUTION may be made up of multiple projects (such as different DLLs), when the XAML is processed, it uses the "xmlns" as a reference to whatever "yourProjectOrLibrary" is... In your case the project/class "MVVM_Tutorial".
Now, the "vm". This is just an "alias" within the xaml, so anytime it is referencing a
The xaml knows where it originates to get resolution to control, properties, types, etc.
As for the "x:Key" part... Not positive, but when I was first building out my customized themes, also ran into confusion about the x:Key. My interpretation of this was found to be x:Key is like a private reference, but by being given the name ..x:Key="viewModel"... is making this "name" available later within the xaml file.
This "key" can then be referenced later in the xaml... For example,
<ControlTemplate x:Key="CTButton" TargetType="{x:Type Button}" >
<!-- Start border of button to have a rounded corners -->
</ControlTemplate>
Then later within the theme, I could reference this "Key"... in my case "CTButton". So if I wanted multiple controls to use / derive from same control template, I could have them reference it...
<someControl>
<Style>
<Setter Property="Template" Value="{StaticResource CTButton}" />
</Style>
</someControl
Again, I don't get EVERYTHING about all the xaml markup, but hopefully clarifies this for you some.

Trouble adding a DataTemplateSelector to a wpf XAML

This is my first time ever doing anything with XAML and I'm a bit lost.
I'm trying to add a DataTemplateSelector to my XAML page using the instructions found here.
However I'm stuck on the part where I'm supposed to "declare the TaskListDataTemplateSelector as a resource". This is the example given:
<Window.Resources>
...
<local:TaskListDataTemplateSelector x:Key="myDataTemplateSelector"/>
...
</Window.Resources>
However, the top level tag in the XAML document is <UserControl>, and I don't see anything about Window or Window.Resources.
Under the <UserControl> tag is a <UserControl.Resources> tag, but when I try to put the example code there, it gives me an error saying "The namespace prefix 'local' is not defined". I tried replacing "local" with the actual namespace, but got the same error.
The custom DataTemplateSelector class is in the codebehind for the XAML page, and is in the same namespace.
For anyone who googled this question like I did:
I think I found the answer.
You need to define the local prefix in your XAML file.
This can be done by placing the following namespace argument in the root element:
xmlns:local="clr-namespace:AssemblyName"
Change "AssemblyName" in your erm.. assembly's name.

What does (x) in x:Name mean in Silverlight XAML Markup?

We see some properties in TextBlock or Grid like this:
<TextBlock x:Name="TextBlock1" ...
Why do we include this (x)? why don't we just say:
<TextBlock Name="TextBlock1" ...
I mean, we're already within the definition scope of this TextBlock, right?
There must be a reason for that.
Thanks in advance.
As an extension to Gabe's answer, x:Name is an attached property. Attached properties are different from standard properties, as they aren't defined (usually) on the control that uses them. For example, the TextBlock control does not have an x:Name property - instead, this property is defined elsewhere (in the XAML namespace), and is being "attached" to the TextBlock control to implement it's behaviour. It's saying "I want to use the Name attached property that can be found in the XAML namespace). Of course, to complicate things, the TextBlock control has a Name property (it didn't used to in Silverlight 2, thus you needed to use the x:Name attached property instead). They do the same thing though.
Another (easier to understand) example of an attached property is Grid.Row. You can use this property on the TextBlock control to specify what row the control should appear in a Grid, even though it's not defined on that control (the Grid control defines it). The TextBlock is simply attaching that property to itself, which associates itself with that behaviour. It's a confusing concept initially, but very powerful and useful. More info on attached properties can be found here: http://msdn.microsoft.com/en-us/library/cc265152(VS.95).aspx.
Hope this helps...
Chris
That is a namespace prefix.
Example 1:
You should see something like this on the xaml page:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Which declares the x prefix referring to the xaml namespace.
Example 2:
You could load your own user controls by registering the namespace and giving it a prefix.
xmlns:mycontrols="clr-namespace:MyControls.Namespace;assembly=MyAssembly"
Then here we are using the prefix to utilize one of the controls from this namespace.
<mycontrols:MyControl />

Is there any difference in x:name and name for controls in xaml file?

I am new in Silverlight.
When I add some control to my xaml file with Visual Studio it set controls name with Name property, but there is also x:Name.
Is there any difference and when to use each of them?
Thanks.
In Brief
Yes there is a difference. The bottom line is that x:Name can be used on object elements that do not have Name properties of their own.
A longer explanation
You can only use Name on an element that represents an object that actually does have a Name property. For example anything that derives from FrameworkElement.
The x:Name attribute may be placed on any element that represents an object regardless of whether that object actually has a Name property. If the object does have a Name property then the value of x:Name will be assigned to it hence you can't have both x:Name and Name on the same element.
When an object has a Name property or an x:Name property the value of that property is associated with the objects entry in the object tree. It is via the object tree that the FindName method of a FrameworkElement can find an object. FindName can find objects by name even if that object does not carry a Name property of its own since it uses the name recorded in the object tree.
The autogenerated code for a UserControl will contain field definitions for any element that that has a Name or x:Name property. The InitialiseComponent method that is generated will use the FindName method to assign values to these fields.
Example
The above Xaml creates two fields LayoutRoot of type Grid and MyBrush of type SolidColorBrush. If you were to change x:Name="LayoutRoot" to Name="LayoutRoot" that would change nothing. Grid has a Name property. However try changing x:Name="MyBrush" to Name="MyBrush". That doesn't work because SolidColorBrush doesn't have a name property. With the above Xaml you can then do code like this:-
public MainPage()
{
InitializeComponent();
MyBrush.Color = Colors.LightGray;
}
Open the definition of InitializeComponent and take a look at the auto generated code.
No, you just can't use them both. x:Name is what the XAML preprocessor actually uses and Name is just a convience property provided on the FrameworkElement class to set it.
From the MSDN reference:
If Name is available as a property on an element, Name and x:Name can be used interchangeably, but an error results if both attributes are specified on the same element.
Short answer: if you're writing stuff out in XAML, it's probably best to just use x:Name consistently.
Long answer: A previous answer mentioned that Name is a "convienience" property for accessing x:Name. That's correct. However, now that the tools environment for XAML in both Visual Studio and the Expression series has really matured and you are seeing more and more tool-generated XAML, you are also probably seeing more and more x:Name as opposed to Name. The tools prefer x:Name because that way they don't take a somewhat risky dependency (potentially specific to framework) re: how x:Name and Name are really the same, and they don't need to flipflop between setting Name if something happens to be a FrameworkElement and then x:Name on something like a Storyboard and generating a duality if you were to look at this XAML through something like a DOM. In other words, the "Name" attribute in XAML really is a lot less "convenient" to use nowadays than might have been conceived of in the original API design. Part of the "convenience" was to not have to map x:, but you have to do that anyways for x:Class and by now pretty much everyone has gotten used to using x: attributes and the general principles of XAML markup effectively.
I'm not sure of the statement made by the original poster that VS encourages using Name. Yes, Name appears as an intellisense option, but so does x:Name. And all the cases I see in the templates where an object is given a starting name are using x:Name even tho most of these are FrameworkElements.

How to set properties of a d:DesignInstance in XAML?

I'm using the new d:DesignInstance feature of the 4.0 series WPF tools. Works great!
Only issue I'm having is: how can I set properties on the instance? Given something like this:
<Grid d:DataContext="{d:DesignInstance plugin:SamplePendingChangesViewModel, IsDesignTimeCreatable=True}"/>
How can I set properties on the viewmodel, aside from setting them in its default ctor or routing it through some other object initializer?
I gave this a try but VS gives errors on compile "d:DataContext was not found":
<Grid>
<d:DataContext>
<d:DesignInstance IsDesignTimeCreatable="True">
<plugin:SamplePendingChangesViewModel ActiveTagIndex="2"/>
</d:DesignInstance>
</d:DataContext>
For the moment I'm going back to using a resource and 'd:DataContext={StaticResource SampleData}', where I can set the properties in the resource.
Is there a way to do it via a d:DesignInstance?
As #jberger you should probably use d:DesignData instead of inlining a d:DataContext.
However you can set the d:DataContext inline in the xaml file as well, the secret is to use the correct class (DesignProperties) to qualify the d:DataContext property:
<d:DesignProperties.DataContext>
<plugin:SamplePendingChangesViewModel ActiveTagIndex="2"/>
</d:DesignProperties.DataContext>
How do you know what class to qualify with? Mouse over a property that is set in attribute syntax and a tooltip will appear with the fully qualified property name.
Note also that im not using the d:DesignInstance markup exstension as its job specifically is to create a instance of a type that you provide the name for (or generate a proxy of that type if it cant be instanciated at design-time). Thats not what we want, we want to define the instance in inline xaml in this case.
Indeed, d:DesignData (also a markup extension) works much the same way, except that it looks for a xaml file and deserializes that to the actual instance to use instead of just using the default constructor.
Just for completeness i should also mention that you can use DesignData and DesignInstance with element syntax as well by using their full class names (xxxExtension):
<d:DesignProperties.DataContext>
<d:DesignDataExtension Source="SampleData.xaml"></d:DesignDataExtension>
</d:DesignProperties.DataContext>
This is true for most markup exstensions but its not required to follow this naming convension (The Binding class is a notable exception) More info can be found here:
Markup Extensions and WPF XAML

Resources