Is it possible to bind a DynamicResource of clr:string to another source instead of literal?
Asked Answered
A

2

0
<Window x:Class="WpfTutorialSamples.WPF_Application.ResourceSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <Window.Resources>
        <sys:String x:Key="centralRes">Hello, world!</sys:String>
    </Window.Resources>

    <StackPanel Margin="10">
        <TextBox Name="src" />
        <TextBlock Name="dst" Text="{DynamicResource centralRes}" FontSize="56" />
    </StackPanel>
</Window>

I am just learning, and was curious if I can bind the string literal in centralRes to another control's Text property (like src.Text), so when it updates, all things bound to it like dst automatically update.

Almost like a central hub for a piece of info. Is this possible to do?

Example of what I want:

<sys:String x:Key="centralRes" Value="{Binding Text, ElementName=src}">Hello, world!</sys:String>
Athabaska answered 19/9, 2014 at 11:19 Comment(3)
I used <sys:Boolean>True</sys:Boolean> throughout my application and had no problem with it.Greenhead
@Greenhead I need a way of binding that True or literal value in case of a string to another source, in XAML. I know if I change it in code it would all work magically.Athabaska
So you need it to be dependent on like a MainViewModel and display the same information throughout the app? Obviously only the Items that are bound to that Resource.Greenhead
L
0

Binding directly to the object (saved in Resources) in this case is not easy if not wanting to say it's impossible. However you can bind the Text to the Window and set the Path to that resource and it works OK:

<TextBox Name="src" 
         Text="{Binding RelativeSource={RelativeSource AncestorType=Window},
         Path=Resources[centralRes],Mode=OneWayToSource,
         UpdateSourceTrigger=PropertyChanged}"/>

More about binding directly to the object: When doing like this, the Source of the Binding will be assigned to a StaticResource and the Path should be . (otherwise an error saying 2 way binding requires Path or XPath although we set Mode to BindingMode.OneWayToSource). Using DynamicResource is not possible for a Binding's Source. After that the code compiles OK but the Binding does nothing. I doubt that the StaticResource is the problem, however as I said, DynamicResource cannot be used. Hence we're stuck at binding directly to the object.

Letta answered 19/9, 2014 at 16:18 Comment(0)
P
0

Use StaticResource instead ie. {StaticResource centralRes}

Protrusile answered 2/9, 2015 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.