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>

我只是在学习,并且很好奇我是否可以将string文字绑定centralRes到另一个控件的 Text 属性(如src.Text),所以当它更新时,所有绑定到它的东西都会dst自动更新。

几乎就像一个信息的中心枢纽。这可能吗?

我想要的示例:

<sys:String x:Key="centralRes" Value="{Binding Text, ElementName=src}">Hello, world!</sys:String>
4

2 回答 2

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.

于 2014-09-19T16:18:28.243 回答
0

改用 StaticResource,即。{静态资源中心资源}

于 2015-09-02T13:33:52.617 回答