C# WPF-将图像绑定到代码隐藏中的相对URI

C# WPF-将图像绑定到代码隐藏中的相对URI,c#,wpf,image,binding,relative-path,C#,Wpf,Image,Binding,Relative Path,我为DataGrid对象创建了一个ImageColumn。但是,我不知道如何将相对图像路径绑定到它。 我需要这样的东西,但用C 这是我当前的绑定 Binding b = new Binding(); b.Path = new PropertyPath("IMAGE_PATH"); b.RelativeSource = new RelativeSource(RelativeSourceMode.Self); 编辑: “IMAGE_PATH”是DataGrid的另一列。它保存图像文件的相对路径(相

我为DataGrid对象创建了一个ImageColumn。但是,我不知道如何将相对图像路径绑定到它。 我需要这样的东西,但用C

这是我当前的绑定

Binding b = new Binding();
b.Path = new PropertyPath("IMAGE_PATH");
b.RelativeSource = new RelativeSource(RelativeSourceMode.Self);
编辑: “IMAGE_PATH”是DataGrid的另一列。它保存图像文件的相对路径(相对于应用程序根)。 如果我添加一个绝对路径,它就会工作。但不是相对路径

有关该项目的更多信息: datagrid保存项目信息(零件号、图像、描述、价格)。用户应该能够添加图像。图像将复制到应用程序中,如下所示:

应用程序\u ROOT/Images/Item/file.png

此路径将保存在数据库的“图像路径”列中

Images/Item/file.png

稍后,此路径将用于在ImageColumn中绘制图像。然而,这是一个相对路径,它只是在一个绝对路径下工作


希望这能让事情变得更清楚。谢谢大家!

