2014-09-19 71 views
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> 

我剛學,並很好奇,如果我能在centralRes綁定string文字到另一個控件的Text屬性(如src.Text),所以當它更新,勢必會像dst萬物自動更新。是否可以將clr:string的DynamicResource綁定到另一個源而不是文字?

幾乎就像一個信息的中心樞紐。這可能嗎?我想要什麼

例子:

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

我在我的應用程序中使用了' True',並且沒有任何問題。 – XAMlMAX 2014-09-19 11:48:39

+0

@XAMlMAX我需要在XAML中綁定'True'或字符串值的方式來將字符串綁定到另一個源。我知道如果我在代碼中改變它,它們都會神奇地起作用。 – sprocket12 2014-09-19 12:02:20

+0

所以你需要它像'MainViewModel'一樣依賴,並在整個應用程序中顯示相同的信息?顯然只有綁定到該資源的項目。 – XAMlMAX 2014-09-19 12:18:12

回答

0

直接綁定到在這種情況下,對象(保存在資源)是不容易的,如果不想說這是不可能的。然而,你可以綁定TextWindow並設置Path到資源,它的工作原理確定:

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

更多關於直接綁定到該對象:在做這樣的BindingSource會分配給StaticResourcePath應該是.(否則,雖然我們將Mode設置爲BindingMode.OneWayToSource,但是表示2路綁定需要Path或XPath的錯誤)。對於Binding的來源,使用DynamicResource是不可能的。之後代碼編譯好,但綁定什麼都不做。我懷疑StaticResource是問題,但正如我所說,DynamicResource不能使用。因此,我們堅持直接綁定到對象。

0

改爲使用StaticResource即。 {StaticResource centralRes}

相關問題