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

微笑、不失礼 提交于 2019-12-12 02:01:41

问题


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

回答1:


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.




回答2:


Use StaticResource instead ie. {StaticResource centralRes}



来源:https://stackoverflow.com/questions/25932736/is-it-possible-to-bind-a-dynamicresource-of-clrstring-to-another-source-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!