首先我们定义一个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. Asp.net封装js的类

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

  2. 手把手教你使用Size Class

    在 iOS8 中,我们不用再像以前那样,一个页面新建多个 xib 文件来适配不同类型的屏幕,现在我们可以把各种尺寸屏幕的适配工作放在一个文件中完成,然后可以通过不同类别的 Size 来定制各种尺寸的界 ...

  3. JavaScript中常用函数(入门级)(持续更新)

    本文中枫竹梦介绍一些JavaScript中入门级的常用函数,对于已经过了入门的童鞋可选择略过,都是一些非常实用的函数.如果发现什么问题,欢迎讨论. 问题列表 Q1: 设计一个函数repeatIt(st ...

  4. shareplex的安装&&起停服务(添加新用户)

    一.主机环境   主从类型 系统版本 数据库版本 主机地址 主机名 源数据库 Centos6.4 X86_64 11.2.0.4.0 192.168.3.230 dbshareplex 目的数据库 C ...

  5. C# 委托的几种写法

    class Program    {         delegate string Get(string ss);        delegate string Get2(int i);       ...

  6. Asp.net 后台调用js方法(转)

    1. 用Response.Write方法 代码如下: Response.Write("<script type='text/javascript'>alert("XXX ...

  7. SQL Server的三种物理连接之Loop Join(一)

    Sql Server有三种物理连接Loop Join,Merge Join,Hash Join, 当表之间连接的时候会选择其中之一,不同的连接产生的性能不同,理解这三种物理连接对性能调优有很大帮助. ...

  8. Android从imageview中获得bitmap

    第一种: 使用setDrawingCacheEnabled()和getDrawingCache()这两种方法,第一个是为了设置是否开启缓存,第二个就可以直接获得imageview中的缓存,一般来说需要 ...

  9. VS2012生成不依赖运行时不依赖MFC的MFC程序

    转载请注明来源:http://www.cnblogs.com/xuesongshu/ 1.新建MFC或者Win32工程,全部使用默认设置 2.设置工程属性,展开配置属性,转到:常规~MFC的使用,修改 ...

  10. Unity3D项目实战笔记(5):延时功能的几种实现

    我所做过的系统,分单机版系统(2005年).CS系统(2010年).实时系统(2015年),各个系统均有“延时”功能:定时调度的: 本博客说的是实时系统中的延时功能(基于Unity3D游戏引擎). 在 ...