开发者

Display image in Silverlight4 Datagrid using Entity Framework

I have Employee Entity of northwind database and one of the field of this entity is "Photo" which is of type "Binary".

Now my question is how should i display the "Photo"fields in the Silverlight 4 datagrid so that i can view the employee photo?

What do i need todo in my WCF code or my ModelView Code?

My XAML code is given below:

<navigation:Page x:Class="NorthWind.SMS.UI.Views.EmployeeListing" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="EmployeeListing Page" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="50" MaxHeight="50" MinHeight="50" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid Height="Auto" HorizontalAlignment="Left" Margin="5,5,0,0" Name="grid1" VerticalAlignment="Top" Width="Auto" />
        <TextBlock Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="tbHeader" Text="Employee Listing" VerticalAlignment="Top" FontSize="14" FontFamily="Verdana" TextAlignment="Center" />
        <sdk:DataGrid Grid.Row="1" ItemsSource="{Binding Path=Employees}" AutoGenerateColumns="False" Height="Auto" HorizontalAlignment="Left" Margin="5,5,0,0" Name="dgEmployee" VerticalAlignment="Top" Width="Auto" AlternatingRowBackground="{x:Null}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTemplateColumn Header="Name">
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock> 
                                <Run Text="{Binding EmployeeName.TitleOfCourtesy}"></Run>
                                <Run Tex开发者_JS百科t="{Binding EmployeeName.FirstName}"></Run>
                                <Run Text="{Binding EmployeeName.LastName}"></Run></TextBlock>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>
                <sdk:DataGridTextColumn Binding="{Binding Path=Title}" Header="Title" />
                <sdk:DataGridTextColumn Binding="{Binding Path=HireDate}" Header="HireDate" />
                <sdk:DataGridTextColumn Binding="{Binding Path=BirthDate}" Header="DOB" />
                <sdk:DataGridTextColumn Binding="{Binding Path=HomePhone}" Header="Phone" />
                <sdk:DataGridTextColumn Binding="{Binding Path=City}" Header="City" />
                <sdk:DataGridTextColumn Binding="{Binding Path=Region}" Header="Region" />
                <sdk:DataGridTextColumn Binding="{Binding Path=Country}" Header="Country" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
    </Grid>
</navigation:Page>

My ModelView Code is given below;

private void RefreshEmployees()
        {
            this.serviceClient.GetEmployeesListingCompleted += (s, e) =>
                {
                    this.Employees = e.Result;
                };
            this.serviceClient.GetEmployeesListingAsync();

        }

My WCF code that is getting the data is show below;

[OperationContract]
        public IEnumerable<Employee> GetEmployeesListing()
        {
            using (var context = new NorthwindEntities())
            {
                //context.ContextOptions.LazyLoadingEnabled = false;
                var result = context.Employees.ToList();
                result.ForEach(e => context.Detach(e));
                return result;
            }
        }


I found the answer to my question here is what i did;

Step 1:

WCF code modified to convert the Binary "Photo" field to Jpeg format.

Code is shown below;

[OperationContract]
        public IEnumerable<Employee> GetEmployeesListing()
        {
            List<Employee> empList = new List<Employee>();
            using (var context = new NorthwindEntities())
            {
                //context.ContextOptions.LazyLoadingEnabled = false;
                var result = context.Employees.ToList();
                result.ForEach(e => context.Detach(e));
                //return result;
                foreach (Employee emp in result)
                {
                    Employee e = new Employee();
                    e.EmployeeName.TitleOfCourtesy = emp.EmployeeName.TitleOfCourtesy;
                    e.EmployeeName.FirstName = emp.EmployeeName.FirstName;
                    e.EmployeeName.LastName = emp.EmployeeName.LastName;
                    e.Title = emp.Title;
                    e.HireDate = emp.HireDate;
                    e.BirthDate = emp.BirthDate;
                    e.City = emp.City;
                    e.Region = emp.Region;
                    e.Country = emp.Country;
                    if (emp.Photo != null)
                    {
                        byte[] blob = emp.Photo;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            ms.Write(blob, 78, blob.Length - 78);
                            Bitmap bm = (Bitmap)Image.FromStream(ms);
                            using (MemoryStream msJpg = new MemoryStream())
                            {
                                bm.Save(msJpg, ImageFormat.Jpeg);
                                e.Photo = msJpg.GetBuffer();
                            }
                        }
                    }

                    empList.Add(e);
                }
                return empList;
            }
        }

Step 2:

Create a Image Converter class implementing the IValueConverter interface in your Silverlight project.

Code is shown below;

 public class ByteToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            byte[] pic = value as byte[];
            if (value != null)
            {

                MemoryStream ms = new MemoryStream((byte[])value, false);
                BitmapImage bmi = new BitmapImage();
                bmi.SetSource(ms);
                return bmi;
            }
            else return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

Step 4

In the XAML file where you have your Data grid add a refernce of ByteToImageConverter class like this;

xmlns:src="clr-namespace:NorthWind.SMS.UI.Converters"

Step 5

Add a Static resource details in your XAML file like this;

<UserControl.Resources>
        <src:ByteToImageConverter x:Key="ConvertToImage">
        </src:ByteToImageConverter>
    </UserControl.Resources>

Step 6

Update your datagrid image template like this;

<sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image x:Name="img1" Source ="{Binding Path=Photo, Converter={StaticResource ConvertToImage}}" Width="75" Height="75" Visibility="Visible"/>
                        </DataTemplate>
                    </sdk:DataGridTemplateColumn.CellTemplate>
                </sdk:DataGridTemplateColumn>

This solution is working just fine for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