Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use a DynamicResource in a MultiBinding at all?

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?

like image 902
slugster Avatar asked Jun 06 '13 13:06

slugster


Video Answer


1 Answers

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 or FrameworkContentElement. That property must be backed by a DependencyProperty.
  • 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 a FrameworkElement or FrameworkContentElement property, or a Setter 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.

Additional references

  1. Resources section: Wha' Happened Part Two: More Property Changes in WPF.
  2. WPF: Dependency Properties & Resources.
like image 149
Sergey Vyacheslavovich Brunov Avatar answered Oct 24 '22 18:10

Sergey Vyacheslavovich Brunov