2010-06-25 96 views
1

我想在Silverlight 4用戶控件的資源中設計一組圖標,然後在按鈕上顯示這些圖標。數據綁定按鈕內容到靜態資源失敗

<UserControl.Resources>   
    <Rectangle x:Key="Icon1" Fill="Black" Width="10" Height="10" />    
</UserControl.Resources> 

<Button x:Name="Button1" 
     Width="50" Height="50"       
     Content="{Binding Source={StaticResource Icon1}}" /> 

我也試過... Content="{StaticResource Icon1}"。兩者在VS 2010的XAML設計器中均表現良好,但在嘗試使用XAMLParseException運行時失敗。第一個人抱怨說這個論證沒有落入預期的範圍內,第二個只是說「無法分配財產」。將矩形複製到按鈕內容中直接正常工作。

問題在哪裏?我以爲我終於明白這一點.. =/

回答

2

我會建議使用模板,而不是設置內容。

<ControlTemplate 
    x:Key="IconTemplate"> 
     <Rectangle x:Key="Icon1" Fill="Black" Width="10" Height="10" /> 
</ControlTemplate> 

<Style x:Key="IconStyle" TargetType="Button"> 
     <Setter Property="Template" Value="{StaticResource IconTemplate}"/> 
</Style> 

<Button x:Name="Button1" 
     Width="50" Height="50"       
     Style="{StaticResource IconStyle}" /> 

HTH

+0

感謝您的回答!我想知道,爲什麼你會選擇這種方法而不是直接設置內容? – Jens 2010-06-28 06:09:30

+0

有幾個原因; 1)它似乎是MS希望我們使用WPF的方式 2)這可以更好地測試,以確保元素(模板和樣式)可用於控制 3)對我來說這是一個更具可擴展性的方法,但這可能是有爭議的 – 2010-06-29 16:19:33

+0

我試過這種方法,但似乎我的(triggerbehavior)模板內部的控件的VisualState不被維護。任何線索爲什麼? – 2014-12-11 13:40:03

0

我完成了這一由的ContentTemplate設置爲一個DataTemplate:

<UserControl.Resources>   
    <DataTemplate x:Key="Icon1"> 
     <Rectangle Fill="Black" Width="10" Height="10" />    
    </DataTemplate> 
</UserControl.Resources> 

按鈕:

<Button x:Name="Button1" 
     Width="50" Height="50"       
     ContentTemplate="{StaticResource Icon1}" /> 

設置模板上的按鈕工作過,但我相信你必須替換控件的整個模板。這種方法可以讓你保持現有的控制模板。

+0

...我在WPF中做了這個,但我認爲它也適用於Silverlight。 – 2013-01-22 05:49:32