2017-01-16 86 views
0

我有資源中定義的視覺畫筆列表。如下所示。如何將資源名稱與背景屬性綁定?

<Window.Resources> 
    <VisualBrush x:Key="Img"> 
     <VisualBrush.Visual> 
      <Canvas> 
       <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="path3402" Fill="#FFDDE6EE" Data="m 171.33928 338.07648 0 -140.625 234.375 0 234.375 0 0 140.625 0 140.625 -234.375 0 -234.375 0 0 -140.625 z"/>      
      </Canvas> 
     </VisualBrush.Visual> 
    </VisualBrush> 

    <VisualBrush x:Key="Img1"> 
     <VisualBrush.Visual> 
      <Canvas>     
       <Path xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Name="path3396" Fill="#FF6798C8" Data="m 171.33928 338.07648 0 -140.625 234.375 0 234.375 0 0 140.625 0 140.625 -234.375 0 -234.375 0 0 -140.625 z m 75 130.21087 c 0 -0.61571 0.87726 -0.81896 z"/>      
      </Canvas> 
     </VisualBrush.Visual> 
    </VisualBrush> 
</Window.Resources> 

資源鍵值將來自viewmodel的列表。 現在我想達到以下。

<Border Background="{StaticResource Binding{ResourceName}}"/> 

我怎麼能達到以上?

+0

這不支持使用StaticResource或DynamicResource。您可以實現自己的自定義標記擴展:http://www.c-sharpcorner.com/uploadfile/mamta_m/creating-a-custom-markup-extension-in-wpf/。或者使用轉換器。 – mm8

+0

轉換器如何在這裏有用。你能解釋一下嗎? – Rudra

+0

請參考我的回答。 – mm8

回答

1

這可不是用靜態資源也不DynamicResource支持,但你可以使用多轉換器:

public class ResourceConverter : IMultiValueConverter 
{ 
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (values != null && values.Length == 2) 
     { 
      string resourceKey = values[0].ToString(); 
      Window window = values[1] as Window; 
      if (!string.IsNullOrEmpty(resourceKey) && window != null) 
       return window.Resources[resourceKey] as System.Windows.Media.Brush; 
     } 
     return null; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

用法:

<Window.Resources> 
    <VisualBrush x:Key="Img1">...</VisualBrush> 
    <VisualBrush x:Key="Img2">...</VisualBrush> 
    <local:ResourceConverter x:Key="ResourceConverter" /> 
</Window.Resources> 
... 
<Border> 
    <Border.Background> 
     <MultiBinding Converter="{StaticResource ResourceConverter}"> 
      <Binding Path="ResourceName" /> 
      <Binding Path="." RelativeSource="{RelativeSource AncestorType=Window}" /> 
     </MultiBinding> 
    </Border.Background> 
    <TextBlock>...</TextBlock> 
</Border> 

public string ResourceName { get; } = "Img1"; 

另一種選擇是寫你的自定義標記擴展名:http://www.c-sharpcorner.com/uploadfile/mamta_m/creating-a-custom-markup-extension-in-wpf/

+0

感謝您的詳細解釋。這將解決我的問題。 – Rudra

相關問題