gpt4 book ai didi

wpf - 通过 wpf 中的属性绑定(bind)图像源

转载 作者:行者123 更新时间:2023-12-04 09:36:16 25 4
gpt4 key购买 nike

我正在尝试使用图像源(.jpg)显示图标。我在 View 模型中创建了一个 Icon 属性并尝试为其分配图像的路径,但我在 View 中看不到任何图像。我尝试将路径转换为位图图像,但不起作用。我在这里有什么遗漏吗?

<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}"/>
<Image Source="{Binding Path=Icon}"></Image>
</StackPanel>




BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.UriSource = new Uri("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg", UriKind.Absolute);
img.EndInit();
Icon = img;

最佳答案

我自己遇到过一次,虽然可能不是最好的解决方案,但以下对我有用。

1. 将图片添加到您的项目中,例如:

  • 为您的项目创建一个文件夹 images/icons 并在其中添加图像。
  • 将图像的构建操作设置为内容(如果较新则复制)

  • 2. 创建一个 ImageSource 属性:
        public ImageSource YourImage
    {
    get { return _yourImage; }
    set
    {
    _yourImage = value;
    NotifyOfPropertyChange(() => YourImage);
    }
    }

    (注:我用caliburn micro辅助绑定(bind))

    3. 像这样更新 ImageSource:
                if(!string.IsNullOrEmpty("TheImageYouWantToShow"))
    {
    var yourImage = new BitmapImage(new Uri(String.Format("Images/Icons/{0}.jpg", TheImageYouWantToShow), UriKind.Relative));
    yourImage.Freeze(); // -> to prevent error: "Must create DependencySource on same Thread as the DependencyObject"
    YourImage = yourImage;
    }
    else
    {
    YourImage = null;
    }

    4. 将源属性绑定(bind)到 YourImage 属性:

    (你已经这样做了)

    关于wpf - 通过 wpf 中的属性绑定(bind)图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14358553/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com