首先我们定义一个Student类,有ID,Name,Photo(保存图片路径).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace BindingImage
{
public class Student
{
public int Id { get; set; } public string Name { get; set; } public string Photo { get; set; }
}
}

然后我们写两个有关数据库操作的类,SqlHelper,StudentDAL,因为我们不希望在UI层后台的代码中出现有关数据库的操作,我们定义了这两个类。

上代码:

SqlHelper:

 using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace BindingImage
{
public static class SqlHelper
{
//读取保存在APP.config的链接字符串
public static readonly string connstr =
ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; //执行ExcuteNonQuery方法,返回受影响的行数
public static int ExecuteNonQuery(string sql,
params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteNonQuery();
}
}
}
//返回DataTable结果集
public static DataTable ExecuteDataTable(string sql,
params SqlParameter[] parameters)
{
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(parameters); DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
return dataset.Tables[];
}
}
}
//若数据库中的字段值为Null
public static object FromDbValue(object value)
{
if (value == DBNull.Value)
{
return null;
}
else
{
return value;
}
} //若实体类重的属性值为null
public static object ToDbValue(object value)
{
if (value == null)
{
return DBNull.Value;
}
else
{
return value;
}
}
} }

StudentDAL:

 using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace BindingImage
{
public static class StudentDAL
{ public static Student GetById(int id)
{
DataTable table = SqlHelper.ExecuteDataTable("select * from T_Student2 where Id=@Id",
new SqlParameter("@Id", id));
if (table.Rows.Count <= )
{
return null;
}
else if (table.Rows.Count > )
{
throw new Exception("存在Id重复用户!");
}
else
{
return ToStudent(table.Rows[]);
}
} public static void Update(Student st)
{
SqlHelper.ExecuteNonQuery("update T_Student2 set Name=@Name,Photo=@Photo where Id=@Id",
new SqlParameter("@Name", SqlHelper.ToDbValue( st.Name)),
new SqlParameter("@Photo", SqlHelper.ToDbValue( st.Photo)),
new SqlParameter("@Id",st.Id)); } private static Student ToStudent(DataRow row)
{
Student st = new Student();
st.Id = (int)row["Id"];
st.Name =(string)SqlHelper.FromDbValue(row["Name"]);
st.Photo = (string)SqlHelper.FromDbValue(row["Photo"]);
return st;
}
}
}

UI层:

在学生ID文本框中输入Id,然后显示在此界面中,我们将学生姓名 学生头像保定到相应控件元素上,XAML代码如下

 <Window x:Class="BindingImage.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingImage"
Title="MainWindow" Height="" Width="" Loaded="Window_Loaded" WindowStartupLocation="CenterScreen">
<Window.Resources>
<local:Converter x:Key="con"/>
</Window.Resources>
<Grid Name="gridstudent">
<TextBox x:Name="txtId" HorizontalAlignment="Left" Height="" Margin="66,33,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width=""/>
<TextBox x:Name="txtName" HorizontalAlignment="Left" Height="" Margin="66,105,0,0" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width=""/>
<Image x:Name="imgPhoto" Source="{Binding Photo,Converter={StaticResource con}}" HorizontalAlignment="Left" Height="" Margin="271,105,0,0" VerticalAlignment="Top" Width=""/>
<Button Content="Save" HorizontalAlignment="Left" Margin="126,259,0,0" VerticalAlignment="Top" Width="" Click="Button_Click_1"/>
<Button Content="LoadPhoto" HorizontalAlignment="Left" Margin="405,186,0,0" VerticalAlignment="Top" Width="" Click="Button_Click"/>
<Button Content="Cancel" HorizontalAlignment="Left" Margin="282,259,0,0" VerticalAlignment="Top" Width="" Click="Button_Click_2"/>
<TextBlock HorizontalAlignment="Left" Margin="11,41,0,0" TextWrapping="Wrap" Text="学生ID:" VerticalAlignment="Top" RenderTransformOrigin="-0.159,1.145"/>
<TextBlock HorizontalAlignment="Left" Margin="15,113,0,0" TextWrapping="Wrap" Text="学生姓名:" VerticalAlignment="Top" RenderTransformOrigin="-0.159,1.145"/>
<TextBlock HorizontalAlignment="Left" Margin="204,113,0,0" TextWrapping="Wrap" Text="学生头像:" VerticalAlignment="Top" RenderTransformOrigin="-0.159,1.145"/>
<Button Content="显示" HorizontalAlignment="Left" Margin="204,33,0,0" VerticalAlignment="Top" Width="" Click="Button_Click_3"/>
</Grid>
</Window>

然后做最为关键的一步,对数据类型的转换,我们需要把Student类中的Photo属性也就是图片路径转换为BitmapImage类型,才能显示在UI上。

Converter:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging; namespace BindingImage
{
public class Converter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//若数据库中字段为空,返回默认值
if (value == null)
{
return new BitmapImage(new Uri(@"D:\1.jpg"));
}
return new BitmapImage(new Uri(value.ToString())); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ //图片是不能编辑的,这里就没有必要支持反向转换
throw new NotImplementedException();
}
}
}

剩下的是操作的一些逻辑代码

 using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace BindingImage
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void Window_Loaded(object sender, RoutedEventArgs e)
{ }
private void LoadData()
{ this.gridstudent.DataContext = StudentDAL.GetById(Convert.ToInt32(txtId.Text)); } private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JPG图片|*.jpg|PNGt图片|*.png";
if (ofd.ShowDialog() == true)
{ string filename = ofd.FileName;
imgPhoto.Source = new BitmapImage(new Uri(filename));
Student student = (Student)this.gridstudent.DataContext;
student.Photo = filename;
}
} private void Button_Click_1(object sender, RoutedEventArgs e)
{
Student student = (Student)this.gridstudent.DataContext;
StudentDAL.Update(student);
if (MessageBox.Show("保存完毕", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{ this.Close();
}
} private void Button_Click_2(object sender, RoutedEventArgs e)
{
this.Close();
} private void Button_Click_3(object sender, RoutedEventArgs e)
{
if (txtId.Text == "")
{
return;
}
LoadData(); } }
}

