【问题标题】:How to bind an image source in bin/debug? [duplicate]如何在 bin/debug 中绑定图像源? [复制]
【发布时间】:2021-09-03 17:49:25
【问题描述】:

XAML 代码:

<ListView x:Name="Toolbar" Grid.Row="1" ItemsSource="{Binding List}">
    <ListView.ItemTemplate>
        <DataTemplate>
        <StackPanel  MouseLeftButtonDown="Lamp_Click" Name="Lamp" Background="White" Width="34" Height="35">
            <Grid Height="30">
                <Image  Source="images/{Binding Path}">
                    
                </Image>
                <TextBlock Text="{Binding Name}" FontSize="7" TextAlignment="Center" Margin="-1,19,1,-12"></TextBlock>
            </Grid>
        </StackPanel>
       
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

C#代码:

public class MyClass
{
    public static List<ViewModel> List{ get; set; } = GetAll();
    
    public static List<ViewModel> GetAll()
    {
       // get records from data base.

    }
}

此代码有语法错误。如何将 images/{Binding path} 更改为有效。为什么这段代码有错误?我真的很困惑。请帮帮我。

【问题讨论】:

  • 显示 ViewModel 类型的实现。

标签: c# wpf xaml


【解决方案1】:
<Image  Source="images/{Binding Path}">

XAML 不支持你正在做的这种半绑定的事情,你要么绑定一些东西,要么不绑定。即使这样做了,它也不会那样工作,因为Image.Source 不是string,而是ImageSource

相反,您需要创建一个转换器,通过实例化 BitmapImage 并将其源设置为异步加载图像,将您的 Path 绑定(字符串)转换为 ImageSource

【讨论】:

  • 一个普通的字符串或 Uri 就足够了。绑定本身将调用所需的转换器。
  • StringFormat 不足以执行连接,如果这就是你的意思。隐式转换器在执行转换之前不使用它。你需要一个转换器。
  • 存在从stringUribyte[]ImageSource 的隐式转换,由 ImageSourceConverter - 一个 TypeConverter 类提供。您不需要绑定转换器。
  • 在没有转换器的情况下随意尝试,我试过了,但它不起作用。还是您没有阅读问题并且他想将字符串附加到绑定的问题?
  • 绑定无效 - 正如您正确指出的那样。它应该是Source="{Binding Path}",其中images/ 前缀成为相对或绝对文件路径或资源文件包URI 或其他任何由Path 属性返回的部分。该绑定将在没有转换器的情况下工作。您的答案中的“不起作用”部分是完全错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 2010-11-18
相关资源
最近更新 更多