Binding to BitmapImage

孤人 提交于 2020-01-05 03:56:06

问题


    public class Thumbnail : INotifyPropertyChanged
    {
        public BitmapImage testimage { get; set; }
        Thumbnail()
        {
            testimage = new BitmapImage(new Uri("http://www.diseno-art.com/news_content/wp-content/uploads/2012/09/2013-Jaguar-F-Type-1.jpg"));
        }
    }

And a image element in a custom control:

<Image x:Name="previewImage" x:FieldModifier="public" Margin="8" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="{Binding Path=thumbnail.testimage}" Stretch="Fill" />

When i create a control, i do this:

MyControl MC = new MyControl();
MC.DataContext = new Thumbnail();

And image doesn't show up - why?


回答1:


XAML:

<Image x:Name="previewImage" x:FieldModifier="public" Margin="8" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="{Binding Path=testimage}" Stretch="Fill" />

code (cleaner):

 public class Thumbnail : INotifyPropertyChanged
        {
            private BitmapImage tmpbmp;
            public BitmapImage testimage { get { return tmpbmp; } set { tmpbmp = value; OnPropertyChanged("testimage"); } }
            public Thumbnail()
            {
                tmpbmp = new BitmapImage(new Uri("http://www.diseno-art.com/news_content/wp-content/uploads/2012/09/2013-Jaguar-F-Type-1.jpg"));
            }


            public event PropertyChangedEventHandler PropertyChanged;

            protected virtual void OnPropertyChanged(string propertyName)
            {
                PropertyChangedEventHandler handler = PropertyChanged;
                if (handler != null)
                    handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }



回答2:


Thumbnail class doesn't have public constructor, doesn't implement INotifyPropertyChanged members (not needed at all in your example). And XAML should be:

<Image x:Name="previewImage" x:FieldModifier="public" Margin="8" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="{Binding Path=testimage}" Stretch="Fill" />


来源:https://stackoverflow.com/questions/20146657/binding-to-bitmapimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!