2010-08-30 84 views
9

我想綁定到資源(DynamicResource)並訪問該資源上的屬性,但有沒有辦法做到這一點?如何綁定動態資源並指定路徑

(我想在Visual Studio中的XAML編輯器構造可視化的默認值。引用過的DataContext也沒有通過我的窗口類增加了一個屬性的對象時,這些不能被看見......)

沒有工作的XAML:(在作曲,但不能在運行時的作品...)

<Window ... > 
    <Window.Resources> 
     <local:MyClass x:Key="myResource" /> 
    </Window.Resources> 
    <StackPanel> 
     <Button Content="{Binding Source={DynamicResource myResource} Path=Property1}" /> 
     <Button Content="{Binding Source={DynamicResource myResource} Path=Property2}" /> 
    </StackPanel> 
</Window> 

與類(這可能需要執行INotifyPropertyChanged):

public class MyClass 
{ 
    public MyClass() 
    { 
     this.Property1 = "Ok"; 
     this.Property2 = "Cancel"; 
    } 
    public string Property1 { get; set; } 
    public string Property2 { get; set; } 
} 

回答

19

這是因爲DynamicResource標記擴展只能用於依賴項屬性,因爲如果資源發生更改,它將需要更新它。而Binding.Source不是依賴屬性...

作爲一種變通方法,您可以設置按鈕的DataContextDynamicResource

<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property1}" /> 
<Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property2}" /> 
+1

+1,這似乎是圍繞一個更清潔的工作和我」已經做到這一點效果很好 – marr75 2010-08-30 10:58:54

+1

不要忘了接受答案,然後;) – 2010-08-30 13:45:04