首先我们定义一个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. Objective-C ,ios,iphone开发基础:快速实现一个简单的图片查看器

    新建一个single view 工程: 关闭ARC , 在.xib视图文件上拖放一个UIImageView  两个UIButton ,一个UISlider ,布局如图. 并为他们连线, UIImage ...

  2. linux -cp/mv

    cp 复制 -r文件夹 -f强制没有提示 mv 移动改名 mv test.py temp/test2.py移动(后面只加路径就是移动.路径+文件名就是移动+改名) 执行mv一般会执行  mv -i交互 ...

  3. CMS垃圾回收与G1垃圾回收

    CMS垃圾回收与G1垃圾回收的比较请参见:http://colobu.com/2015/04/14/G1-Getting-Started/

  4. hihocoder 1066 无间道之并查集

    #1066 : 无间道之并查集 时间限制:20000ms 单点时限:1000ms 内存限制:256MB 描述 这天天气晴朗.阳光明媚.鸟语花香,空气中弥漫着春天的气息……额,说远了,总之,小Hi和小H ...

  5. Myeclipse中tomcat所应用的JDK设置

    Preferences------ > MyElipse ---------- >Servers ----------- > Tomcat-------- >Tomcat 6. ...

  6. Ajax发送FormData对象封装的表单数据

    前端页面: <!doctype html> <html lang="en"> <head> <meta charset="UTF ...

  7. Tomcat - DBCP 配置

    1. Database configuration Create a new test user, a new database and a single test table. Your MySQL ...

  8. Ajax B/S 聊天工具txt文件保存

    打算做一个两个或多个网页之间交流的功能,思路是多个页面聊天的内容存放到一个文件里,每个页面都有提交聊天功能,当提交聊天信息时保存到上面那个文件里, 在每个也页面里放一个定时器,每秒钟获取聊天文件里的记 ...

  9. Android 第三方授权(微信篇)

    0.申请开发者: https://open.weixin.qq.com/cgi-bin/frame?t=home/app_tmpl&lang=zh_CN 1.下载sdk包: https://o ...

  10. ubuntu(16.04.01)学习-day1

    1.修改root用户密码 sudo passwd root 按提示进行设置. 2.从Ubuntu 16.04开始,用户可以实现改变启动器的位置,可以将启动器移到屏幕底部,但是无法移到右边或顶部.打开终 ...