2011-10-24 48 views
0

我想將Border屬性的背景綁定到列表中的元素。從資源字典中綁定Boder.Background到LinearGradientBrush

我有一個字典持有follwing:

<LinearGradientBrush x:Key="ConfigurationItemBackground" EndPoint="0.5,1" StartPoint="0.5,0"> 
    <GradientStop Color="#FFAABBCC" Offset="1"/> 
    <GradientStop Color="#FFCCDDEE" Offset="0.7"/> 
</LinearGradientBrush>  

<LinearGradientBrush x:Key="NavigationItemBackground" EndPoint="0.5,1" StartPoint="0.5,0"> 
    <GradientStop Color="#FFD97825" Offset="1"/> 
    <GradientStop Color="#FFFF9A2E" Offset="0.7"/> 
</LinearGradientBrush> 

現在我填的ObservableCollection拿着包含一個名爲「BackgroundStyle」屬性對象。當我充滿風格的背景列表框我想在後臺「BackgroundStyle」

<Border x:Name="Border" BorderThickness="1" CornerRadius="4" Width="120" Height="80" 
     VerticalAlignment="Center" HorizontalAlignment="Center" Padding="4" 
     BorderBrush="Black" Background="{Binding Path=BackgroundStyle}"> 

結合這種運作良好,如果BackgroundStyle =「紅色」或「綠色」,但它不會,如果我的工作使用「ConfigurationItemBackground」。

有什麼建議嗎? 感謝您的幫助;)

-Tim-

+0

你的ObservableCollection與Border的關係如何?你是否將其設置在邊界的DataContext中,或者它的任何直接父母? –

+0

@PhilippSchmid:他的'ListBox'將該集合作爲它的'ItemsSource',聽起來像。 'Border'看起來就像是'DataTemplate',他將'Background'綁定到'BackgroundStyle'屬性。 –

回答

0

你不能做的正是你正在嘗試做的,這基本上是使用數據綁定到存儲資源的關鍵內你的綁定對象。您可以得到的最接近的答案是this question,它基本上使用ValueConverter從應用程序資源獲取資源。

不幸的是,這不會與你想要做的,這是使用本地資源。爲此,你最好寫下你自己定製的ValueConverter,將你的string值轉換成畫筆。

可以做一些通用這樣的:

[ValueConversion(typeof(string), typeof(object))] 
public class ResourceKeyConverter : IValueConverter 
{ 
    public ResourceKeyConverter() 
    { 
     Resources = new ResourceDictionary(); 
    } 

    public ResourceDictionary Resources { get; private set; } 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return Resources[(string)value]; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new InvalidOperationException(); 
    } 
} 

然後使用它是這樣的:

<Window.Resources> 
    <my:ResourceKeyConverter x:Key="keyConverter"> 
     <ResourceKeyConverter.Resources> 
      <LinearGradientBrush x:Key="ConfigurationItemBackground" EndPoint="0.5,1" StartPoint="0.5,0"> 
       <GradientStop Color="#FFAABBCC" Offset="1"/> 
       <GradientStop Color="#FFCCDDEE" Offset="0.7"/> 
      </LinearGradientBrush>  

      <LinearGradientBrush x:Key="NavigationItemBackground" EndPoint="0.5,1" StartPoint="0.5,0"> 
       <GradientStop Color="#FFD97825" Offset="1"/> 
       <GradientStop Color="#FFFF9A2E" Offset="0.7"/> 
      </LinearGradientBrush> 
     </ResourceKeyConverter.Resources> 
    </my:ResourceKeyConverter> 
</Window.Resources> 

... 

<Border Background="{Binding BackgroundStyle, Converter={StaticResource keyConverter}}"> 
</Border> 

(我在家裏,沒有前面的Visual Studio我,所以這可能需要一些調整,但它應該基本上是正確的)。