2016-12-23 3 views
0

働いていません。 しかしImageコントロールには何も表示されません。バインディングImageコントロールの「ソース」プロパティは、私はXAML</em>を通じて<strong>ソースに<strong>画像</strong>制御<em>の</strong>プロパティをバインドしようとしています

XAML:

<Window x:Class="ImageSourceBinding.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <StackPanel> 
     <Image Name="MyImage1" Width="32" Height="32" Source="{Binding MyImageSource}"/> 
     <Image Name="MyImage2" Width="32" Height="32" /> 
    </StackPanel> 
</Window> 

コードの後ろ:

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    ImageSource MyImageSource; 
    String  FilePath = @"C:\Users\UserName\Documents\Map.txt"; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 

     System.Drawing.Icon ExtractedIcon = System.Drawing.Icon.ExtractAssociatedIcon(FilePath); 
     MyImageSource = Imaging.CreateBitmapSourceFromHIcon(ExtractedIcon.Handle, new Int32Rect(0, 0, 32, 32), BitmapSizeOptions.FromEmptyOptions()); 
     ExtractedIcon.Dispose(); 

     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs("MyImageSource")); 

     this.Icon  = MyImageSource; //This is Working 
     //MyImage2.Source = MyImageSource; //and this too. 
    } 
} 

私は、ウィンドウのアイコンを変更するにはMyImageSourceを使用することができます。 また、コードビハインドからソースを設定すると、イメージが正しく表示されます。

答えて

4

PropertyChangedと明らかに正しいデータコンテキストを使用しているため、MyImageSourceの変更についてバインディングに通知されますが、MyImageSourceはプライベートでプロパティではないため、アクセスできません。

MyImageSourceを定義し、これを使用してみてください:

public ImageSource MyImageSource { get; private set; } 
+0

例外があります。 – Gaurav

+0

私は例外を持っています。 [System.Windows.Markup.XamlParseException] \t {''指定されたバインディング制約に一致する 'ImageSourceBinding.MainWindow'型のコンストラクタを呼び出すと例外がスローされました。行番号 '3'と行位置 '9'。 "} – Gaurav

+0

InnerExceptionはありますか? XamlParseExceptionは、WPFウィンドウのコンストラクタの例外に表示されるため、実際には何かになる可能性があります。 –

1

あなたが唯一のプロパティに、フィールドにバインドすることはできません。このようなプロパティを作成し、コードのプロパティでコードに割り当てます:

private ImageSource _myImageSource; 
public ImageSource MyImageSource { 
    get { return _myImageSource; } 
    set { 
     if (value != _myImageSource) 
     { 
      _myImageSource = value; 
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyImageSource))); 
     } 
    } 
} 

public MainWindow() 
{ 
    InitializeComponent(); 
    this.DataContext = this; 

    System.Drawing.Icon ExtractedIcon = System.Drawing.Icon.ExtractAssociatedIcon(FilePath); 
    MyImageSource = Imaging.CreateBitmapSourceFromHIcon(ExtractedIcon.Handle, new Int32Rect(0, 0, 32, 32), BitmapSizeOptions.FromEmptyOptions()); 
    ExtractedIcon.Dispose(); 

    this.Icon  = MyImageSource; //This is Working 
} 

これでバインドする必要があります。

DataContext = this;はお勧めしません。別のviewmodelクラスを使用することをお勧めします。しかし、これは一度あなたを殺しません。

関連する問題

 関連する問題