如何使用background属性绑定资源名称?

时间:2017-01-16 11:10:17

标签: wpf xaml mvvm binding resources

我有资源中定义的可视画笔列表。如下。

<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}}"/>  

我如何才能达到上述目标?

1 个答案:

答案 0 :(得分:1)

使用StaticResource和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/