How do I work with images in a portable class library targeting Windows Store Apps and WP7,WP8,WPF?

后端 未结 7 1037
忘掉有多难
忘掉有多难 2020-12-31 00:23

I am working on a first PCL that targets : WSA (Windows Store Application), WPF,WP7,WP8. We can say that it is a rolerdex kind of application, you have contacts , they have

7条回答
  •  礼貌的吻别
    2020-12-31 01:11

    you can put the image on the view model as type "object" and use an interface (which is injected) to create the bitmap.

    public interface IBitMapCreator
    {
        object Create(string path);
    }
    
    public class MyViewModel
    {
        private bool _triedToSetThumb;
        private readonly IBitMapCreator _bc;
    
        public MyViewModel(IBitMapCreator bc, string path)
        {
            _bc = bc;
            SetThumb(path);
        }
    
        public object Thumb { get; private set; }
    
        private void SetThumb(string path)
        {
            try
            {
                if (!_triedToSetThumb)
                {
                    string ext = Path.GetExtension(path).ToUpper();
    
                    if (
                        ext == ".JPG" ||
                        ext == ".JPEG" ||
                        ext == ".PNG" ||
                        ext == ".GIF" ||
                        ext == ".BMP" ||
                        false
                        )
                    {
                        Thumb = _bc.Create(path);
                        OnPropertyChanged(new PropertyChangedEventArgs("Thumb"));
                    }
                }
            }
            finally
            {
                _triedToSetThumb = true;
            }
        }
    
    }
    

    in the WPF version, you could do this

    class BitMapCreator : IBitMapCreator
    {
        public object Create(string path)
        {
            return BitmapFrame.Create(new Uri(path));
        }
    } 
    

    By using this method you can data bind right to the image and do not need a converter.

提交回复
热议问题