What does this WPF binding mean? - wpf

I have this sample code:
<ControlTemplate Content="{Binding .}"/>
What does the point mean here relating to the binding?

The . (period) of the binding refers to the binding path, and simply tells it to bind to the current source (i.e. inherited DataContext).
From the MSDN page:
Optionally, a period (.) path can be used to bind to the current source. For example, Text=”{Binding}” is equivalent to Text=”{Binding Path=.}”.
Also note that Path= can be omitted if Path is the first parameter, so your code means exactly the same. I tend to prefer just the {Binding} syntax, though it's up to you.

Related

What is the difference between x:Reference and ElementName?

According to the x:Reference Markup Extension page on MSDN, x:Reference
References an instance that is declared elsewhere in XAML markup. The reference refers to an element's x:Name.
According to the Binding.ElementName Property page on MSDN, ElementName
The value of the Name property or x:Name Directive of the element of interest.
Looking back at the remarks section on the first page:
x:Reference and WPF
In WPF and XAML 2006, element references are addressed by the framework-level feature of ElementName binding. For most WPF applications and scenarios, ElementName binding should still be used. Exceptions to this general guidance might include cases where there are data context or other scoping considerations that make data binding impractical and where markup compilation is not involved.
For completeness, here is part of the remarks section on the ElementName page:
This property is useful when you want to bind to the property of another element in your application. For example, if you want to use a Slider to control the height of another control in your application, or if you want to bind the Content of your control to the SelectedValue property of your ListBox control.
Now, while I am fully aware of when and how to use the ElementName property, I don't fully understand the difference between it and the x:Reference markup extension. Can anybody please explain this and in particular, expand on the last sentence shown from the x:Reference remarks section?:
Exceptions to this general guidance might include cases where there are data context or other scoping considerations that make data binding impractical and where markup compilation is not involved.
Basically like you said those two do almost the same. However there are small differences under the hood.
{x:Reference ...} -> returns just a reference of an object it doesn't create that "bridge" between two properties like binding would do. Behind all that a service is being used that searches for the given name in a specific scope which is usually the window itself.
{Binding ElementName="..." } -> first of all it creates that binding object then it searches for the object name but not by using the same technique under the hood as x:Reference. The search algorithm moves up and/or down in VisualTree to find the desired element. Therefore a functional VisualTree is always needed. As example when used inside a Non-UiElement, it won't work. In the end the Binding stays and does its daily bread.
This won't work:
<StackPanel>
<Button x:name="bttn1" Visibility="Hidden">Click me</Button>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Visibility="{Binding ElementName=bttn1, Path=DataContext.Visibility}"/>
....
This works:
<StackPanel>
<Button x:name="bttn1" Visibility="Hidden">Click me</Button>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Visibility="{Binding Source={x:Reference bttn1}, Path=DataContext.Visibility}"/>
....
Sort of like that :)
ElementName is platform specific. I.e. it may or may not be present based on which platform you're using. x:Reference elevates that concept to a XAML native feature. Thus any platform that supports XAML supports x:Reference.

What do parentheses in binding paths mean?

Recently i've read 'Databinding overview' article at MSDN and there is such sample code:
<TextBox.ToolTip>
<Binding RelativeSource="{RelativeSource Self}" Path="(Validation.Errors)[0].ErrorContent"/>
</TextBox.ToolTip>
I know that {} means markup extensions but what mean () parentheses here? It would be nice someone share link to explanation such syntax. Thanks!
Path="(Validation.Errors)[0].ErrorContent"
The () parentheses refer to Attached Properties.
Binding to an Attached Property
Quoting the MSDN library (I'm quoting MSDN here because I couldn't have written it down better):
This syntax is generally used for one of the following cases:
The path is specified in XAML that is in a style or template that does not have a specified TargetType. A qualified usage is generally not valid for cases other than this, because in non-style, non-template cases, the property exists on an instance, not a type.
The property is an attached property.
You are binding to a static property.
For use as storyboard target, the property specified as propertyName must be a DependencyProperty.
(Validation.Errors) references the attached property Errors in the Validation class. Since the binding has a RelativeSource = Self, it's gonna look for the value of that attached property with respect to the TextBox itself.
This below msdn link is neatly explaining about the validation rule and sequences as well as how to use.
http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errors.aspx

Why is StaticResource required?

First, I searched long and hard to try to find the answer to this. I resorted to here for expert help with this problem.
I am currently reading a book about programming for the Windows Phone 7. I am currently learning about Data Binding (and doing pretty good too). I have come across a question about the formatting of DataBinding in WPF, mostly about the function of StaticResource.
In the following code you are about to see, there is a slider and a text block. The text block is binded to the slider so that when the slider is moved, the text block's value changes. A class has been created, TruncationConverter, and has can be called in XAML with the keyword "truncate". It is declared in phone:ApplicationPage.Resources.
So, this is right
<TextBlock Name="txtblk"
Text="{Binding ElementName=slider,
Path=Value,
Converter={StaticResource truncate}}"
And this is wrong
<TextBlock Name="txtblk"
Text="{Binding ElementName=slider,
Path=Value,
Converter=truncate}"
The book never really went in to explaining why one must put StaticResource before the function.
So, the question is, why do you need to put StaticResource before the call? What does it do, what is its function? Why is there an error when you don't put StaticResource before truncate.
Thanks in advance!
The constructor for the Converter class uses a markup extension in order to work. The markup extension requires that the object be previously defined in the object graph, and this is was done when you assigned your converter class a key. When the Xaml parser sees StaticResource (or DynamicResource) it starts looking upward in the object graph until the value is found. At runtime, an instance of the class is created and used to do your conversions. Once an instance of your converter has been created, WPF uses it for the life time of your application, hence 'Static'.
The 'StaticResource' may seem extraneous or redundant because a converter cannot be a DynamicResource, but such are the syntax rules of Xaml.
Basically placing StaticResource is telling it to find the external property likely in a ResourceDictionary which holds the function of for example "truncate"
So like another example would be if I go and say create another control or converter or even a brush or other instance I wish to be made available throughout other elements of an application, it's created as an available resource that is only editable in one spot (a resource dictionary) but usable by all, eg; a StaticResource
Like when you placed your slider and your Textblock, it by default is calling a style for each found in your CoreStyles resource dictionary. If I wanted to change what they did or how they look for example I could copy the resource, edit it as necessary, rename it, and say call it by

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 />

How does a XAML definition get turned into an object instance?

XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a Binding instance and assigns it to the Text property of the TextBox element.
<TextBox Text="{Binding ElementName=Foo, Path=Bar}"/>
I want to extend XAML so that the developer could enter this as valid...
<TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/>
This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it?
If this is possible I have a followup question. Can I take a string "{Binding ElementName=Foo, Path=Bar}" and ask the framework to process it and return the Binding instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed.
The Binding class is a Markup Extension. You can write your own by deriving from System.Windows.Markup.MarkupExtension.
ElementName and Path are simply properties on the Binding object.
As for the followup you can create a new Binding in code by instantiating the Binding object. I do not know of a way to process a string through.
take a look at markupextensions
http://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecustommarkupextension.aspx

Resources