Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

xaml - Binding image source through property in wpf

I am trying to display an icon using an image source(.jpg). I create a Icon property in view model and try to assign it the path of the image but I do not see any image in the view. I tried converting the path to Bitmap image but doesn't work. Is there anything I am missing here?

<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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I ran into this myself once and, though maybe not the best solution, the following worked for me.

1. Add the images to your project, for example:

  • Create a folder images/icons to your project and add the images there.
  • Set build action of images to Content (copy if newer)

2. Create an ImageSource property:

    public ImageSource YourImage
    {
        get { return _yourImage; }
        set 
        { 
            _yourImage = value;
            NotifyOfPropertyChange(() => YourImage);
        }
    }

(Note: I use caliburn micro to assist in binding)

3. Update the the ImageSource like this:

            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 source attribute to YourImage property:

(you already did this)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...