2012-07-18 82 views
1

我將圖像Source綁定到我的代碼中的BitmapImage,但它不顯示。圖像源綁定不起作用

XAML:

<Window x:Class="bleh.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" 
    mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="600" d:DesignWidth="600"> 
<Grid x:Name="LayoutRoot"> 
    <Image x:Name="current" HorizontalAlignment="Center" Stretch="None" VerticalAlignment="Center" Source="{Binding Picture}" /> 
</Grid> 
</Window> 

和我的CS:

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    /// <summary> 
    /// Event implementing INotifyPropertyChanged interface. 
    /// </summary> 
    public event PropertyChangedEventHandler PropertyChanged; 

    public BitmapImage Picture { get; set; } 

    public MainWindow() 
    { 
     Uri uri = new Uri("Images/xpto.jpg", UriKind.Relative); 
     this.Picture = new BitmapImage(uri); 
     InitializeComponent(); 
     //setup(); 
    } 
} 

奇怪的是,窗口與圖像的大小打開,但我看不到圖像。我也嘗試在xaml中手動分配,並且它可以工作。

current.source="Images/xpto.jpg"也有效。

回答

1

您的視圖(MainWindow)的DataContext未設置,因此沒有要綁定的「圖片」屬性。如果您希望視圖綁定到自己,請向您的MainWindow構造函數中添加

this.DataContext = this; 

+0

工程,你是如何做到這一點在XAML?我在窗口標籤上試過'DataContext =「MainWindow」'並且看起來不起作用 – GriffinHeart 2012-07-19 00:17:15

+1

爲你的窗口命名(例如x:Name =「Main」),然後使用Source =「{Binding Picture,ElementName = Main}「 – lesscode 2012-07-19 00:23:32

+0

請注意,儘管您可以綁定Xaml中窗口的DataContext(或其中的任何元素),但您必須綁定到視圖中已有的東西(因爲當然,您沒有DataContext ...) – lesscode 2012-07-19 00:29:30

0

您沒有爲屬性實現INotifyPropertyChanged圖片: public BitmapImage Picture {get;組; } 你必須做的:

BitmapImage _picture; 
public BitmapImage Picture { 
get {return _picture;} 
set{ 
     _picture=value; 
     OnPropertyChanged("Picture"); 
    }` 
} 
+0

這解決了我的問題。 +1 – MiloDC 2015-06-05 02:11:50