有一些问题需要解决:

  • 图像的SourceProperty需要一个ImageSource对象,我猜在您的示例中,DataContext属性“Image\u PATH”的类型是string
  • Binding RelativePath.Self意味着查找控件的“own”属性,您可以设置绑定,除非您有一个自定义图像控件,其中DP“Image_PATH”为字符串,在内部将其转换为BitmapImage,否则这将不起作用
  • 您没有提供ViewModel和Datagrid的ItemsSource绑定。您需要一个具有ObservableCollection属性的ViewModel,并将其绑定到DataGrid ItemsSource属性
  • 类“YourType”需要一个属性,该属性包含要在DataGridTemplateColumn的绑定中使用的BitmapImage
  • 我倾向于将图像构建为资源(Sol.Explorer->Image->build Action…),因此“Pack”-Uri get更简单,您不必将图像复制到outputfolder中
  • 这里是一个工作版本(可能不是完美的,但功能强大)

    窗口xaml:

    <Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid AutoGenerateColumns="False"  
                  Name="dg1" ItemsSource="{Binding Items}"
                  CanUserAddRows="False" />
    </Grid>
    
    类别1.cs

    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    
    namespace WpfApp1
    {
    class Class1
    {
        public static DataGridTemplateColumn createImageColumn(string header, Size s)
        {
            Binding b = new Binding("img");
    
            DataTemplate dt = new DataTemplate();
            dt.DataType = typeof(Class2);
            var dtFactory = new FrameworkElementFactory(typeof(StackPanel));
            dtFactory.Name = "stack";
            dtFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
    
    
            FrameworkElementFactory imageHolder = new 
            FrameworkElementFactory(typeof(Image));
            imageHolder.SetValue(Image.SourceProperty, b);
            imageHolder.SetValue(Image.WidthProperty, s.Width);
            imageHolder.SetValue(Image.HeightProperty, s.Height);
            imageHolder.SetValue(Image.HorizontalAlignmentProperty, 
            HorizontalAlignment.Center);
            imageHolder.SetValue(Image.VerticalAlignmentProperty, 
            VerticalAlignment.Center);
    
            dtFactory.AppendChild(imageHolder);
    
            var  imageColumn = new DataGridTemplateColumn();
            imageColumn.Header = header;
            imageColumn.CellTemplate = dt;
            return imageColumn;
        }
    
    }
    }
    
    类别2

    using System;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Windows.Media.Imaging;
    
    namespace WpfApp1
    {
    class Class2 : INotifyPropertyChanged
    {
    
        private string _IMAGE_PATH;
        public string IMAGE_PATH
        {
            get { return _IMAGE_PATH; }
            set
            {
                _IMAGE_PATH = value;
                NotifyPropertyChanged();
                img = new BitmapImage(
                    new Uri("pack://application:,,,/Images/" + value));
            }
        }
    
        private BitmapImage _img;
        public BitmapImage img
        {
            get
            {
    
                return _img;
            }
            set
            {
                _img = value;
                NotifyPropertyChanged();
            }
        }
    
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
    
        private string _value;
        public string value
        {
            get { return _value; }
            set { _value = value; NotifyPropertyChanged(); }
        }
    }
    }
    
    以及ViewModel VM.cs

    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    
    namespace WpfApp1
    {
    class VM : INotifyPropertyChanged
    {
    
        public VM()
        {
            Items = new ObservableCollection<Class2>();
        }
    
        private ObservableCollection<Class2> _Items;
        public ObservableCollection<Class2> Items
        {
            get { return _Items; }
            set { _Items = value; NotifyPropertyChanged(); }
        }
    
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    }
    
    使用系统;
    使用System.Collections.ObjectModel;
    使用系统组件模型;
    使用System.Runtime.CompilerServices;
    命名空间WpfApp1
    {
    类VM:INotifyPropertyChanged
    {
    公共虚拟机()
    {
    Items=新的ObservableCollection();
    }
    私人可观测收集项目;
    公共可观测收集项目
    {
    获取{return\u Items;}
    设置{u Items=value;NotifyPropertyChanged();}
    }
    公共事件属性更改事件处理程序属性更改;
    私有void NotifyPropertyChanged([CallerMemberName]字符串propertyName=”“)
    {
    if(PropertyChanged!=null)
    {
    PropertyChanged(这是新的PropertyChangedEventArgs(propertyName));
    }
    }
    }
    }
    
    试试这个

                                 BitmapImage _image = new BitmapImage();
                                _image.BeginInit();
                                _image.CacheOption = BitmapCacheOption.None;
                                _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                                _image.CacheOption = BitmapCacheOption.OnLoad;
                                _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                                _image.UriSource = new Uri(imageSource, UriKind.RelativeOrAbsolute);
                                _image.EndInit();
                                ImageName.Source = _image;
    

    什么是图像路径?它是文件名还是包含文件名的属性,还是包含URI的属性,还是包含图像的属性?你所说的相对路径是什么意思?您是指相对URI还是相对绑定路径?您可能想阅读本页,但不清楚您为什么认为需要绑定。为什么不简单地将BitmapImage分配给源属性?比如
    imageHolder.SetValue(Image.SourceProperty,新的位图图像(新的Uri(…))using System;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Windows.Media.Imaging;
    
    namespace WpfApp1
    {
    class Class2 : INotifyPropertyChanged
    {
    
        private string _IMAGE_PATH;
        public string IMAGE_PATH
        {
            get { return _IMAGE_PATH; }
            set
            {
                _IMAGE_PATH = value;
                NotifyPropertyChanged();
                img = new BitmapImage(
                    new Uri("pack://application:,,,/Images/" + value));
            }
        }
    
        private BitmapImage _img;
        public BitmapImage img
        {
            get
            {
    
                return _img;
            }
            set
            {
                _img = value;
                NotifyPropertyChanged();
            }
        }
    
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
    
        private string _value;
        public string value
        {
            get { return _value; }
            set { _value = value; NotifyPropertyChanged(); }
        }
    }
    }
    
    using System;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    
    namespace WpfApp1
    {
    class VM : INotifyPropertyChanged
    {
    
        public VM()
        {
            Items = new ObservableCollection<Class2>();
        }
    
        private ObservableCollection<Class2> _Items;
        public ObservableCollection<Class2> Items
        {
            get { return _Items; }
            set { _Items = value; NotifyPropertyChanged(); }
        }
    
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    }
    
                                 BitmapImage _image = new BitmapImage();
                                _image.BeginInit();
                                _image.CacheOption = BitmapCacheOption.None;
                                _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                                _image.CacheOption = BitmapCacheOption.OnLoad;
                                _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                                _image.UriSource = new Uri(imageSource, UriKind.RelativeOrAbsolute);
                                _image.EndInit();
                                ImageName.Source = _image;