【问题标题】:Binding Image Dynamically in Metro App在 Metro App 中动态绑定图像
【发布时间】:2012-12-04 04:15:08
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你想将它绑定到什么?后面代码中的一个属性
  • 我正在尝试将图像与图像的路径绑定。有可能吗?
  • 路径在哪里,堆栈面板中对象的一部分?
  • 例如 然后我有 String ImagePath { get;放; },所以我添加了集合 public List img = new List(); img.Add(new Topic("image.png)); public Topic(string imgName) ImagePath = imgName;

标签: c# xaml microsoft-metro


【解决方案1】:

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

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

【讨论】:

  • 对不起,你能解释一下 ImagePath 包含什么吗?
  • 嗯,我不知道,但这不起作用。我在 app.xaml 中添加了 path=Assets\f2f.png, StaticResource imageConverter, 。但我得到的是空白图像:/
  • 检查你的图像的构建动作
【解决方案2】:

试试这个:

<Image> 
    <Image.Source> 
        <BitmapImage UriSource=”{Binding ImagePath}” /> 
   </Image.Source> 
</Image> 

【讨论】:

  • 我不能在 中使用
【解决方案3】:

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

【讨论】:

  • 如何设置数据上下文?我的意思是指绑定的来源
【解决方案4】:

你需要在new Uri(BaseUri, Url)中指定BaseUri

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    相关资源
    最近更新 更多