【问题标题】:Binding to BitmapImage绑定到 BitmapImage
【发布时间】:2013-12-07 10:32:39
【问题描述】:
    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();

图像没有显示 - 为什么?

【问题讨论】:

    标签: c# xaml data-binding windows-8 datacontext


    【解决方案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));
                }
            }
    

    【讨论】:

      【解决方案2】:

      Thumbnail 类没有公共构造函数,没有实现 INotifyPropertyChanged 成员(在您的示例中根本不需要)。 XAML 应该是:

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

      【讨论】:

        猜你喜欢
        • 2015-06-26
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2019-01-24
        • 1970-01-01
        • 2021-11-06
        • 2017-03-29
        相关资源
        最近更新 更多