希望对大家对WPF中的绑定知识有所启迪,尤其是数据转换这方面,因为常规的一些数据转换,.NET已经报我们做好,就是这些类似于图片Source属性,CheckBox控件IsChecked属性和我们定义的类属性的转换等等.

WPF中Image控件绑定到自定义类属性的更多相关文章

  1. WPF中一个控件绑定另一个控件的属性

    如同一个Grid中的一个按钮根据另一个按钮的显示与否作出不同的响应: 绑定的时候通过ElementName来指定控件 <Grid Margin="50,130"> &l ...

  2. WPF中ComboBox控件绑定键值对操作

    WPF中下拉框将键值对作为其数据源的具体操作.本实例以枚举类型以及枚举特性描述字符串生成键值对来进行. namespace ViewC { /// <summary> /// View.x ...

  3. WPF中TreeView控件SelectedItemChanged方法的MVVM绑定

    问题描述:左侧treeview控件中点击不同类别的节点时,右侧的页面会显示不同的权限.比如对于My Publications,拥有Modify和Delete两种权限,对于My Subscription ...

  4. WPF中TreeView控件数据绑定和后台动态添加数据(二)

    写在前面:在(一)中,介绍了TreeView控件MVVM模式下数据绑定的方法.在这篇文章中,将总结给节点添加事件的方法,这样说有些不对,总之实现的效果就是点击某个节点,将出现对应于该节点的页面或者数据 ...

  5. WPF中PasswordBox控件的Password属性的数据绑定

    原文:WPF中PasswordBox控件的Password属性的数据绑定 英文原文:http://www.wpftutorial.net/PasswordBox.html 中文原文:http://bl ...

  6. 示例:WPF中Slider控件封装的缓冲播放进度条控件

    原文:示例:WPF中Slider控件封装的缓冲播放进度条控件 一.目的:模仿播放器播放进度条,支持缓冲任务功能 二.进度: 实现类似播放器中带缓存的播放样式(播放区域.缓冲区域.全部区域等样式) 实现 ...

  7. WPF中TreeView控件数据绑定和后台动态添加数据(一)

    数据绑定: 更新内容:补充在MVVM模式上的TreeView控件数据绑定的代码. xaml代码: <TreeView Name="syntaxTree" ItemsSourc ...

  8. WPF中Ribbon控件的使用

    这篇博客将分享如何在WPF程序中使用Ribbon控件.Ribbon可以很大的提高软件的便捷性. 上面截图使Outlook 2010的界面,在Home标签页中,将所属的Menu都平铺的布局,非常容易的可 ...

  9. c#中DropDownList控件绑定枚举数据

    c# asp.net 中DropDownList控件绑定枚举数据 1.枚举(enum)代码: private enum heros { 德玛 = , 皇子 = , 大头 = , 剑圣 = , } 如果 ...

随机推荐

  1. MYSQL基础笔记(四)-数据基本操作

    数据操作 新增数据:两种方案. 1.方案一,给全表字段插入数据,不需要指定字段列表,要求数据的值出现的顺序必须与表中设计的字段出现的顺序一致.凡是非数值数据,到需要使用引号(建议使用单引号)包裹. i ...

  2. Asp.net封装js的类

    using System; using System.Collections.Generic; using System.Text; using System.Web; using System.We ...

  3. JavaScript版几种常见排序算法

    今天发现一篇文章讲“JavaScript版几种常见排序算法”,看着不错,推荐一下原文:http://www.w3cfuns.com/blog-5456021-5404137.html 算法描述: * ...

  4. [改善Java代码]使用valueOf前必须进行校验

    每个枚举都是java.lang.Enum的子类,都可以访问Enum类提供的方法,比如hashCode(),name(),valueOf()等..... 其中valueOf()方法会把一个String类 ...

  5. Mac下批量打包

    两种方式: 第一种:有源码 这种方式比较 简单.利用ant打包.直接shell脚本修改 配置渠道号的文件.我们目前是用的umeng的.在AndroidManifest.xml里.提供一个简单的修改渠道 ...

  6. poj3393[模拟题]

    Lucky and Good Months by Gregorian Calendar Time Limit: 1000MS   Memory Limit: 65536K Total Submissi ...

  7. 如何通过PhpMyAdmin批量删除MYSQL数据库数据表

    使用这个方法前,强烈建议先备份整个数据库.至于怎么备份?你不会么?在本文下方留言吧. 具体方法:复制下面的php执行语句,保存为sql.php文件(注意配置数据库名称.密码.数据表头),通过ftp上传 ...

  8. HDOJ2027统计元音

    统计元音 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submis ...

  9. 日入过百优质消除手游数据分享—萌萌哒包子脸爱消除(游戏开发引擎:libgdx)

    从2014年开始,消除游戏异常火爆,从消除小星星到腾讯的天天消除都赢得了海量用户.目前,各大市场上开心消消乐等游戏依旧火爆.消除游戏一直持续保持着女性和孩子的主流游戏地位.虽然市场上消除游戏种类很多, ...

  10. [zz]安装PostgreSQL数据库(Linux篇)

    0.编译环境 Linux: CentOS 5.5 gcc: 4.1.2 1. 安装PostgreSQL 1) 解压postgresql-9.1.7.tar.bz2 #tar jxvf postgres ...