WPF中Image控件绑定到自定义类属性
首先我们定义一个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控件绑定到自定义类属性的更多相关文章
- WPF中一个控件绑定另一个控件的属性
如同一个Grid中的一个按钮根据另一个按钮的显示与否作出不同的响应: 绑定的时候通过ElementName来指定控件 <Grid Margin="50,130"> &l ...
- WPF中ComboBox控件绑定键值对操作
WPF中下拉框将键值对作为其数据源的具体操作.本实例以枚举类型以及枚举特性描述字符串生成键值对来进行. namespace ViewC { /// <summary> /// View.x ...
- WPF中TreeView控件SelectedItemChanged方法的MVVM绑定
问题描述:左侧treeview控件中点击不同类别的节点时,右侧的页面会显示不同的权限.比如对于My Publications,拥有Modify和Delete两种权限,对于My Subscription ...
- WPF中TreeView控件数据绑定和后台动态添加数据(二)
写在前面:在(一)中,介绍了TreeView控件MVVM模式下数据绑定的方法.在这篇文章中,将总结给节点添加事件的方法,这样说有些不对,总之实现的效果就是点击某个节点,将出现对应于该节点的页面或者数据 ...
- WPF中PasswordBox控件的Password属性的数据绑定
原文:WPF中PasswordBox控件的Password属性的数据绑定 英文原文:http://www.wpftutorial.net/PasswordBox.html 中文原文:http://bl ...
- 示例:WPF中Slider控件封装的缓冲播放进度条控件
原文:示例:WPF中Slider控件封装的缓冲播放进度条控件 一.目的:模仿播放器播放进度条,支持缓冲任务功能 二.进度: 实现类似播放器中带缓存的播放样式(播放区域.缓冲区域.全部区域等样式) 实现 ...
- WPF中TreeView控件数据绑定和后台动态添加数据(一)
数据绑定: 更新内容:补充在MVVM模式上的TreeView控件数据绑定的代码. xaml代码: <TreeView Name="syntaxTree" ItemsSourc ...
- WPF中Ribbon控件的使用
这篇博客将分享如何在WPF程序中使用Ribbon控件.Ribbon可以很大的提高软件的便捷性. 上面截图使Outlook 2010的界面,在Home标签页中,将所属的Menu都平铺的布局,非常容易的可 ...
- c#中DropDownList控件绑定枚举数据
c# asp.net 中DropDownList控件绑定枚举数据 1.枚举(enum)代码: private enum heros { 德玛 = , 皇子 = , 大头 = , 剑圣 = , } 如果 ...
随机推荐
- ArcGIS Server 10.2 实战(五)spatial etl tool 格式转换服务
上不同的地图服务平台对地图文件格式的要求多种多样,arcgis使用的文件很难应用于其他平台上,因此需要有格式转换的服务来克服这种使用不同平台带来的麻烦,下面以TIFF格式转GEOTIFF格式为例. 首 ...
- linux别名
alias: alias cdn ='cd /opt/lammp' [root@besttest /]# cdn[root@besttest lampp]# 如果想永久生效写进root/.bash ...
- plsql常用快捷键
plsql使用技巧 1.类SQL PLUS窗口:File->New->Command Window,这个类似于oracle的客户端工具sql plus,但比它好用多了. 2.设置关键字自动 ...
- 【模拟,时针分针秒针两两夹角】【没有跳坑好兴奋】hdu - 5387 (多校#8 1008)
算是最好写的一道题了吧,最近模拟没手感,一次过也是很鸡冻o(* ̄▽ ̄*)o 注意事项都在代码里,没有跳坑也不清楚坑点在哪~ #include<cstdio> #include<cst ...
- poj 2942 点的双连通分量
思路: 对于该图,直接用建图貌似没法解,所以也很容易想到建补图,这样存在边的两个点就能再圆桌上做一起.也就将问题转化为对双连通分量中是否存在奇圈了. 我们将每次查询的边保存在stack中,当遇到关键点 ...
- 在Visual Studio 的 “一般处理程序 ” .ashx 文件中如何创建Session 对象
只需要继承这个接口即可实现创建Session对象. IHttpHandler,System.Web.SessionState.IHttpSessionState 代码示例: public class ...
- ActiveMQ(5.10.0) - Spring Support
Maven Dependency: <dependencies> <dependency> <groupId>org.apache.activemq</gro ...
- Remoting的入门教程
注:<网摘自http://www.codesky.net/article/200411/48322.html> 基本原理 当客户端创建远程RemotableClass的一个实例,.NET框 ...
- git常用命令行
查看.添加.提交.删除.找回,重置修改文件 git help <command> # 显示command的help git show # 显示某次提交的内容 git show $id gi ...
- SignalR 2.0入门
下载已完成的项目 本教程展示如何使用那么 SignalR 创建一个实时聊天应用程序.你会那么 SignalR 添加一个空的 ASP.NET web 应用程序,创建一个 HTML 页面发送并显示消息. ...