WPF中Image控件绑定到自定义类属性

时间:2021-09-21 15:32:38

首先我们定义一个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层:

WPF中Image控件绑定到自定义类属性

在学生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属性和我们定义的类属性的转换等等.