2013-06-01 143 views
1

我已經創建了一個附加屬性添加到UserControls。此附加屬性需要綁定,並且此綁定需要轉換器。附加屬性聲明

由於資源是在UserControl聲明後設置的,我正在尋找一種方法來在資源創建後聲明附加屬性。我怎樣才能做到這一點?

一個例子,如果我定義背景的靜態資源,我不能設置在控制創作背景,但在資源創建後:

<UserControl ... 
      ... 
      ...> 

<UserControl.Resources> 
    background color declared 
</UserControl.Resrouces> 

<UserControl.Background> 
    usage of the StaticResource here is valid. 
</UserControl.Background> 

所以我想同樣帶有附加屬性,我woudl正常定義爲:

<UserControl xx:MyAttachedProperty.Bla="{Binding A}" > 

但因爲我需要一個轉換器,我想在資源後面指定它。

希望它很清楚。謝謝。

回答

1

您可以將您的Converter定義爲一個等級的資源,可以是WindowApp的一部分,也可以按照您的意圖使用它。

此外,將公共資源移動到應用程序級別可讓您獲得re-usability不同的用戶控件可以共享的優勢。將您的轉換器移至App.xaml -

<App.Resources> 
    <!-- Your converter here --> 
</App.Resources> 
+0

我還沒有意識到共享那種方式的資源。很好的事情要知道。我要檢查它。無論如何,你知道我能否以某種方式聲明像這樣的附屬屬性?因爲這個轉換器是特定的視圖,它不會被肯定重用。 –

+0

@SoMoS如果您只使用UserControl上的屬性,爲什麼不把它設置爲正常的DP。這樣你就可以得到你想要的行爲,並且足夠清楚地說明它只是一個屬性UserControl – Viv

+0

它的轉換器只能在用戶控件上使用。不管怎麼說,還是要謝謝你! –

2

您可以使用ResourceDictionary

只是Add -> Resource dictionary

它添加在Solution Explorer中聲明你的Converter有像

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

    <BooleanToVisibilityConverter x:Key="BooleanToVisibility" /> 

</ResourceDictionary> 

在你XAML,你可以使用它像

<Window.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="MyResources.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Window.Resources> 

現在你可以使用你的Converter任何地方你有你的Resource Dictionary

如果你只需要你的ConverterUserControl(如你在上面的評論中提及),那麼你仍然可以把它聲明,如:

<Window.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="MyResources.xaml" /> 
      <ResourceDictionary> 
       <BooleanToVisibilityConverter x:Key="MyConverter" /> 
      </ResourceDictionary> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Window.Resources> 

我只是用BooleanToVisibilityConverter的例子,但它很容易在那裏使用你自己的轉換器。

+0

沒有。在調用Window.Resources之前,我不能使用聲明到該字典中的任何東西,這正是我所遇到的問題。 –

+1

有兩個步驟。在字典中聲明它,然後在window.resources中添加該字典並且可以使用它。 –

+0

現在我明白你的觀點。謝謝。 –