實現效果:
實現遇到的問題:
當時想要實現如圖所示‘合格率’所示的效果,我的第一個想法就是使用wpf的轉換器,可是接下來問題來了,我這個是通過數值來判斷是否合格,什么控件可以做到既可以綁定圖片類型的,又可以綁定數值類型的;還有此時的當值綁定肯定不行,可以多值綁定嗎?
解決方案:
通過自己的聯想,以及網上查詢,我終於解決了我的兩個疑問,下面我就直奔主題!
- “什么控件可以做到既可以綁定圖片類型” =》 我選擇了Label,這個啥類型的都可以綁定
- “多值綁定可以嗎” =》 可以,使用“MultiBinding”綁定(對於單值,直接使用Binding)
關鍵代碼:
前台:
<DataGridTemplateColumn Header="合格率">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<!--<Label Content="{Binding Path=hege,Converter={StaticResource dc_departallperson}}"/>-->
<Label>
<Label.Content>
<MultiBinding Converter="{StaticResource dc_dallpersonicon}">
<Binding Path="hege"></Binding>
<Binding Path="userrealname"></Binding>
</MultiBinding>
</Label.Content>
</Label>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="合格率" Binding="{Binding hege,Converter={StaticResource dc_departallperson}}" />
轉換器中代碼:
(通過判斷合格率顯示對應圖片)
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
byte[] img = null;
if (!string.IsNullOrEmpty(value.ToString()))
{
img = (byte[]) value;
//從數據庫中獲取圖片數據轉換為字節數組(注意:不用用這種方式轉換為字節數組,這種轉換有問題,我之前一直出不來效果 byte[] img = System.Text.ASCIIEncoding.ASCII.GetBytes(ds.Tables[0].Rows[0]["pic"].ToString()); 現在修改了,就能出來效果了,這個問題還挺讓人糾結的呢,所以大家要注意哦!)
}
if (img == null)
{
return "/HDMSWpfManage;component/templet/images/defaulthead.jpg";
}
return ShowSelectedIMG(img); //以流的方式顯示圖片的方法
}
//轉換器中二進制轉化為BitmapImage datagrid綁定仙石的
private BitmapImage ShowSelectedIMG(byte[] img)
{
BitmapImage newBitmapImage = null;
if (img != null)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(img);//img是從數據庫中讀取出來的字節數組
ms.Seek(0, System.IO.SeekOrigin.Begin);
newBitmapImage = new BitmapImage();
newBitmapImage.BeginInit();
newBitmapImage.StreamSource = ms;
newBitmapImage.EndInit();
}
return newBitmapImage;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}