Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top