Sana
Sana

Reputation: 147

WPF and databinding issue

public ImageSource imagesource
{
   get
   {
      string constring=@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource='C:\picdata.mdb'";
      OleDbConnection cn = new OleDbConnection(constring);

      cn.Open();
      OleDbDataAdapter da = new OleDbDataAdapter("select * from picdata", cn);
      DataSet ds = new DataSet();
      da.Fill(ds);
      cn.Close();

      var Img = new BitmapImage();
      Img.BeginInit();
      byte[] content = (byte[])ds.Tables[0].Rows[0].ItemArray[0];
      MemoryStream stream = new MemoryStream(content);
      Img.StreamSource = stream;
      Img.EndInit();

      return Img;
   }
}

XAML FILE

<my:DataGrid AutoGenerateColumns="True" Margin="308,12,255,50" Name="dataGrid3"  >
    <my:DataGridTemplateColumn Header="Image" >
        <my:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Image Name="display" Margin="201,29,0,0" Stretch="Fill" Source="{Binding imageSource}">      </Image> 
            </DataTemplate>
        </my:DataGridTemplateColumn.CellTemplate>
    </my:DataGridTemplateColumn>
</my:DataGrid>

The property imagesource is not invoked. Do you have any suggestions?
I have successfully done the conversion and binding using C# and DataGridView but I am unable to figure it out using WPF. I am completely new to WPF so any help would be greatly appreciated.
How else could I successfully bind the access database containing pictures (conversion required) to a DataGrid? Why isn't the imagesource property being executed?

Upvotes: 0

Views: 426

Answers (1)

Jens H
Jens H

Reputation: 4632

I strongly suggest you to read some tutorials on WPF. It looks like you need some WPF basic knowledge. There are so many reasons that your code will not work...

I recommend this one for the WPF DataGrid and WPF 4 Unleashed (Amazon.com) as a good reading about WPF in general.

  • Your ViewModel needs to implement the INotifyChanged interface so that the UI will know where and when to look for changed properties.

  • In the setter - not the getter - you need to call a PropertyChangedEvent that notifies the UI to react to it.

  • Too much code for just a getter. Your database connection will be opened each time you call the property getter. A getter should just return a simple value without accessing expensive resources. (Hava a look at Microsoft's Rico Marian's blog about this topic here.)

Upvotes: 1

Related Questions