绑定到的BitmapImage(Binding to BitmapImage)

2019-10-19 01:31发布

    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"));
        }
    }

而在自定义控制图像元素:

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

当我创建一个控制,我这样做:

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

和图像显示不出来-为什么?

Answer 1:

XAML:

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

代码(清洁器):

 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));
            }
        }


Answer 2:

缩略图类没有公共构造方法,不执行INotifyPropertyChanged成员(根本不需要在你的例子)。 和XAML应该是:

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


文章来源: Binding to BitmapImage