Datagrid图像TemplateColumn源绑定wpf

时间:2017-05-10 12:13:48

标签: c# wpf image binding datagrid

我使用Datagrid显示用户信息,除了要显示用户图像的列外,每个文件列的工作正常。 这是xaml中的Datagrid

 <DataGrid Name="UserListDataGrid" Margin="10,50,10,10"  
                                                  AutoGenerateColumns="False" 
                                                  EnableRowVirtualization="False"  
                                                  ItemsSource="{Binding convUsrList}"
                                                  CellStyle="{StaticResource Body_Content_DataGrid_Centering}"
                                                  RowDetailsVisibilityMode="VisibleWhenSelected" 
                                                  CanUserSortColumns="False" 
                                                  CanUserAddRows="False" 
                                                  CanUserResizeRows="False" 
                                                  CanUserReorderColumns="False"
                                                  IsReadOnly="True" 
                                                  Width="900"
                                                  Opacity="0"
                                                  Foreground="Black" 
                                                  GridLinesVisibility="None"
                                                  HeadersVisibility="All"
                                                  HorizontalContentAlignment="Center"  
                                                  Background="Gray" 
                                                  BorderBrush="Transparent"
                                                  ScrollViewer.HorizontalScrollBarVisibility="Auto" >
                                            <DataGrid.Columns>
                                                                                                  <DataGridTemplateColumn  >
                                                    <DataGridTemplateColumn.CellTemplate >
                                                        <DataTemplate>
                                                            <Image Source="{Binding PhotoSource}" Width="60" Height="60" />
                                                        </DataTemplate>
                                                    </DataGridTemplateColumn.CellTemplate>
                                                    <DataGridTemplateColumn.HeaderTemplate>
                                                        <DataTemplate>
                                                            <TextBlock Text="{Binding DataContext[10],RelativeSource={RelativeSource AncestorType=DataGrid}}" Width="60"/>
                                                        </DataTemplate>
                                                    </DataGridTemplateColumn.HeaderTemplate>
                                                </DataGridTemplateColumn>



                                                <DataGridTextColumn   Binding="{Binding FirstName}"  >
                                                    <DataGridTextColumn.HeaderTemplate>
                                                        <DataTemplate>
                                                            <TextBlock Text="{Binding DataContext[4],RelativeSource={RelativeSource AncestorType=DataGrid}}" Width="60"/>
                                                        </DataTemplate>
                                                    </DataGridTextColumn.HeaderTemplate>
                                                </DataGridTextColumn>....

我以base64字符串格式从我的数据库中获取用户照片,使用此函数转换为BitmapImage

 public static BitmapImage getImage(string image)
    {
        byte[] b = Convert.FromBase64String(image);
        MemoryStream mst = new MemoryStream(b, 0, b.Length);
        BitmapImage bmp = new BitmapImage();
        bmp.BeginInit();
        bmp.CacheOption = BitmapCacheOption.OnLoad;
        bmp.StreamSource = mst;
        bmp.EndInit();
        return bmp;
    }

最后创建一个user列表(这是一个显示用户信息的类,如firstname(string)// lastname(string)// ... // PhotoSource(BitmapImage))并将其提供给数据网格,如下所示

 UserListDataGrid.ItemsSource = convUsrList;

正如我所说的一切都在Datagrid上展示,除了用户形象,你能帮我吗? enter image description here

这是用户类:

public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool IsActive { get; set; }
        public int UserTypeId { get; set; }
        public int ShopId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }
        public string CellNumber { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public bool Gender { get; set; }
        public string Photo { get; set; }
        public string SecurityAnswer { get; set; }
        public int SecurityQuestionId { get; set; }
        public long LastSecurityCheck { get; set; }
        public DateTime? DeletedAt { get; set; }
        public DateTime? ExpireDate { get; set; }
    }
    public class UserDatagrid:User
    {
        public BitmapImage PhotoSource;
    }

以下是convUsrList的声明方式:

public void loadUserTable()
    {
        UserManagement um = new UserManagement(db);
        List<User> userlist = um.getUserlist(um.GetUsers());

        if (db.IsRTL)
            UserListDataGrid.FlowDirection = FlowDirection.RightToLeft;
        else
            UserListDataGrid.FlowDirection = FlowDirection.LeftToRight;
        string s = "";
        dataBase.AppNotifyDic.TryGetValue("userTbl", out s);
        string[] contbl = s.Split('-');
        UserListDataGrid.DataContext = new List<string>() { contbl[0], contbl[1], contbl[2], contbl[3], contbl[4], contbl[5], contbl[6], contbl[7], contbl[8], contbl[9], contbl[10], contbl[11], contbl[12], contbl[13], contbl[14], contbl[15], contbl[16] };
        List<UserDatagrid> convUsrList = new List<UserDatagrid>();
        for (int i=0;i<userlist.Count;i++)
        {
            convUsrList.Add(tools.convertUserForDataGrid(userlist[i]));
        }
        UserListDataGrid.ItemsSource = convUsrList;

    }

并且convertUserForDataGrid如下:

 public static UserDatagrid convertUserForDataGrid(User origUser)
    {
        UserDatagrid convUser = new UserDatagrid();

        convUser.Id = origUser.Id;
        convUser.UserName = origUser.UserName;
        convUser.Password = origUser.Password;
        convUser.IsActive = origUser.IsActive;
        convUser.UserTypeId = origUser.UserTypeId;
        convUser.ShopId = origUser.ShopId;
        convUser.FirstName = origUser.FirstName;
        convUser.LastName = origUser.LastName;
        convUser.PhoneNumber = origUser.PhoneNumber;
        convUser.CellNumber = origUser.CellNumber;
        convUser.Address = origUser.Address;
        convUser.Email = origUser.Email;
        convUser.Gender = origUser.Gender;
        convUser.Photo = origUser.Photo;
        convUser.SecurityAnswer = origUser.SecurityAnswer;
        convUser.SecurityQuestionId = origUser.SecurityQuestionId;
        convUser.LastSecurityCheck = origUser.LastSecurityCheck;
        convUser.DeletedAt = origUser.DeletedAt;
        convUser.ExpireDate = origUser.ExpireDate;
        convUser.PhotoSource = (string.IsNullOrEmpty(origUser.Photo)) ? (convUser.Gender)? setImagesource("male.png"): setImagesource("Female.png") : getImage(origUser.Photo);
         return convUser;
    }

1 个答案:

答案 0 :(得分:1)

因为绑定系统使用Reflection来查找

  

DataContext中的属性(即您的VM)

希望这会有所帮助。

币:link1