In this case I am looking to use strings declared in a resource dictionary as part of a binding on a Text
property. Binding just a single dynamic resource string is not a problem:
<TextBlock Text="{DynamicResource keyToMyString}" />
But you quickly run into problems if you need to use a StringFormat on a MultiBinding because you need to insert dynamic text or want to combine several strings. For example, if my MultiBinding looks like this:
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1} some more text">
<Binding Source="{x:Static Resources:Strings.string1}" />
<Binding Source="{x:Static Resources:Strings.string2}" />
</MultiBinding>
<TextBlock.Text>
I can inject string1
and string2
from the specified resource file into the bound text, no problems there. But I cannot find a way to use strings from a dynamic resource in the same way. (I'm using this method to inject company and product names into text from a merged resource dictionary).
With a TextBlock I can circumvent this issue by using several Run items for the TextBlock content (reference):
<TextBlock >
<Run Text="{DynamicResource CompanyName}" />
<Run Text="{DynamicResource ProductName}" />
<Run Text="{DynamicResource MajorVersion}" />
</TextBlock>
but this is of no help when needing to bind the dynamic resource to the Window Title property. Is there anyway to accomplish this with (creative, if necessary) use of the existing markup extensions (like x:Static
, etc)? Or do we have to write our own markup extension to achieve this?
Dynamic resource references have some notable restrictions. At least one of the following must be true:
- The property being set must be a property on a
FrameworkElement
orFrameworkContentElement
. That property must be backed by aDependencyProperty
.- The reference is for a value within a
Style
Setter
.- The property being set must be a property on a
Freezable
that is provided as a value of either aFrameworkElement
orFrameworkContentElement
property, or aSetter
value.
Source: XAML Resources, MSDN.
So, in case of using the Binding
, all the statements are violated.
As was shown, the DynamicResourceExtension
works just fine for an instance of the Run
class because the Run
class (at least) is derived from the FrameworkContentElement
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With