5

我在 ImageBrush 中有一个 ImageSource,它将根据我的数据动态更改。

问题是,我无法直接访问 ImageBrush 的名称,因为它位于 DataTemplate 中。我知道这是个坏主意,因为在 UI 中存储数据是个坏习惯。

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

<DataTemplate>
  <StackPanel Width="250" Height="180" VerticalAlignment="Bottom">
    <StackPanel.Background>
       <ImageBrush ImageSource="{Binding ???}"/>
    </StackPanel.Background>
    ........
  </StackPanel>
</DataTemplate>
4

4 回答 4

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();
    }
}

然后在 XAML 中:

< Image Source="{Binding Path=ImagePath, Converter={StaticResource ImageConverter}}" />
于 2012-12-04T04:23:23.460 回答
0

为什么不使用属性并将控件绑定到属性!您可以将图像的路径设置到属性中,然后将元素绑定到属性

于 2012-12-04T07:27:58.570 回答
0

您需要BaseUrinew Uri(BaseUri, Url)

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

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

还要在 XAML 代码中指定转换器

<Page:Resources>
     <local:ImageConverter x:Key="imageConverter"/>
</Page:Resources>

和转换器在你Image

<Image Source="{Binding Path=ImagePath, Converter={StaticResource imageConverter}}" />
于 2012-12-04T07:33:21.063 回答
0

试试这个:

<Image> 
    <Image.Source> 
        <BitmapImage UriSource=”{Binding ImagePath}” /> 
   </Image.Source> 
</Image> 
于 2012-12-04T05:11:12.970 回答