使用文件路径存储在“应用程序设置”中的图像

时间:2010-03-27 12:14:17

标签: wpf filepath

我正在尝试开发一个使用大量图像的应用程序,这些图像存储在单独的远程文件位置中。 UI元素的文件路径存储在“应用程序设置”中。虽然我理解如何从C#中的Settings中访问和使用文件路径(Properties.Settings.Default.pathToGridImages +“OK.png”),但我无法弄清楚如何利用WPF中的设置路径,以及如果我包含文件路径,似乎只能访问该文件,例如:

<Grid.Background>
     <ImageBrush ImageSource="C:\Skins\bottomfill.png" TileMode="Tile" />
</Grid.Background>

我原以为在WPF中将“Properties.Settings.Default.pathToGridImages”和“bottomfill.png”连接在一起可以像在C#中完成一样。有谁能指出我正确的方向?

1 个答案:

答案 0 :(得分:2)

您可以使用MultiBinding和值转换器执行此操作。首先,使用多重绑定将图像源绑定到基本路径,并使用图像名称:

<ImageBrush>
    <ImageBrush.ImageSource>
        <MultiBinding Converter="{StaticResource MyConverter}">
            <Binding Source="{StaticResource MySettings}" Path="Default.FilePath" />
            <Binding Source="ImageName.png"></Binding>
        </MultiBinding>
    </ImageBrush.ImageSource>
</ImageBrush>

然后,您需要一个实现IMultiValueConverter的转换器,并将路径的两个部分组合在一起,并使用ImageSourceConverter或创建新的BitmapImage创建图像:

class MyConverter: IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // Concatenate the values.
        string filename = Path.Combine(values[0].ToString(), values[1].ToString());

        // You can either use an ImageSourceConverter
        // to create your image source from the path.
        ImageSourceConverter imageConverter = new ImageSourceConverter();
        return imageConverter.ConvertFromString(filename);

        // ...or you can create a new bitmap with the combined path.
        return new BitmapImage(new Uri(filename, UriKind.RelativeOrAbsolute));
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        // No need to implement the convert back as this will never be used in two way binding.
        throw new NotImplementedException();
    }
}

显然,您需要向XAML中的CLR内容声明名称空间和资源,以便您可以访问它(如果您将设置和转换器类称为不同的,请确保将其更改为匹配):

...
xmlns:local ="clr-namespace:WpfApplication1">
<Window.Resources>
    <local:MyConverter x:Key="MyConverter"></local:MyConverter>
    <local:MySettings x:Key="MySettings"></local:MySettings>
</Window.Resources>

我已经测试过它并且工作正常。

[另一种方法是将ImageSource属性绑定到数据上下文中的一个属性,该属性组合了C#代码中的路径,但这取决于您如何设置datacontexts,因此可能不合需要很多情况。]