在Metro App中动态绑定图像

Cha*_*gih 5 c# xaml microsoft-metro

我在ImageBrush中有一个ImageSource,它会根据我的数据动态改变.

问题是,我不能直接访问ImageBrush的名称,因为它在DataTemplate中.我知道这是个坏主意,因为在UI中存储数据是一个坏习惯.

如果有人知道如何使用Image上的数据绑定来解决这个问题,我真的很感激.谢谢!!

<DataTemplate>
  <StackPanel Width="250" Height="180" VerticalAlignment="Bottom">
    <StackPanel.Background>
       <ImageBrush ImageSource="{Binding ???}"/>
    </StackPanel.Background>
    ........
  </StackPanel>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

Zdr*_*nev 2

您可以创建一个将路径转换为图像的转换器:

public sealed class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            return new BitmapImage(new Uri((string)value));
        }
        catch 
        {
            return new BitmapImage();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在 XAML 中:

< Image Source="{Binding Path=ImagePath, Converter={StaticResource ImageConverter}}" />
Run Code Online (Sandbox Code Playgroud)